pdf.combined.js 1.4 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788
  1. /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
  3. /* Copyright 2012 Mozilla Foundation
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /*jshint globalstrict: false */
  18. /* globals PDFJS */
  19. // Initializing PDFJS global object (if still undefined)
  20. if (typeof PDFJS === 'undefined') {
  21. (typeof window !== 'undefined' ? window : this).PDFJS = {};
  22. }
  23. PDFJS.version = '1.1.233';
  24. PDFJS.build = '0a744fb';
  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 (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.errors) {
  223. console.log('Error: ' + msg);
  224. console.log(backtrace());
  225. }
  226. UnsupportedManager.notify(UNSUPPORTED_FEATURES.unknown);
  227. throw new Error(msg);
  228. }
  229. function backtrace() {
  230. try {
  231. throw new Error();
  232. } catch (e) {
  233. return e.stack ? e.stack.split('\n').slice(2).join('\n') : '';
  234. }
  235. }
  236. function assert(cond, msg) {
  237. if (!cond) {
  238. error(msg);
  239. }
  240. }
  241. var UNSUPPORTED_FEATURES = PDFJS.UNSUPPORTED_FEATURES = {
  242. unknown: 'unknown',
  243. forms: 'forms',
  244. javaScript: 'javaScript',
  245. smask: 'smask',
  246. shadingPattern: 'shadingPattern',
  247. font: 'font'
  248. };
  249. var UnsupportedManager = PDFJS.UnsupportedManager =
  250. (function UnsupportedManagerClosure() {
  251. var listeners = [];
  252. return {
  253. listen: function (cb) {
  254. listeners.push(cb);
  255. },
  256. notify: function (featureId) {
  257. warn('Unsupported feature "' + featureId + '"');
  258. for (var i = 0, ii = listeners.length; i < ii; i++) {
  259. listeners[i](featureId);
  260. }
  261. }
  262. };
  263. })();
  264. // Combines two URLs. The baseUrl shall be absolute URL. If the url is an
  265. // absolute URL, it will be returned as is.
  266. function combineUrl(baseUrl, url) {
  267. if (!url) {
  268. return baseUrl;
  269. }
  270. if (/^[a-z][a-z0-9+\-.]*:/i.test(url)) {
  271. return url;
  272. }
  273. var i;
  274. if (url.charAt(0) === '/') {
  275. // absolute path
  276. i = baseUrl.indexOf('://');
  277. if (url.charAt(1) === '/') {
  278. ++i;
  279. } else {
  280. i = baseUrl.indexOf('/', i + 3);
  281. }
  282. return baseUrl.substring(0, i) + url;
  283. } else {
  284. // relative path
  285. var pathLength = baseUrl.length;
  286. i = baseUrl.lastIndexOf('#');
  287. pathLength = i >= 0 ? i : pathLength;
  288. i = baseUrl.lastIndexOf('?', pathLength);
  289. pathLength = i >= 0 ? i : pathLength;
  290. var prefixLength = baseUrl.lastIndexOf('/', pathLength);
  291. return baseUrl.substring(0, prefixLength + 1) + url;
  292. }
  293. }
  294. // Validates if URL is safe and allowed, e.g. to avoid XSS.
  295. function isValidUrl(url, allowRelative) {
  296. if (!url) {
  297. return false;
  298. }
  299. // RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1)
  300. // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
  301. var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url);
  302. if (!protocol) {
  303. return allowRelative;
  304. }
  305. protocol = protocol[0].toLowerCase();
  306. switch (protocol) {
  307. case 'http':
  308. case 'https':
  309. case 'ftp':
  310. case 'mailto':
  311. case 'tel':
  312. return true;
  313. default:
  314. return false;
  315. }
  316. }
  317. PDFJS.isValidUrl = isValidUrl;
  318. function shadow(obj, prop, value) {
  319. Object.defineProperty(obj, prop, { value: value,
  320. enumerable: true,
  321. configurable: true,
  322. writable: false });
  323. return value;
  324. }
  325. PDFJS.shadow = shadow;
  326. var PasswordResponses = PDFJS.PasswordResponses = {
  327. NEED_PASSWORD: 1,
  328. INCORRECT_PASSWORD: 2
  329. };
  330. var PasswordException = (function PasswordExceptionClosure() {
  331. function PasswordException(msg, code) {
  332. this.name = 'PasswordException';
  333. this.message = msg;
  334. this.code = code;
  335. }
  336. PasswordException.prototype = new Error();
  337. PasswordException.constructor = PasswordException;
  338. return PasswordException;
  339. })();
  340. PDFJS.PasswordException = PasswordException;
  341. var UnknownErrorException = (function UnknownErrorExceptionClosure() {
  342. function UnknownErrorException(msg, details) {
  343. this.name = 'UnknownErrorException';
  344. this.message = msg;
  345. this.details = details;
  346. }
  347. UnknownErrorException.prototype = new Error();
  348. UnknownErrorException.constructor = UnknownErrorException;
  349. return UnknownErrorException;
  350. })();
  351. PDFJS.UnknownErrorException = UnknownErrorException;
  352. var InvalidPDFException = (function InvalidPDFExceptionClosure() {
  353. function InvalidPDFException(msg) {
  354. this.name = 'InvalidPDFException';
  355. this.message = msg;
  356. }
  357. InvalidPDFException.prototype = new Error();
  358. InvalidPDFException.constructor = InvalidPDFException;
  359. return InvalidPDFException;
  360. })();
  361. PDFJS.InvalidPDFException = InvalidPDFException;
  362. var MissingPDFException = (function MissingPDFExceptionClosure() {
  363. function MissingPDFException(msg) {
  364. this.name = 'MissingPDFException';
  365. this.message = msg;
  366. }
  367. MissingPDFException.prototype = new Error();
  368. MissingPDFException.constructor = MissingPDFException;
  369. return MissingPDFException;
  370. })();
  371. PDFJS.MissingPDFException = MissingPDFException;
  372. var UnexpectedResponseException =
  373. (function UnexpectedResponseExceptionClosure() {
  374. function UnexpectedResponseException(msg, status) {
  375. this.name = 'UnexpectedResponseException';
  376. this.message = msg;
  377. this.status = status;
  378. }
  379. UnexpectedResponseException.prototype = new Error();
  380. UnexpectedResponseException.constructor = UnexpectedResponseException;
  381. return UnexpectedResponseException;
  382. })();
  383. PDFJS.UnexpectedResponseException = UnexpectedResponseException;
  384. var NotImplementedException = (function NotImplementedExceptionClosure() {
  385. function NotImplementedException(msg) {
  386. this.message = msg;
  387. }
  388. NotImplementedException.prototype = new Error();
  389. NotImplementedException.prototype.name = 'NotImplementedException';
  390. NotImplementedException.constructor = NotImplementedException;
  391. return NotImplementedException;
  392. })();
  393. var MissingDataException = (function MissingDataExceptionClosure() {
  394. function MissingDataException(begin, end) {
  395. this.begin = begin;
  396. this.end = end;
  397. this.message = 'Missing data [' + begin + ', ' + end + ')';
  398. }
  399. MissingDataException.prototype = new Error();
  400. MissingDataException.prototype.name = 'MissingDataException';
  401. MissingDataException.constructor = MissingDataException;
  402. return MissingDataException;
  403. })();
  404. var XRefParseException = (function XRefParseExceptionClosure() {
  405. function XRefParseException(msg) {
  406. this.message = msg;
  407. }
  408. XRefParseException.prototype = new Error();
  409. XRefParseException.prototype.name = 'XRefParseException';
  410. XRefParseException.constructor = XRefParseException;
  411. return XRefParseException;
  412. })();
  413. function bytesToString(bytes) {
  414. assert(bytes !== null && typeof bytes === 'object' &&
  415. bytes.length !== undefined, 'Invalid argument for bytesToString');
  416. var length = bytes.length;
  417. var MAX_ARGUMENT_COUNT = 8192;
  418. if (length < MAX_ARGUMENT_COUNT) {
  419. return String.fromCharCode.apply(null, bytes);
  420. }
  421. var strBuf = [];
  422. for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
  423. var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
  424. var chunk = bytes.subarray(i, chunkEnd);
  425. strBuf.push(String.fromCharCode.apply(null, chunk));
  426. }
  427. return strBuf.join('');
  428. }
  429. function stringToBytes(str) {
  430. assert(typeof str === 'string', 'Invalid argument for stringToBytes');
  431. var length = str.length;
  432. var bytes = new Uint8Array(length);
  433. for (var i = 0; i < length; ++i) {
  434. bytes[i] = str.charCodeAt(i) & 0xFF;
  435. }
  436. return bytes;
  437. }
  438. function string32(value) {
  439. return String.fromCharCode((value >> 24) & 0xff, (value >> 16) & 0xff,
  440. (value >> 8) & 0xff, value & 0xff);
  441. }
  442. function log2(x) {
  443. var n = 1, i = 0;
  444. while (x > n) {
  445. n <<= 1;
  446. i++;
  447. }
  448. return i;
  449. }
  450. function readInt8(data, start) {
  451. return (data[start] << 24) >> 24;
  452. }
  453. function readUint16(data, offset) {
  454. return (data[offset] << 8) | data[offset + 1];
  455. }
  456. function readUint32(data, offset) {
  457. return ((data[offset] << 24) | (data[offset + 1] << 16) |
  458. (data[offset + 2] << 8) | data[offset + 3]) >>> 0;
  459. }
  460. // Lazy test the endianness of the platform
  461. // NOTE: This will be 'true' for simulated TypedArrays
  462. function isLittleEndian() {
  463. var buffer8 = new Uint8Array(2);
  464. buffer8[0] = 1;
  465. var buffer16 = new Uint16Array(buffer8.buffer);
  466. return (buffer16[0] === 1);
  467. }
  468. Object.defineProperty(PDFJS, 'isLittleEndian', {
  469. configurable: true,
  470. get: function PDFJS_isLittleEndian() {
  471. return shadow(PDFJS, 'isLittleEndian', isLittleEndian());
  472. }
  473. });
  474. // Lazy test if the userAgent support CanvasTypedArrays
  475. function hasCanvasTypedArrays() {
  476. var canvas = document.createElement('canvas');
  477. canvas.width = canvas.height = 1;
  478. var ctx = canvas.getContext('2d');
  479. var imageData = ctx.createImageData(1, 1);
  480. return (typeof imageData.data.buffer !== 'undefined');
  481. }
  482. Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', {
  483. configurable: true,
  484. get: function PDFJS_hasCanvasTypedArrays() {
  485. return shadow(PDFJS, 'hasCanvasTypedArrays', hasCanvasTypedArrays());
  486. }
  487. });
  488. var Uint32ArrayView = (function Uint32ArrayViewClosure() {
  489. function Uint32ArrayView(buffer, length) {
  490. this.buffer = buffer;
  491. this.byteLength = buffer.length;
  492. this.length = length === undefined ? (this.byteLength >> 2) : length;
  493. ensureUint32ArrayViewProps(this.length);
  494. }
  495. Uint32ArrayView.prototype = Object.create(null);
  496. var uint32ArrayViewSetters = 0;
  497. function createUint32ArrayProp(index) {
  498. return {
  499. get: function () {
  500. var buffer = this.buffer, offset = index << 2;
  501. return (buffer[offset] | (buffer[offset + 1] << 8) |
  502. (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0;
  503. },
  504. set: function (value) {
  505. var buffer = this.buffer, offset = index << 2;
  506. buffer[offset] = value & 255;
  507. buffer[offset + 1] = (value >> 8) & 255;
  508. buffer[offset + 2] = (value >> 16) & 255;
  509. buffer[offset + 3] = (value >>> 24) & 255;
  510. }
  511. };
  512. }
  513. function ensureUint32ArrayViewProps(length) {
  514. while (uint32ArrayViewSetters < length) {
  515. Object.defineProperty(Uint32ArrayView.prototype,
  516. uint32ArrayViewSetters,
  517. createUint32ArrayProp(uint32ArrayViewSetters));
  518. uint32ArrayViewSetters++;
  519. }
  520. }
  521. return Uint32ArrayView;
  522. })();
  523. var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
  524. var Util = PDFJS.Util = (function UtilClosure() {
  525. function Util() {}
  526. var rgbBuf = ['rgb(', 0, ',', 0, ',', 0, ')'];
  527. // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids
  528. // creating many intermediate strings.
  529. Util.makeCssRgb = function Util_makeCssRgb(r, g, b) {
  530. rgbBuf[1] = r;
  531. rgbBuf[3] = g;
  532. rgbBuf[5] = b;
  533. return rgbBuf.join('');
  534. };
  535. // Concatenates two transformation matrices together and returns the result.
  536. Util.transform = function Util_transform(m1, m2) {
  537. return [
  538. m1[0] * m2[0] + m1[2] * m2[1],
  539. m1[1] * m2[0] + m1[3] * m2[1],
  540. m1[0] * m2[2] + m1[2] * m2[3],
  541. m1[1] * m2[2] + m1[3] * m2[3],
  542. m1[0] * m2[4] + m1[2] * m2[5] + m1[4],
  543. m1[1] * m2[4] + m1[3] * m2[5] + m1[5]
  544. ];
  545. };
  546. // For 2d affine transforms
  547. Util.applyTransform = function Util_applyTransform(p, m) {
  548. var xt = p[0] * m[0] + p[1] * m[2] + m[4];
  549. var yt = p[0] * m[1] + p[1] * m[3] + m[5];
  550. return [xt, yt];
  551. };
  552. Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {
  553. var d = m[0] * m[3] - m[1] * m[2];
  554. var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  555. var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  556. return [xt, yt];
  557. };
  558. // Applies the transform to the rectangle and finds the minimum axially
  559. // aligned bounding box.
  560. Util.getAxialAlignedBoundingBox =
  561. function Util_getAxialAlignedBoundingBox(r, m) {
  562. var p1 = Util.applyTransform(r, m);
  563. var p2 = Util.applyTransform(r.slice(2, 4), m);
  564. var p3 = Util.applyTransform([r[0], r[3]], m);
  565. var p4 = Util.applyTransform([r[2], r[1]], m);
  566. return [
  567. Math.min(p1[0], p2[0], p3[0], p4[0]),
  568. Math.min(p1[1], p2[1], p3[1], p4[1]),
  569. Math.max(p1[0], p2[0], p3[0], p4[0]),
  570. Math.max(p1[1], p2[1], p3[1], p4[1])
  571. ];
  572. };
  573. Util.inverseTransform = function Util_inverseTransform(m) {
  574. var d = m[0] * m[3] - m[1] * m[2];
  575. return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d,
  576. (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
  577. };
  578. // Apply a generic 3d matrix M on a 3-vector v:
  579. // | a b c | | X |
  580. // | d e f | x | Y |
  581. // | g h i | | Z |
  582. // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],
  583. // with v as [X,Y,Z]
  584. Util.apply3dTransform = function Util_apply3dTransform(m, v) {
  585. return [
  586. m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
  587. m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
  588. m[6] * v[0] + m[7] * v[1] + m[8] * v[2]
  589. ];
  590. };
  591. // This calculation uses Singular Value Decomposition.
  592. // The SVD can be represented with formula A = USV. We are interested in the
  593. // matrix S here because it represents the scale values.
  594. Util.singularValueDecompose2dScale =
  595. function Util_singularValueDecompose2dScale(m) {
  596. var transpose = [m[0], m[2], m[1], m[3]];
  597. // Multiply matrix m with its transpose.
  598. var a = m[0] * transpose[0] + m[1] * transpose[2];
  599. var b = m[0] * transpose[1] + m[1] * transpose[3];
  600. var c = m[2] * transpose[0] + m[3] * transpose[2];
  601. var d = m[2] * transpose[1] + m[3] * transpose[3];
  602. // Solve the second degree polynomial to get roots.
  603. var first = (a + d) / 2;
  604. var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;
  605. var sx = first + second || 1;
  606. var sy = first - second || 1;
  607. // Scale values are the square roots of the eigenvalues.
  608. return [Math.sqrt(sx), Math.sqrt(sy)];
  609. };
  610. // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)
  611. // For coordinate systems whose origin lies in the bottom-left, this
  612. // means normalization to (BL,TR) ordering. For systems with origin in the
  613. // top-left, this means (TL,BR) ordering.
  614. Util.normalizeRect = function Util_normalizeRect(rect) {
  615. var r = rect.slice(0); // clone rect
  616. if (rect[0] > rect[2]) {
  617. r[0] = rect[2];
  618. r[2] = rect[0];
  619. }
  620. if (rect[1] > rect[3]) {
  621. r[1] = rect[3];
  622. r[3] = rect[1];
  623. }
  624. return r;
  625. };
  626. // Returns a rectangle [x1, y1, x2, y2] corresponding to the
  627. // intersection of rect1 and rect2. If no intersection, returns 'false'
  628. // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]
  629. Util.intersect = function Util_intersect(rect1, rect2) {
  630. function compare(a, b) {
  631. return a - b;
  632. }
  633. // Order points along the axes
  634. var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare),
  635. orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare),
  636. result = [];
  637. rect1 = Util.normalizeRect(rect1);
  638. rect2 = Util.normalizeRect(rect2);
  639. // X: first and second points belong to different rectangles?
  640. if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) ||
  641. (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) {
  642. // Intersection must be between second and third points
  643. result[0] = orderedX[1];
  644. result[2] = orderedX[2];
  645. } else {
  646. return false;
  647. }
  648. // Y: first and second points belong to different rectangles?
  649. if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) ||
  650. (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) {
  651. // Intersection must be between second and third points
  652. result[1] = orderedY[1];
  653. result[3] = orderedY[2];
  654. } else {
  655. return false;
  656. }
  657. return result;
  658. };
  659. Util.sign = function Util_sign(num) {
  660. return num < 0 ? -1 : 1;
  661. };
  662. Util.appendToArray = function Util_appendToArray(arr1, arr2) {
  663. Array.prototype.push.apply(arr1, arr2);
  664. };
  665. Util.prependToArray = function Util_prependToArray(arr1, arr2) {
  666. Array.prototype.unshift.apply(arr1, arr2);
  667. };
  668. Util.extendObj = function extendObj(obj1, obj2) {
  669. for (var key in obj2) {
  670. obj1[key] = obj2[key];
  671. }
  672. };
  673. Util.getInheritableProperty = function Util_getInheritableProperty(dict,
  674. name) {
  675. while (dict && !dict.has(name)) {
  676. dict = dict.get('Parent');
  677. }
  678. if (!dict) {
  679. return null;
  680. }
  681. return dict.get(name);
  682. };
  683. Util.inherit = function Util_inherit(sub, base, prototype) {
  684. sub.prototype = Object.create(base.prototype);
  685. sub.prototype.constructor = sub;
  686. for (var prop in prototype) {
  687. sub.prototype[prop] = prototype[prop];
  688. }
  689. };
  690. Util.loadScript = function Util_loadScript(src, callback) {
  691. var script = document.createElement('script');
  692. var loaded = false;
  693. script.setAttribute('src', src);
  694. if (callback) {
  695. script.onload = function() {
  696. if (!loaded) {
  697. callback();
  698. }
  699. loaded = true;
  700. };
  701. }
  702. document.getElementsByTagName('head')[0].appendChild(script);
  703. };
  704. return Util;
  705. })();
  706. /**
  707. * PDF page viewport created based on scale, rotation and offset.
  708. * @class
  709. * @alias PDFJS.PageViewport
  710. */
  711. var PageViewport = PDFJS.PageViewport = (function PageViewportClosure() {
  712. /**
  713. * @constructor
  714. * @private
  715. * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates.
  716. * @param scale {number} scale of the viewport.
  717. * @param rotation {number} rotations of the viewport in degrees.
  718. * @param offsetX {number} offset X
  719. * @param offsetY {number} offset Y
  720. * @param dontFlip {boolean} if true, axis Y will not be flipped.
  721. */
  722. function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) {
  723. this.viewBox = viewBox;
  724. this.scale = scale;
  725. this.rotation = rotation;
  726. this.offsetX = offsetX;
  727. this.offsetY = offsetY;
  728. // creating transform to convert pdf coordinate system to the normal
  729. // canvas like coordinates taking in account scale and rotation
  730. var centerX = (viewBox[2] + viewBox[0]) / 2;
  731. var centerY = (viewBox[3] + viewBox[1]) / 2;
  732. var rotateA, rotateB, rotateC, rotateD;
  733. rotation = rotation % 360;
  734. rotation = rotation < 0 ? rotation + 360 : rotation;
  735. switch (rotation) {
  736. case 180:
  737. rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1;
  738. break;
  739. case 90:
  740. rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0;
  741. break;
  742. case 270:
  743. rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0;
  744. break;
  745. //case 0:
  746. default:
  747. rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1;
  748. break;
  749. }
  750. if (dontFlip) {
  751. rotateC = -rotateC; rotateD = -rotateD;
  752. }
  753. var offsetCanvasX, offsetCanvasY;
  754. var width, height;
  755. if (rotateA === 0) {
  756. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  757. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  758. width = Math.abs(viewBox[3] - viewBox[1]) * scale;
  759. height = Math.abs(viewBox[2] - viewBox[0]) * scale;
  760. } else {
  761. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  762. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  763. width = Math.abs(viewBox[2] - viewBox[0]) * scale;
  764. height = Math.abs(viewBox[3] - viewBox[1]) * scale;
  765. }
  766. // creating transform for the following operations:
  767. // translate(-centerX, -centerY), rotate and flip vertically,
  768. // scale, and translate(offsetCanvasX, offsetCanvasY)
  769. this.transform = [
  770. rotateA * scale,
  771. rotateB * scale,
  772. rotateC * scale,
  773. rotateD * scale,
  774. offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,
  775. offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY
  776. ];
  777. this.width = width;
  778. this.height = height;
  779. this.fontScale = scale;
  780. }
  781. PageViewport.prototype = /** @lends PDFJS.PageViewport.prototype */ {
  782. /**
  783. * Clones viewport with additional properties.
  784. * @param args {Object} (optional) If specified, may contain the 'scale' or
  785. * 'rotation' properties to override the corresponding properties in
  786. * the cloned viewport.
  787. * @returns {PDFJS.PageViewport} Cloned viewport.
  788. */
  789. clone: function PageViewPort_clone(args) {
  790. args = args || {};
  791. var scale = 'scale' in args ? args.scale : this.scale;
  792. var rotation = 'rotation' in args ? args.rotation : this.rotation;
  793. return new PageViewport(this.viewBox.slice(), scale, rotation,
  794. this.offsetX, this.offsetY, args.dontFlip);
  795. },
  796. /**
  797. * Converts PDF point to the viewport coordinates. For examples, useful for
  798. * converting PDF location into canvas pixel coordinates.
  799. * @param x {number} X coordinate.
  800. * @param y {number} Y coordinate.
  801. * @returns {Object} Object that contains 'x' and 'y' properties of the
  802. * point in the viewport coordinate space.
  803. * @see {@link convertToPdfPoint}
  804. * @see {@link convertToViewportRectangle}
  805. */
  806. convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) {
  807. return Util.applyTransform([x, y], this.transform);
  808. },
  809. /**
  810. * Converts PDF rectangle to the viewport coordinates.
  811. * @param rect {Array} xMin, yMin, xMax and yMax coordinates.
  812. * @returns {Array} Contains corresponding coordinates of the rectangle
  813. * in the viewport coordinate space.
  814. * @see {@link convertToViewportPoint}
  815. */
  816. convertToViewportRectangle:
  817. function PageViewport_convertToViewportRectangle(rect) {
  818. var tl = Util.applyTransform([rect[0], rect[1]], this.transform);
  819. var br = Util.applyTransform([rect[2], rect[3]], this.transform);
  820. return [tl[0], tl[1], br[0], br[1]];
  821. },
  822. /**
  823. * Converts viewport coordinates to the PDF location. For examples, useful
  824. * for converting canvas pixel location into PDF one.
  825. * @param x {number} X coordinate.
  826. * @param y {number} Y coordinate.
  827. * @returns {Object} Object that contains 'x' and 'y' properties of the
  828. * point in the PDF coordinate space.
  829. * @see {@link convertToViewportPoint}
  830. */
  831. convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) {
  832. return Util.applyInverseTransform([x, y], this.transform);
  833. }
  834. };
  835. return PageViewport;
  836. })();
  837. var PDFStringTranslateTable = [
  838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  839. 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0,
  841. 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,
  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, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014,
  844. 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C,
  845. 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160,
  846. 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC
  847. ];
  848. function stringToPDFString(str) {
  849. var i, n = str.length, strBuf = [];
  850. if (str[0] === '\xFE' && str[1] === '\xFF') {
  851. // UTF16BE BOM
  852. for (i = 2; i < n; i += 2) {
  853. strBuf.push(String.fromCharCode(
  854. (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1)));
  855. }
  856. } else {
  857. for (i = 0; i < n; ++i) {
  858. var code = PDFStringTranslateTable[str.charCodeAt(i)];
  859. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  860. }
  861. }
  862. return strBuf.join('');
  863. }
  864. function stringToUTF8String(str) {
  865. return decodeURIComponent(escape(str));
  866. }
  867. function utf8StringToString(str) {
  868. return unescape(encodeURIComponent(str));
  869. }
  870. function isEmptyObj(obj) {
  871. for (var key in obj) {
  872. return false;
  873. }
  874. return true;
  875. }
  876. function isBool(v) {
  877. return typeof v === 'boolean';
  878. }
  879. function isInt(v) {
  880. return typeof v === 'number' && ((v | 0) === v);
  881. }
  882. function isNum(v) {
  883. return typeof v === 'number';
  884. }
  885. function isString(v) {
  886. return typeof v === 'string';
  887. }
  888. function isName(v) {
  889. return v instanceof Name;
  890. }
  891. function isCmd(v, cmd) {
  892. return v instanceof Cmd && (cmd === undefined || v.cmd === cmd);
  893. }
  894. function isDict(v, type) {
  895. if (!(v instanceof Dict)) {
  896. return false;
  897. }
  898. if (!type) {
  899. return true;
  900. }
  901. var dictType = v.get('Type');
  902. return isName(dictType) && dictType.name === type;
  903. }
  904. function isArray(v) {
  905. return v instanceof Array;
  906. }
  907. function isStream(v) {
  908. return typeof v === 'object' && v !== null && v.getBytes !== undefined;
  909. }
  910. function isArrayBuffer(v) {
  911. return typeof v === 'object' && v !== null && v.byteLength !== undefined;
  912. }
  913. function isRef(v) {
  914. return v instanceof Ref;
  915. }
  916. /**
  917. * Promise Capability object.
  918. *
  919. * @typedef {Object} PromiseCapability
  920. * @property {Promise} promise - A promise object.
  921. * @property {function} resolve - Fullfills the promise.
  922. * @property {function} reject - Rejects the promise.
  923. */
  924. /**
  925. * Creates a promise capability object.
  926. * @alias PDFJS.createPromiseCapability
  927. *
  928. * @return {PromiseCapability} A capability object contains:
  929. * - a Promise, resolve and reject methods.
  930. */
  931. function createPromiseCapability() {
  932. var capability = {};
  933. capability.promise = new Promise(function (resolve, reject) {
  934. capability.resolve = resolve;
  935. capability.reject = reject;
  936. });
  937. return capability;
  938. }
  939. PDFJS.createPromiseCapability = createPromiseCapability;
  940. /**
  941. * Polyfill for Promises:
  942. * The following promise implementation tries to generally implement the
  943. * Promise/A+ spec. Some notable differences from other promise libaries are:
  944. * - There currently isn't a seperate deferred and promise object.
  945. * - Unhandled rejections eventually show an error if they aren't handled.
  946. *
  947. * Based off of the work in:
  948. * https://bugzilla.mozilla.org/show_bug.cgi?id=810490
  949. */
  950. (function PromiseClosure() {
  951. if (globalScope.Promise) {
  952. // Promises existing in the DOM/Worker, checking presence of all/resolve
  953. if (typeof globalScope.Promise.all !== 'function') {
  954. globalScope.Promise.all = function (iterable) {
  955. var count = 0, results = [], resolve, reject;
  956. var promise = new globalScope.Promise(function (resolve_, reject_) {
  957. resolve = resolve_;
  958. reject = reject_;
  959. });
  960. iterable.forEach(function (p, i) {
  961. count++;
  962. p.then(function (result) {
  963. results[i] = result;
  964. count--;
  965. if (count === 0) {
  966. resolve(results);
  967. }
  968. }, reject);
  969. });
  970. if (count === 0) {
  971. resolve(results);
  972. }
  973. return promise;
  974. };
  975. }
  976. if (typeof globalScope.Promise.resolve !== 'function') {
  977. globalScope.Promise.resolve = function (value) {
  978. return new globalScope.Promise(function (resolve) { resolve(value); });
  979. };
  980. }
  981. if (typeof globalScope.Promise.reject !== 'function') {
  982. globalScope.Promise.reject = function (reason) {
  983. return new globalScope.Promise(function (resolve, reject) {
  984. reject(reason);
  985. });
  986. };
  987. }
  988. if (typeof globalScope.Promise.prototype.catch !== 'function') {
  989. globalScope.Promise.prototype.catch = function (onReject) {
  990. return globalScope.Promise.prototype.then(undefined, onReject);
  991. };
  992. }
  993. return;
  994. }
  995. var STATUS_PENDING = 0;
  996. var STATUS_RESOLVED = 1;
  997. var STATUS_REJECTED = 2;
  998. // In an attempt to avoid silent exceptions, unhandled rejections are
  999. // tracked and if they aren't handled in a certain amount of time an
  1000. // error is logged.
  1001. var REJECTION_TIMEOUT = 500;
  1002. var HandlerManager = {
  1003. handlers: [],
  1004. running: false,
  1005. unhandledRejections: [],
  1006. pendingRejectionCheck: false,
  1007. scheduleHandlers: function scheduleHandlers(promise) {
  1008. if (promise._status === STATUS_PENDING) {
  1009. return;
  1010. }
  1011. this.handlers = this.handlers.concat(promise._handlers);
  1012. promise._handlers = [];
  1013. if (this.running) {
  1014. return;
  1015. }
  1016. this.running = true;
  1017. setTimeout(this.runHandlers.bind(this), 0);
  1018. },
  1019. runHandlers: function runHandlers() {
  1020. var RUN_TIMEOUT = 1; // ms
  1021. var timeoutAt = Date.now() + RUN_TIMEOUT;
  1022. while (this.handlers.length > 0) {
  1023. var handler = this.handlers.shift();
  1024. var nextStatus = handler.thisPromise._status;
  1025. var nextValue = handler.thisPromise._value;
  1026. try {
  1027. if (nextStatus === STATUS_RESOLVED) {
  1028. if (typeof handler.onResolve === 'function') {
  1029. nextValue = handler.onResolve(nextValue);
  1030. }
  1031. } else if (typeof handler.onReject === 'function') {
  1032. nextValue = handler.onReject(nextValue);
  1033. nextStatus = STATUS_RESOLVED;
  1034. if (handler.thisPromise._unhandledRejection) {
  1035. this.removeUnhandeledRejection(handler.thisPromise);
  1036. }
  1037. }
  1038. } catch (ex) {
  1039. nextStatus = STATUS_REJECTED;
  1040. nextValue = ex;
  1041. }
  1042. handler.nextPromise._updateStatus(nextStatus, nextValue);
  1043. if (Date.now() >= timeoutAt) {
  1044. break;
  1045. }
  1046. }
  1047. if (this.handlers.length > 0) {
  1048. setTimeout(this.runHandlers.bind(this), 0);
  1049. return;
  1050. }
  1051. this.running = false;
  1052. },
  1053. addUnhandledRejection: function addUnhandledRejection(promise) {
  1054. this.unhandledRejections.push({
  1055. promise: promise,
  1056. time: Date.now()
  1057. });
  1058. this.scheduleRejectionCheck();
  1059. },
  1060. removeUnhandeledRejection: function removeUnhandeledRejection(promise) {
  1061. promise._unhandledRejection = false;
  1062. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1063. if (this.unhandledRejections[i].promise === promise) {
  1064. this.unhandledRejections.splice(i);
  1065. i--;
  1066. }
  1067. }
  1068. },
  1069. scheduleRejectionCheck: function scheduleRejectionCheck() {
  1070. if (this.pendingRejectionCheck) {
  1071. return;
  1072. }
  1073. this.pendingRejectionCheck = true;
  1074. setTimeout(function rejectionCheck() {
  1075. this.pendingRejectionCheck = false;
  1076. var now = Date.now();
  1077. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1078. if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) {
  1079. var unhandled = this.unhandledRejections[i].promise._value;
  1080. var msg = 'Unhandled rejection: ' + unhandled;
  1081. if (unhandled.stack) {
  1082. msg += '\n' + unhandled.stack;
  1083. }
  1084. warn(msg);
  1085. this.unhandledRejections.splice(i);
  1086. i--;
  1087. }
  1088. }
  1089. if (this.unhandledRejections.length) {
  1090. this.scheduleRejectionCheck();
  1091. }
  1092. }.bind(this), REJECTION_TIMEOUT);
  1093. }
  1094. };
  1095. function Promise(resolver) {
  1096. this._status = STATUS_PENDING;
  1097. this._handlers = [];
  1098. try {
  1099. resolver.call(this, this._resolve.bind(this), this._reject.bind(this));
  1100. } catch (e) {
  1101. this._reject(e);
  1102. }
  1103. }
  1104. /**
  1105. * Builds a promise that is resolved when all the passed in promises are
  1106. * resolved.
  1107. * @param {array} array of data and/or promises to wait for.
  1108. * @return {Promise} New dependant promise.
  1109. */
  1110. Promise.all = function Promise_all(promises) {
  1111. var resolveAll, rejectAll;
  1112. var deferred = new Promise(function (resolve, reject) {
  1113. resolveAll = resolve;
  1114. rejectAll = reject;
  1115. });
  1116. var unresolved = promises.length;
  1117. var results = [];
  1118. if (unresolved === 0) {
  1119. resolveAll(results);
  1120. return deferred;
  1121. }
  1122. function reject(reason) {
  1123. if (deferred._status === STATUS_REJECTED) {
  1124. return;
  1125. }
  1126. results = [];
  1127. rejectAll(reason);
  1128. }
  1129. for (var i = 0, ii = promises.length; i < ii; ++i) {
  1130. var promise = promises[i];
  1131. var resolve = (function(i) {
  1132. return function(value) {
  1133. if (deferred._status === STATUS_REJECTED) {
  1134. return;
  1135. }
  1136. results[i] = value;
  1137. unresolved--;
  1138. if (unresolved === 0) {
  1139. resolveAll(results);
  1140. }
  1141. };
  1142. })(i);
  1143. if (Promise.isPromise(promise)) {
  1144. promise.then(resolve, reject);
  1145. } else {
  1146. resolve(promise);
  1147. }
  1148. }
  1149. return deferred;
  1150. };
  1151. /**
  1152. * Checks if the value is likely a promise (has a 'then' function).
  1153. * @return {boolean} true if value is thenable
  1154. */
  1155. Promise.isPromise = function Promise_isPromise(value) {
  1156. return value && typeof value.then === 'function';
  1157. };
  1158. /**
  1159. * Creates resolved promise
  1160. * @param value resolve value
  1161. * @returns {Promise}
  1162. */
  1163. Promise.resolve = function Promise_resolve(value) {
  1164. return new Promise(function (resolve) { resolve(value); });
  1165. };
  1166. /**
  1167. * Creates rejected promise
  1168. * @param reason rejection value
  1169. * @returns {Promise}
  1170. */
  1171. Promise.reject = function Promise_reject(reason) {
  1172. return new Promise(function (resolve, reject) { reject(reason); });
  1173. };
  1174. Promise.prototype = {
  1175. _status: null,
  1176. _value: null,
  1177. _handlers: null,
  1178. _unhandledRejection: null,
  1179. _updateStatus: function Promise__updateStatus(status, value) {
  1180. if (this._status === STATUS_RESOLVED ||
  1181. this._status === STATUS_REJECTED) {
  1182. return;
  1183. }
  1184. if (status === STATUS_RESOLVED &&
  1185. Promise.isPromise(value)) {
  1186. value.then(this._updateStatus.bind(this, STATUS_RESOLVED),
  1187. this._updateStatus.bind(this, STATUS_REJECTED));
  1188. return;
  1189. }
  1190. this._status = status;
  1191. this._value = value;
  1192. if (status === STATUS_REJECTED && this._handlers.length === 0) {
  1193. this._unhandledRejection = true;
  1194. HandlerManager.addUnhandledRejection(this);
  1195. }
  1196. HandlerManager.scheduleHandlers(this);
  1197. },
  1198. _resolve: function Promise_resolve(value) {
  1199. this._updateStatus(STATUS_RESOLVED, value);
  1200. },
  1201. _reject: function Promise_reject(reason) {
  1202. this._updateStatus(STATUS_REJECTED, reason);
  1203. },
  1204. then: function Promise_then(onResolve, onReject) {
  1205. var nextPromise = new Promise(function (resolve, reject) {
  1206. this.resolve = resolve;
  1207. this.reject = reject;
  1208. });
  1209. this._handlers.push({
  1210. thisPromise: this,
  1211. onResolve: onResolve,
  1212. onReject: onReject,
  1213. nextPromise: nextPromise
  1214. });
  1215. HandlerManager.scheduleHandlers(this);
  1216. return nextPromise;
  1217. },
  1218. catch: function Promise_catch(onReject) {
  1219. return this.then(undefined, onReject);
  1220. }
  1221. };
  1222. globalScope.Promise = Promise;
  1223. })();
  1224. var StatTimer = (function StatTimerClosure() {
  1225. function rpad(str, pad, length) {
  1226. while (str.length < length) {
  1227. str += pad;
  1228. }
  1229. return str;
  1230. }
  1231. function StatTimer() {
  1232. this.started = {};
  1233. this.times = [];
  1234. this.enabled = true;
  1235. }
  1236. StatTimer.prototype = {
  1237. time: function StatTimer_time(name) {
  1238. if (!this.enabled) {
  1239. return;
  1240. }
  1241. if (name in this.started) {
  1242. warn('Timer is already running for ' + name);
  1243. }
  1244. this.started[name] = Date.now();
  1245. },
  1246. timeEnd: function StatTimer_timeEnd(name) {
  1247. if (!this.enabled) {
  1248. return;
  1249. }
  1250. if (!(name in this.started)) {
  1251. warn('Timer has not been started for ' + name);
  1252. }
  1253. this.times.push({
  1254. 'name': name,
  1255. 'start': this.started[name],
  1256. 'end': Date.now()
  1257. });
  1258. // Remove timer from started so it can be called again.
  1259. delete this.started[name];
  1260. },
  1261. toString: function StatTimer_toString() {
  1262. var i, ii;
  1263. var times = this.times;
  1264. var out = '';
  1265. // Find the longest name for padding purposes.
  1266. var longest = 0;
  1267. for (i = 0, ii = times.length; i < ii; ++i) {
  1268. var name = times[i]['name'];
  1269. if (name.length > longest) {
  1270. longest = name.length;
  1271. }
  1272. }
  1273. for (i = 0, ii = times.length; i < ii; ++i) {
  1274. var span = times[i];
  1275. var duration = span.end - span.start;
  1276. out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n';
  1277. }
  1278. return out;
  1279. }
  1280. };
  1281. return StatTimer;
  1282. })();
  1283. PDFJS.createBlob = function createBlob(data, contentType) {
  1284. if (typeof Blob !== 'undefined') {
  1285. return new Blob([data], { type: contentType });
  1286. }
  1287. // Blob builder is deprecated in FF14 and removed in FF18.
  1288. var bb = new MozBlobBuilder();
  1289. bb.append(data);
  1290. return bb.getBlob(contentType);
  1291. };
  1292. PDFJS.createObjectURL = (function createObjectURLClosure() {
  1293. // Blob/createObjectURL is not available, falling back to data schema.
  1294. var digits =
  1295. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  1296. return function createObjectURL(data, contentType) {
  1297. if (!PDFJS.disableCreateObjectURL &&
  1298. typeof URL !== 'undefined' && URL.createObjectURL) {
  1299. var blob = PDFJS.createBlob(data, contentType);
  1300. return URL.createObjectURL(blob);
  1301. }
  1302. var buffer = 'data:' + contentType + ';base64,';
  1303. for (var i = 0, ii = data.length; i < ii; i += 3) {
  1304. var b1 = data[i] & 0xFF;
  1305. var b2 = data[i + 1] & 0xFF;
  1306. var b3 = data[i + 2] & 0xFF;
  1307. var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
  1308. var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
  1309. var d4 = i + 2 < ii ? (b3 & 0x3F) : 64;
  1310. buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
  1311. }
  1312. return buffer;
  1313. };
  1314. })();
  1315. function MessageHandler(name, comObj) {
  1316. this.name = name;
  1317. this.comObj = comObj;
  1318. this.callbackIndex = 1;
  1319. this.postMessageTransfers = true;
  1320. var callbacksCapabilities = this.callbacksCapabilities = {};
  1321. var ah = this.actionHandler = {};
  1322. ah['console_log'] = [function ahConsoleLog(data) {
  1323. console.log.apply(console, data);
  1324. }];
  1325. ah['console_error'] = [function ahConsoleError(data) {
  1326. console.error.apply(console, data);
  1327. }];
  1328. ah['_unsupported_feature'] = [function ah_unsupportedFeature(data) {
  1329. UnsupportedManager.notify(data);
  1330. }];
  1331. comObj.onmessage = function messageHandlerComObjOnMessage(event) {
  1332. var data = event.data;
  1333. if (data.isReply) {
  1334. var callbackId = data.callbackId;
  1335. if (data.callbackId in callbacksCapabilities) {
  1336. var callback = callbacksCapabilities[callbackId];
  1337. delete callbacksCapabilities[callbackId];
  1338. if ('error' in data) {
  1339. callback.reject(data.error);
  1340. } else {
  1341. callback.resolve(data.data);
  1342. }
  1343. } else {
  1344. error('Cannot resolve callback ' + callbackId);
  1345. }
  1346. } else if (data.action in ah) {
  1347. var action = ah[data.action];
  1348. if (data.callbackId) {
  1349. Promise.resolve().then(function () {
  1350. return action[0].call(action[1], data.data);
  1351. }).then(function (result) {
  1352. comObj.postMessage({
  1353. isReply: true,
  1354. callbackId: data.callbackId,
  1355. data: result
  1356. });
  1357. }, function (reason) {
  1358. comObj.postMessage({
  1359. isReply: true,
  1360. callbackId: data.callbackId,
  1361. error: reason
  1362. });
  1363. });
  1364. } else {
  1365. action[0].call(action[1], data.data);
  1366. }
  1367. } else {
  1368. error('Unknown action from worker: ' + data.action);
  1369. }
  1370. };
  1371. }
  1372. MessageHandler.prototype = {
  1373. on: function messageHandlerOn(actionName, handler, scope) {
  1374. var ah = this.actionHandler;
  1375. if (ah[actionName]) {
  1376. error('There is already an actionName called "' + actionName + '"');
  1377. }
  1378. ah[actionName] = [handler, scope];
  1379. },
  1380. /**
  1381. * Sends a message to the comObj to invoke the action with the supplied data.
  1382. * @param {String} actionName Action to call.
  1383. * @param {JSON} data JSON data to send.
  1384. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers
  1385. */
  1386. send: function messageHandlerSend(actionName, data, transfers) {
  1387. var message = {
  1388. action: actionName,
  1389. data: data
  1390. };
  1391. this.postMessage(message, transfers);
  1392. },
  1393. /**
  1394. * Sends a message to the comObj to invoke the action with the supplied data.
  1395. * Expects that other side will callback with the response.
  1396. * @param {String} actionName Action to call.
  1397. * @param {JSON} data JSON data to send.
  1398. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers.
  1399. * @returns {Promise} Promise to be resolved with response data.
  1400. */
  1401. sendWithPromise:
  1402. function messageHandlerSendWithPromise(actionName, data, transfers) {
  1403. var callbackId = this.callbackIndex++;
  1404. var message = {
  1405. action: actionName,
  1406. data: data,
  1407. callbackId: callbackId
  1408. };
  1409. var capability = createPromiseCapability();
  1410. this.callbacksCapabilities[callbackId] = capability;
  1411. try {
  1412. this.postMessage(message, transfers);
  1413. } catch (e) {
  1414. capability.reject(e);
  1415. }
  1416. return capability.promise;
  1417. },
  1418. /**
  1419. * Sends raw message to the comObj.
  1420. * @private
  1421. * @param message {Object} Raw message.
  1422. * @param transfers List of transfers/ArrayBuffers, or undefined.
  1423. */
  1424. postMessage: function (message, transfers) {
  1425. if (transfers && this.postMessageTransfers) {
  1426. this.comObj.postMessage(message, transfers);
  1427. } else {
  1428. this.comObj.postMessage(message);
  1429. }
  1430. }
  1431. };
  1432. function loadJpegStream(id, imageUrl, objs) {
  1433. var img = new Image();
  1434. img.onload = (function loadJpegStream_onloadClosure() {
  1435. objs.resolve(id, img);
  1436. });
  1437. img.onerror = (function loadJpegStream_onerrorClosure() {
  1438. objs.resolve(id, null);
  1439. warn('Error during JPEG image loading');
  1440. });
  1441. img.src = imageUrl;
  1442. }
  1443. /**
  1444. * The maximum allowed image size in total pixels e.g. width * height. Images
  1445. * above this value will not be drawn. Use -1 for no limit.
  1446. * @var {number}
  1447. */
  1448. PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ?
  1449. -1 : PDFJS.maxImageSize);
  1450. /**
  1451. * The url of where the predefined Adobe CMaps are located. Include trailing
  1452. * slash.
  1453. * @var {string}
  1454. */
  1455. PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl);
  1456. /**
  1457. * Specifies if CMaps are binary packed.
  1458. * @var {boolean}
  1459. */
  1460. PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked;
  1461. /**
  1462. * By default fonts are converted to OpenType fonts and loaded via font face
  1463. * rules. If disabled, the font will be rendered using a built in font renderer
  1464. * that constructs the glyphs with primitive path commands.
  1465. * @var {boolean}
  1466. */
  1467. PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ?
  1468. false : PDFJS.disableFontFace);
  1469. /**
  1470. * Path for image resources, mainly for annotation icons. Include trailing
  1471. * slash.
  1472. * @var {string}
  1473. */
  1474. PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ?
  1475. '' : PDFJS.imageResourcesPath);
  1476. /**
  1477. * Disable the web worker and run all code on the main thread. This will happen
  1478. * automatically if the browser doesn't support workers or sending typed arrays
  1479. * to workers.
  1480. * @var {boolean}
  1481. */
  1482. PDFJS.disableWorker = (PDFJS.disableWorker === undefined ?
  1483. false : PDFJS.disableWorker);
  1484. /**
  1485. * Path and filename of the worker file. Required when the worker is enabled in
  1486. * development mode. If unspecified in the production build, the worker will be
  1487. * loaded based on the location of the pdf.js file.
  1488. * @var {string}
  1489. */
  1490. PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc);
  1491. /**
  1492. * Disable range request loading of PDF files. When enabled and if the server
  1493. * supports partial content requests then the PDF will be fetched in chunks.
  1494. * Enabled (false) by default.
  1495. * @var {boolean}
  1496. */
  1497. PDFJS.disableRange = (PDFJS.disableRange === undefined ?
  1498. false : PDFJS.disableRange);
  1499. /**
  1500. * Disable streaming of PDF file data. By default PDF.js attempts to load PDF
  1501. * in chunks. This default behavior can be disabled.
  1502. * @var {boolean}
  1503. */
  1504. PDFJS.disableStream = (PDFJS.disableStream === undefined ?
  1505. false : PDFJS.disableStream);
  1506. /**
  1507. * Disable pre-fetching of PDF file data. When range requests are enabled PDF.js
  1508. * will automatically keep fetching more data even if it isn't needed to display
  1509. * the current page. This default behavior can be disabled.
  1510. *
  1511. * NOTE: It is also necessary to disable streaming, see above,
  1512. * in order for disabling of pre-fetching to work correctly.
  1513. * @var {boolean}
  1514. */
  1515. PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ?
  1516. false : PDFJS.disableAutoFetch);
  1517. /**
  1518. * Enables special hooks for debugging PDF.js.
  1519. * @var {boolean}
  1520. */
  1521. PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug);
  1522. /**
  1523. * Enables transfer usage in postMessage for ArrayBuffers.
  1524. * @var {boolean}
  1525. */
  1526. PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ?
  1527. true : PDFJS.postMessageTransfers);
  1528. /**
  1529. * Disables URL.createObjectURL usage.
  1530. * @var {boolean}
  1531. */
  1532. PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ?
  1533. false : PDFJS.disableCreateObjectURL);
  1534. /**
  1535. * Disables WebGL usage.
  1536. * @var {boolean}
  1537. */
  1538. PDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ?
  1539. true : PDFJS.disableWebGL);
  1540. /**
  1541. * Disables fullscreen support, and by extension Presentation Mode,
  1542. * in browsers which support the fullscreen API.
  1543. * @var {boolean}
  1544. */
  1545. PDFJS.disableFullscreen = (PDFJS.disableFullscreen === undefined ?
  1546. false : PDFJS.disableFullscreen);
  1547. /**
  1548. * Enables CSS only zooming.
  1549. * @var {boolean}
  1550. */
  1551. PDFJS.useOnlyCssZoom = (PDFJS.useOnlyCssZoom === undefined ?
  1552. false : PDFJS.useOnlyCssZoom);
  1553. /**
  1554. * Controls the logging level.
  1555. * The constants from PDFJS.VERBOSITY_LEVELS should be used:
  1556. * - errors
  1557. * - warnings [default]
  1558. * - infos
  1559. * @var {number}
  1560. */
  1561. PDFJS.verbosity = (PDFJS.verbosity === undefined ?
  1562. PDFJS.VERBOSITY_LEVELS.warnings : PDFJS.verbosity);
  1563. /**
  1564. * The maximum supported canvas size in total pixels e.g. width * height.
  1565. * The default value is 4096 * 4096. Use -1 for no limit.
  1566. * @var {number}
  1567. */
  1568. PDFJS.maxCanvasPixels = (PDFJS.maxCanvasPixels === undefined ?
  1569. 16777216 : PDFJS.maxCanvasPixels);
  1570. /**
  1571. * Opens external links in a new window if enabled. The default behavior opens
  1572. * external links in the PDF.js window.
  1573. * @var {boolean}
  1574. */
  1575. PDFJS.openExternalLinksInNewWindow = (
  1576. PDFJS.openExternalLinksInNewWindow === undefined ?
  1577. false : PDFJS.openExternalLinksInNewWindow);
  1578. /**
  1579. * Document initialization / loading parameters object.
  1580. *
  1581. * @typedef {Object} DocumentInitParameters
  1582. * @property {string} url - The URL of the PDF.
  1583. * @property {TypedArray|Array|string} data - Binary PDF data. Use typed arrays
  1584. * (Uint8Array) to improve the memory usage. If PDF data is BASE64-encoded,
  1585. * use atob() to convert it to a binary string first.
  1586. * @property {Object} httpHeaders - Basic authentication headers.
  1587. * @property {boolean} withCredentials - Indicates whether or not cross-site
  1588. * Access-Control requests should be made using credentials such as cookies
  1589. * or authorization headers. The default is false.
  1590. * @property {string} password - For decrypting password-protected PDFs.
  1591. * @property {TypedArray} initialData - A typed array with the first portion or
  1592. * all of the pdf data. Used by the extension since some data is already
  1593. * loaded before the switch to range requests.
  1594. * @property {number} length - The PDF file length. It's used for progress
  1595. * reports and range requests operations.
  1596. * @property {PDFDataRangeTransport} range
  1597. */
  1598. /**
  1599. * @typedef {Object} PDFDocumentStats
  1600. * @property {Array} streamTypes - Used stream types in the document (an item
  1601. * is set to true if specific stream ID was used in the document).
  1602. * @property {Array} fontTypes - Used font type in the document (an item is set
  1603. * to true if specific font ID was used in the document).
  1604. */
  1605. /**
  1606. * This is the main entry point for loading a PDF and interacting with it.
  1607. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
  1608. * is used, which means it must follow the same origin rules that any XHR does
  1609. * e.g. No cross domain requests without CORS.
  1610. *
  1611. * @param {string|TypedArray|DocumentInitParameters|PDFDataRangeTransport} src
  1612. * Can be a url to where a PDF is located, a typed array (Uint8Array)
  1613. * already populated with data or parameter object.
  1614. *
  1615. * @param {PDFDataRangeTransport} pdfDataRangeTransport (deprecated) It is used
  1616. * if you want to manually serve range requests for data in the PDF.
  1617. *
  1618. * @param {function} passwordCallback (deprecated) It is used to request a
  1619. * password if wrong or no password was provided. The callback receives two
  1620. * parameters: function that needs to be called with new password and reason
  1621. * (see {PasswordResponses}).
  1622. *
  1623. * @param {function} progressCallback (deprecated) It is used to be able to
  1624. * monitor the loading progress of the PDF file (necessary to implement e.g.
  1625. * a loading bar). The callback receives an {Object} with the properties:
  1626. * {number} loaded and {number} total.
  1627. *
  1628. * @return {PDFDocumentLoadingTask}
  1629. */
  1630. PDFJS.getDocument = function getDocument(src,
  1631. pdfDataRangeTransport,
  1632. passwordCallback,
  1633. progressCallback) {
  1634. var task = new PDFDocumentLoadingTask();
  1635. // Support of the obsolete arguments (for compatibility with API v1.0)
  1636. if (pdfDataRangeTransport) {
  1637. if (!(pdfDataRangeTransport instanceof PDFDataRangeTransport)) {
  1638. // Not a PDFDataRangeTransport instance, trying to add missing properties.
  1639. pdfDataRangeTransport = Object.create(pdfDataRangeTransport);
  1640. pdfDataRangeTransport.length = src.length;
  1641. pdfDataRangeTransport.initialData = src.initialData;
  1642. }
  1643. src = Object.create(src);
  1644. src.range = pdfDataRangeTransport;
  1645. }
  1646. task.onPassword = passwordCallback || null;
  1647. task.onProgress = progressCallback || null;
  1648. var workerInitializedCapability, transport;
  1649. var source;
  1650. if (typeof src === 'string') {
  1651. source = { url: src };
  1652. } else if (isArrayBuffer(src)) {
  1653. source = { data: src };
  1654. } else if (src instanceof PDFDataRangeTransport) {
  1655. source = { range: src };
  1656. } else {
  1657. if (typeof src !== 'object') {
  1658. error('Invalid parameter in getDocument, need either Uint8Array, ' +
  1659. 'string or a parameter object');
  1660. }
  1661. if (!src.url && !src.data && !src.range) {
  1662. error('Invalid parameter object: need either .data, .range or .url');
  1663. }
  1664. source = src;
  1665. }
  1666. var params = {};
  1667. for (var key in source) {
  1668. if (key === 'url' && typeof window !== 'undefined') {
  1669. // The full path is required in the 'url' field.
  1670. params[key] = combineUrl(window.location.href, source[key]);
  1671. continue;
  1672. } else if (key === 'range') {
  1673. continue;
  1674. } else if (key === 'data' && !(source[key] instanceof Uint8Array)) {
  1675. // Converting string or array-like data to Uint8Array.
  1676. var pdfBytes = source[key];
  1677. if (typeof pdfBytes === 'string') {
  1678. params[key] = stringToBytes(pdfBytes);
  1679. } else if (typeof pdfBytes === 'object' && pdfBytes !== null &&
  1680. !isNaN(pdfBytes.length)) {
  1681. params[key] = new Uint8Array(pdfBytes);
  1682. } else {
  1683. error('Invalid PDF binary data: either typed array, string or ' +
  1684. 'array-like object is expected in the data property.');
  1685. }
  1686. continue;
  1687. }
  1688. params[key] = source[key];
  1689. }
  1690. workerInitializedCapability = createPromiseCapability();
  1691. transport = new WorkerTransport(workerInitializedCapability, source.range);
  1692. workerInitializedCapability.promise.then(function transportInitialized() {
  1693. transport.fetchDocument(task, params);
  1694. });
  1695. return task;
  1696. };
  1697. /**
  1698. * PDF document loading operation.
  1699. * @class
  1700. */
  1701. var PDFDocumentLoadingTask = (function PDFDocumentLoadingTaskClosure() {
  1702. /** @constructs PDFDocumentLoadingTask */
  1703. function PDFDocumentLoadingTask() {
  1704. this._capability = createPromiseCapability();
  1705. /**
  1706. * Callback to request a password if wrong or no password was provided.
  1707. * The callback receives two parameters: function that needs to be called
  1708. * with new password and reason (see {PasswordResponses}).
  1709. */
  1710. this.onPassword = null;
  1711. /**
  1712. * Callback to be able to monitor the loading progress of the PDF file
  1713. * (necessary to implement e.g. a loading bar). The callback receives
  1714. * an {Object} with the properties: {number} loaded and {number} total.
  1715. */
  1716. this.onProgress = null;
  1717. }
  1718. PDFDocumentLoadingTask.prototype =
  1719. /** @lends PDFDocumentLoadingTask.prototype */ {
  1720. /**
  1721. * @return {Promise}
  1722. */
  1723. get promise() {
  1724. return this._capability.promise;
  1725. },
  1726. // TODO add cancel or abort method
  1727. /**
  1728. * Registers callbacks to indicate the document loading completion.
  1729. *
  1730. * @param {function} onFulfilled The callback for the loading completion.
  1731. * @param {function} onRejected The callback for the loading failure.
  1732. * @return {Promise} A promise that is resolved after the onFulfilled or
  1733. * onRejected callback.
  1734. */
  1735. then: function PDFDocumentLoadingTask_then(onFulfilled, onRejected) {
  1736. return this.promise.then.apply(this.promise, arguments);
  1737. }
  1738. };
  1739. return PDFDocumentLoadingTask;
  1740. })();
  1741. /**
  1742. * Abstract class to support range requests file loading.
  1743. * @class
  1744. */
  1745. var PDFDataRangeTransport = (function pdfDataRangeTransportClosure() {
  1746. /**
  1747. * @constructs PDFDataRangeTransport
  1748. * @param {number} length
  1749. * @param {Uint8Array} initialData
  1750. */
  1751. function PDFDataRangeTransport(length, initialData) {
  1752. this.length = length;
  1753. this.initialData = initialData;
  1754. this._rangeListeners = [];
  1755. this._progressListeners = [];
  1756. this._progressiveReadListeners = [];
  1757. this._readyCapability = createPromiseCapability();
  1758. }
  1759. PDFDataRangeTransport.prototype =
  1760. /** @lends PDFDataRangeTransport.prototype */ {
  1761. addRangeListener:
  1762. function PDFDataRangeTransport_addRangeListener(listener) {
  1763. this._rangeListeners.push(listener);
  1764. },
  1765. addProgressListener:
  1766. function PDFDataRangeTransport_addProgressListener(listener) {
  1767. this._progressListeners.push(listener);
  1768. },
  1769. addProgressiveReadListener:
  1770. function PDFDataRangeTransport_addProgressiveReadListener(listener) {
  1771. this._progressiveReadListeners.push(listener);
  1772. },
  1773. onDataRange: function PDFDataRangeTransport_onDataRange(begin, chunk) {
  1774. var listeners = this._rangeListeners;
  1775. for (var i = 0, n = listeners.length; i < n; ++i) {
  1776. listeners[i](begin, chunk);
  1777. }
  1778. },
  1779. onDataProgress: function PDFDataRangeTransport_onDataProgress(loaded) {
  1780. this._readyCapability.promise.then(function () {
  1781. var listeners = this._progressListeners;
  1782. for (var i = 0, n = listeners.length; i < n; ++i) {
  1783. listeners[i](loaded);
  1784. }
  1785. }.bind(this));
  1786. },
  1787. onDataProgressiveRead:
  1788. function PDFDataRangeTransport_onDataProgress(chunk) {
  1789. this._readyCapability.promise.then(function () {
  1790. var listeners = this._progressiveReadListeners;
  1791. for (var i = 0, n = listeners.length; i < n; ++i) {
  1792. listeners[i](chunk);
  1793. }
  1794. }.bind(this));
  1795. },
  1796. transportReady: function PDFDataRangeTransport_transportReady() {
  1797. this._readyCapability.resolve();
  1798. },
  1799. requestDataRange:
  1800. function PDFDataRangeTransport_requestDataRange(begin, end) {
  1801. throw new Error('Abstract method PDFDataRangeTransport.requestDataRange');
  1802. }
  1803. };
  1804. return PDFDataRangeTransport;
  1805. })();
  1806. PDFJS.PDFDataRangeTransport = PDFDataRangeTransport;
  1807. /**
  1808. * Proxy to a PDFDocument in the worker thread. Also, contains commonly used
  1809. * properties that can be read synchronously.
  1810. * @class
  1811. */
  1812. var PDFDocumentProxy = (function PDFDocumentProxyClosure() {
  1813. function PDFDocumentProxy(pdfInfo, transport) {
  1814. this.pdfInfo = pdfInfo;
  1815. this.transport = transport;
  1816. }
  1817. PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ {
  1818. /**
  1819. * @return {number} Total number of pages the PDF contains.
  1820. */
  1821. get numPages() {
  1822. return this.pdfInfo.numPages;
  1823. },
  1824. /**
  1825. * @return {string} A unique ID to identify a PDF. Not guaranteed to be
  1826. * unique.
  1827. */
  1828. get fingerprint() {
  1829. return this.pdfInfo.fingerprint;
  1830. },
  1831. /**
  1832. * @param {number} pageNumber The page number to get. The first page is 1.
  1833. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy}
  1834. * object.
  1835. */
  1836. getPage: function PDFDocumentProxy_getPage(pageNumber) {
  1837. return this.transport.getPage(pageNumber);
  1838. },
  1839. /**
  1840. * @param {{num: number, gen: number}} ref The page reference. Must have
  1841. * the 'num' and 'gen' properties.
  1842. * @return {Promise} A promise that is resolved with the page index that is
  1843. * associated with the reference.
  1844. */
  1845. getPageIndex: function PDFDocumentProxy_getPageIndex(ref) {
  1846. return this.transport.getPageIndex(ref);
  1847. },
  1848. /**
  1849. * @return {Promise} A promise that is resolved with a lookup table for
  1850. * mapping named destinations to reference numbers.
  1851. *
  1852. * This can be slow for large documents: use getDestination instead
  1853. */
  1854. getDestinations: function PDFDocumentProxy_getDestinations() {
  1855. return this.transport.getDestinations();
  1856. },
  1857. /**
  1858. * @param {string} id The named destination to get.
  1859. * @return {Promise} A promise that is resolved with all information
  1860. * of the given named destination.
  1861. */
  1862. getDestination: function PDFDocumentProxy_getDestination(id) {
  1863. return this.transport.getDestination(id);
  1864. },
  1865. /**
  1866. * @return {Promise} A promise that is resolved with a lookup table for
  1867. * mapping named attachments to their content.
  1868. */
  1869. getAttachments: function PDFDocumentProxy_getAttachments() {
  1870. return this.transport.getAttachments();
  1871. },
  1872. /**
  1873. * @return {Promise} A promise that is resolved with an array of all the
  1874. * JavaScript strings in the name tree.
  1875. */
  1876. getJavaScript: function PDFDocumentProxy_getJavaScript() {
  1877. return this.transport.getJavaScript();
  1878. },
  1879. /**
  1880. * @return {Promise} A promise that is resolved with an {Array} that is a
  1881. * tree outline (if it has one) of the PDF. The tree is in the format of:
  1882. * [
  1883. * {
  1884. * title: string,
  1885. * bold: boolean,
  1886. * italic: boolean,
  1887. * color: rgb array,
  1888. * dest: dest obj,
  1889. * items: array of more items like this
  1890. * },
  1891. * ...
  1892. * ].
  1893. */
  1894. getOutline: function PDFDocumentProxy_getOutline() {
  1895. return this.transport.getOutline();
  1896. },
  1897. /**
  1898. * @return {Promise} A promise that is resolved with an {Object} that has
  1899. * info and metadata properties. Info is an {Object} filled with anything
  1900. * available in the information dictionary and similarly metadata is a
  1901. * {Metadata} object with information from the metadata section of the PDF.
  1902. */
  1903. getMetadata: function PDFDocumentProxy_getMetadata() {
  1904. return this.transport.getMetadata();
  1905. },
  1906. /**
  1907. * @return {Promise} A promise that is resolved with a TypedArray that has
  1908. * the raw data from the PDF.
  1909. */
  1910. getData: function PDFDocumentProxy_getData() {
  1911. return this.transport.getData();
  1912. },
  1913. /**
  1914. * @return {Promise} A promise that is resolved when the document's data
  1915. * is loaded. It is resolved with an {Object} that contains the length
  1916. * property that indicates size of the PDF data in bytes.
  1917. */
  1918. getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() {
  1919. return this.transport.downloadInfoCapability.promise;
  1920. },
  1921. /**
  1922. * @return {Promise} A promise this is resolved with current stats about
  1923. * document structures (see {@link PDFDocumentStats}).
  1924. */
  1925. getStats: function PDFDocumentProxy_getStats() {
  1926. return this.transport.getStats();
  1927. },
  1928. /**
  1929. * Cleans up resources allocated by the document, e.g. created @font-face.
  1930. */
  1931. cleanup: function PDFDocumentProxy_cleanup() {
  1932. this.transport.startCleanup();
  1933. },
  1934. /**
  1935. * Destroys current document instance and terminates worker.
  1936. */
  1937. destroy: function PDFDocumentProxy_destroy() {
  1938. this.transport.destroy();
  1939. }
  1940. };
  1941. return PDFDocumentProxy;
  1942. })();
  1943. /**
  1944. * Page text content.
  1945. *
  1946. * @typedef {Object} TextContent
  1947. * @property {array} items - array of {@link TextItem}
  1948. * @property {Object} styles - {@link TextStyles} objects, indexed by font
  1949. * name.
  1950. */
  1951. /**
  1952. * Page text content part.
  1953. *
  1954. * @typedef {Object} TextItem
  1955. * @property {string} str - text content.
  1956. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'.
  1957. * @property {array} transform - transformation matrix.
  1958. * @property {number} width - width in device space.
  1959. * @property {number} height - height in device space.
  1960. * @property {string} fontName - font name used by pdf.js for converted font.
  1961. */
  1962. /**
  1963. * Text style.
  1964. *
  1965. * @typedef {Object} TextStyle
  1966. * @property {number} ascent - font ascent.
  1967. * @property {number} descent - font descent.
  1968. * @property {boolean} vertical - text is in vertical mode.
  1969. * @property {string} fontFamily - possible font family
  1970. */
  1971. /**
  1972. * Page render parameters.
  1973. *
  1974. * @typedef {Object} RenderParameters
  1975. * @property {Object} canvasContext - A 2D context of a DOM Canvas object.
  1976. * @property {PDFJS.PageViewport} viewport - Rendering viewport obtained by
  1977. * calling of PDFPage.getViewport method.
  1978. * @property {string} intent - Rendering intent, can be 'display' or 'print'
  1979. * (default value is 'display').
  1980. * @property {Object} imageLayer - (optional) An object that has beginLayout,
  1981. * endLayout and appendImage functions.
  1982. * @property {function} continueCallback - (deprecated) A function that will be
  1983. * called each time the rendering is paused. To continue
  1984. * rendering call the function that is the first argument
  1985. * to the callback.
  1986. */
  1987. /**
  1988. * PDF page operator list.
  1989. *
  1990. * @typedef {Object} PDFOperatorList
  1991. * @property {Array} fnArray - Array containing the operator functions.
  1992. * @property {Array} argsArray - Array containing the arguments of the
  1993. * functions.
  1994. */
  1995. /**
  1996. * Proxy to a PDFPage in the worker thread.
  1997. * @class
  1998. */
  1999. var PDFPageProxy = (function PDFPageProxyClosure() {
  2000. function PDFPageProxy(pageIndex, pageInfo, transport) {
  2001. this.pageIndex = pageIndex;
  2002. this.pageInfo = pageInfo;
  2003. this.transport = transport;
  2004. this.stats = new StatTimer();
  2005. this.stats.enabled = !!globalScope.PDFJS.enableStats;
  2006. this.commonObjs = transport.commonObjs;
  2007. this.objs = new PDFObjects();
  2008. this.cleanupAfterRender = false;
  2009. this.pendingDestroy = false;
  2010. this.intentStates = {};
  2011. }
  2012. PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ {
  2013. /**
  2014. * @return {number} Page number of the page. First page is 1.
  2015. */
  2016. get pageNumber() {
  2017. return this.pageIndex + 1;
  2018. },
  2019. /**
  2020. * @return {number} The number of degrees the page is rotated clockwise.
  2021. */
  2022. get rotate() {
  2023. return this.pageInfo.rotate;
  2024. },
  2025. /**
  2026. * @return {Object} The reference that points to this page. It has 'num' and
  2027. * 'gen' properties.
  2028. */
  2029. get ref() {
  2030. return this.pageInfo.ref;
  2031. },
  2032. /**
  2033. * @return {Array} An array of the visible portion of the PDF page in the
  2034. * user space units - [x1, y1, x2, y2].
  2035. */
  2036. get view() {
  2037. return this.pageInfo.view;
  2038. },
  2039. /**
  2040. * @param {number} scale The desired scale of the viewport.
  2041. * @param {number} rotate Degrees to rotate the viewport. If omitted this
  2042. * defaults to the page rotation.
  2043. * @return {PDFJS.PageViewport} Contains 'width' and 'height' properties
  2044. * along with transforms required for rendering.
  2045. */
  2046. getViewport: function PDFPageProxy_getViewport(scale, rotate) {
  2047. if (arguments.length < 2) {
  2048. rotate = this.rotate;
  2049. }
  2050. return new PDFJS.PageViewport(this.view, scale, rotate, 0, 0);
  2051. },
  2052. /**
  2053. * @return {Promise} A promise that is resolved with an {Array} of the
  2054. * annotation objects.
  2055. */
  2056. getAnnotations: function PDFPageProxy_getAnnotations() {
  2057. if (this.annotationsPromise) {
  2058. return this.annotationsPromise;
  2059. }
  2060. var promise = this.transport.getAnnotations(this.pageIndex);
  2061. this.annotationsPromise = promise;
  2062. return promise;
  2063. },
  2064. /**
  2065. * Begins the process of rendering a page to the desired context.
  2066. * @param {RenderParameters} params Page render parameters.
  2067. * @return {RenderTask} An object that contains the promise, which
  2068. * is resolved when the page finishes rendering.
  2069. */
  2070. render: function PDFPageProxy_render(params) {
  2071. var stats = this.stats;
  2072. stats.time('Overall');
  2073. // If there was a pending destroy cancel it so no cleanup happens during
  2074. // this call to render.
  2075. this.pendingDestroy = false;
  2076. var renderingIntent = (params.intent === 'print' ? 'print' : 'display');
  2077. if (!this.intentStates[renderingIntent]) {
  2078. this.intentStates[renderingIntent] = {};
  2079. }
  2080. var intentState = this.intentStates[renderingIntent];
  2081. // If there's no displayReadyCapability yet, then the operatorList
  2082. // was never requested before. Make the request and create the promise.
  2083. if (!intentState.displayReadyCapability) {
  2084. intentState.receivingOperatorList = true;
  2085. intentState.displayReadyCapability = createPromiseCapability();
  2086. intentState.operatorList = {
  2087. fnArray: [],
  2088. argsArray: [],
  2089. lastChunk: false
  2090. };
  2091. this.stats.time('Page Request');
  2092. this.transport.messageHandler.send('RenderPageRequest', {
  2093. pageIndex: this.pageNumber - 1,
  2094. intent: renderingIntent
  2095. });
  2096. }
  2097. var internalRenderTask = new InternalRenderTask(complete, params,
  2098. this.objs,
  2099. this.commonObjs,
  2100. intentState.operatorList,
  2101. this.pageNumber);
  2102. internalRenderTask.useRequestAnimationFrame = renderingIntent !== 'print';
  2103. if (!intentState.renderTasks) {
  2104. intentState.renderTasks = [];
  2105. }
  2106. intentState.renderTasks.push(internalRenderTask);
  2107. var renderTask = internalRenderTask.task;
  2108. // Obsolete parameter support
  2109. if (params.continueCallback) {
  2110. renderTask.onContinue = params.continueCallback;
  2111. }
  2112. var self = this;
  2113. intentState.displayReadyCapability.promise.then(
  2114. function pageDisplayReadyPromise(transparency) {
  2115. if (self.pendingDestroy) {
  2116. complete();
  2117. return;
  2118. }
  2119. stats.time('Rendering');
  2120. internalRenderTask.initalizeGraphics(transparency);
  2121. internalRenderTask.operatorListChanged();
  2122. },
  2123. function pageDisplayReadPromiseError(reason) {
  2124. complete(reason);
  2125. }
  2126. );
  2127. function complete(error) {
  2128. var i = intentState.renderTasks.indexOf(internalRenderTask);
  2129. if (i >= 0) {
  2130. intentState.renderTasks.splice(i, 1);
  2131. }
  2132. if (self.cleanupAfterRender) {
  2133. self.pendingDestroy = true;
  2134. }
  2135. self._tryDestroy();
  2136. if (error) {
  2137. internalRenderTask.capability.reject(error);
  2138. } else {
  2139. internalRenderTask.capability.resolve();
  2140. }
  2141. stats.timeEnd('Rendering');
  2142. stats.timeEnd('Overall');
  2143. }
  2144. return renderTask;
  2145. },
  2146. /**
  2147. * @return {Promise} A promise resolved with an {@link PDFOperatorList}
  2148. * object that represents page's operator list.
  2149. */
  2150. getOperatorList: function PDFPageProxy_getOperatorList() {
  2151. function operatorListChanged() {
  2152. if (intentState.operatorList.lastChunk) {
  2153. intentState.opListReadCapability.resolve(intentState.operatorList);
  2154. }
  2155. }
  2156. var renderingIntent = 'oplist';
  2157. if (!this.intentStates[renderingIntent]) {
  2158. this.intentStates[renderingIntent] = {};
  2159. }
  2160. var intentState = this.intentStates[renderingIntent];
  2161. if (!intentState.opListReadCapability) {
  2162. var opListTask = {};
  2163. opListTask.operatorListChanged = operatorListChanged;
  2164. intentState.receivingOperatorList = true;
  2165. intentState.opListReadCapability = createPromiseCapability();
  2166. intentState.renderTasks = [];
  2167. intentState.renderTasks.push(opListTask);
  2168. intentState.operatorList = {
  2169. fnArray: [],
  2170. argsArray: [],
  2171. lastChunk: false
  2172. };
  2173. this.transport.messageHandler.send('RenderPageRequest', {
  2174. pageIndex: this.pageIndex,
  2175. intent: renderingIntent
  2176. });
  2177. }
  2178. return intentState.opListReadCapability.promise;
  2179. },
  2180. /**
  2181. * @return {Promise} That is resolved a {@link TextContent}
  2182. * object that represent the page text content.
  2183. */
  2184. getTextContent: function PDFPageProxy_getTextContent() {
  2185. return this.transport.messageHandler.sendWithPromise('GetTextContent', {
  2186. pageIndex: this.pageNumber - 1
  2187. });
  2188. },
  2189. /**
  2190. * Destroys resources allocated by the page.
  2191. */
  2192. destroy: function PDFPageProxy_destroy() {
  2193. this.pendingDestroy = true;
  2194. this._tryDestroy();
  2195. },
  2196. /**
  2197. * For internal use only. Attempts to clean up if rendering is in a state
  2198. * where that's possible.
  2199. * @ignore
  2200. */
  2201. _tryDestroy: function PDFPageProxy__destroy() {
  2202. if (!this.pendingDestroy ||
  2203. Object.keys(this.intentStates).some(function(intent) {
  2204. var intentState = this.intentStates[intent];
  2205. return (intentState.renderTasks.length !== 0 ||
  2206. intentState.receivingOperatorList);
  2207. }, this)) {
  2208. return;
  2209. }
  2210. Object.keys(this.intentStates).forEach(function(intent) {
  2211. delete this.intentStates[intent];
  2212. }, this);
  2213. this.objs.clear();
  2214. this.annotationsPromise = null;
  2215. this.pendingDestroy = false;
  2216. },
  2217. /**
  2218. * For internal use only.
  2219. * @ignore
  2220. */
  2221. _startRenderPage: function PDFPageProxy_startRenderPage(transparency,
  2222. intent) {
  2223. var intentState = this.intentStates[intent];
  2224. // TODO Refactor RenderPageRequest to separate rendering
  2225. // and operator list logic
  2226. if (intentState.displayReadyCapability) {
  2227. intentState.displayReadyCapability.resolve(transparency);
  2228. }
  2229. },
  2230. /**
  2231. * For internal use only.
  2232. * @ignore
  2233. */
  2234. _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk,
  2235. intent) {
  2236. var intentState = this.intentStates[intent];
  2237. var i, ii;
  2238. // Add the new chunk to the current operator list.
  2239. for (i = 0, ii = operatorListChunk.length; i < ii; i++) {
  2240. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  2241. intentState.operatorList.argsArray.push(
  2242. operatorListChunk.argsArray[i]);
  2243. }
  2244. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  2245. // Notify all the rendering tasks there are more operators to be consumed.
  2246. for (i = 0; i < intentState.renderTasks.length; i++) {
  2247. intentState.renderTasks[i].operatorListChanged();
  2248. }
  2249. if (operatorListChunk.lastChunk) {
  2250. intentState.receivingOperatorList = false;
  2251. this._tryDestroy();
  2252. }
  2253. }
  2254. };
  2255. return PDFPageProxy;
  2256. })();
  2257. /**
  2258. * For internal use only.
  2259. * @ignore
  2260. */
  2261. var WorkerTransport = (function WorkerTransportClosure() {
  2262. function WorkerTransport(workerInitializedCapability, pdfDataRangeTransport) {
  2263. this.pdfDataRangeTransport = pdfDataRangeTransport;
  2264. this.workerInitializedCapability = workerInitializedCapability;
  2265. this.commonObjs = new PDFObjects();
  2266. this.loadingTask = null;
  2267. this.pageCache = [];
  2268. this.pagePromises = [];
  2269. this.downloadInfoCapability = createPromiseCapability();
  2270. // If worker support isn't disabled explicit and the browser has worker
  2271. // support, create a new web worker and test if it/the browser fullfills
  2272. // all requirements to run parts of pdf.js in a web worker.
  2273. // Right now, the requirement is, that an Uint8Array is still an Uint8Array
  2274. // as it arrives on the worker. Chrome added this with version 15.
  2275. // Either workers are disabled, not supported or have thrown an exception.
  2276. // Thus, we fallback to a faked worker.
  2277. this.setupFakeWorker();
  2278. }
  2279. WorkerTransport.prototype = {
  2280. destroy: function WorkerTransport_destroy() {
  2281. this.pageCache = [];
  2282. this.pagePromises = [];
  2283. var self = this;
  2284. this.messageHandler.sendWithPromise('Terminate', null).then(function () {
  2285. FontLoader.clear();
  2286. if (self.worker) {
  2287. self.worker.terminate();
  2288. }
  2289. });
  2290. },
  2291. setupFakeWorker: function WorkerTransport_setupFakeWorker() {
  2292. globalScope.PDFJS.disableWorker = true;
  2293. if (!PDFJS.fakeWorkerFilesLoadedCapability) {
  2294. PDFJS.fakeWorkerFilesLoadedCapability = createPromiseCapability();
  2295. // In the developer build load worker_loader which in turn loads all the
  2296. // other files and resolves the promise. In production only the
  2297. // pdf.worker.js file is needed.
  2298. PDFJS.fakeWorkerFilesLoadedCapability.resolve();
  2299. }
  2300. PDFJS.fakeWorkerFilesLoadedCapability.promise.then(function () {
  2301. warn('Setting up fake worker.');
  2302. // If we don't use a worker, just post/sendMessage to the main thread.
  2303. var fakeWorker = {
  2304. postMessage: function WorkerTransport_postMessage(obj) {
  2305. fakeWorker.onmessage({data: obj});
  2306. },
  2307. terminate: function WorkerTransport_terminate() {}
  2308. };
  2309. var messageHandler = new MessageHandler('main', fakeWorker);
  2310. this.setupMessageHandler(messageHandler);
  2311. // If the main thread is our worker, setup the handling for the messages
  2312. // the main thread sends to it self.
  2313. PDFJS.WorkerMessageHandler.setup(messageHandler);
  2314. this.workerInitializedCapability.resolve();
  2315. }.bind(this));
  2316. },
  2317. setupMessageHandler:
  2318. function WorkerTransport_setupMessageHandler(messageHandler) {
  2319. this.messageHandler = messageHandler;
  2320. function updatePassword(password) {
  2321. messageHandler.send('UpdatePassword', password);
  2322. }
  2323. var pdfDataRangeTransport = this.pdfDataRangeTransport;
  2324. if (pdfDataRangeTransport) {
  2325. pdfDataRangeTransport.addRangeListener(function(begin, chunk) {
  2326. messageHandler.send('OnDataRange', {
  2327. begin: begin,
  2328. chunk: chunk
  2329. });
  2330. });
  2331. pdfDataRangeTransport.addProgressListener(function(loaded) {
  2332. messageHandler.send('OnDataProgress', {
  2333. loaded: loaded
  2334. });
  2335. });
  2336. pdfDataRangeTransport.addProgressiveReadListener(function(chunk) {
  2337. messageHandler.send('OnDataRange', {
  2338. chunk: chunk
  2339. });
  2340. });
  2341. messageHandler.on('RequestDataRange',
  2342. function transportDataRange(data) {
  2343. pdfDataRangeTransport.requestDataRange(data.begin, data.end);
  2344. }, this);
  2345. }
  2346. messageHandler.on('GetDoc', function transportDoc(data) {
  2347. var pdfInfo = data.pdfInfo;
  2348. this.numPages = data.pdfInfo.numPages;
  2349. var pdfDocument = new PDFDocumentProxy(pdfInfo, this);
  2350. this.pdfDocument = pdfDocument;
  2351. this.loadingTask._capability.resolve(pdfDocument);
  2352. }, this);
  2353. messageHandler.on('NeedPassword',
  2354. function transportNeedPassword(exception) {
  2355. var loadingTask = this.loadingTask;
  2356. if (loadingTask.onPassword) {
  2357. return loadingTask.onPassword(updatePassword,
  2358. PasswordResponses.NEED_PASSWORD);
  2359. }
  2360. loadingTask._capability.reject(
  2361. new PasswordException(exception.message, exception.code));
  2362. }, this);
  2363. messageHandler.on('IncorrectPassword',
  2364. function transportIncorrectPassword(exception) {
  2365. var loadingTask = this.loadingTask;
  2366. if (loadingTask.onPassword) {
  2367. return loadingTask.onPassword(updatePassword,
  2368. PasswordResponses.INCORRECT_PASSWORD);
  2369. }
  2370. loadingTask._capability.reject(
  2371. new PasswordException(exception.message, exception.code));
  2372. }, this);
  2373. messageHandler.on('InvalidPDF', function transportInvalidPDF(exception) {
  2374. this.loadingTask._capability.reject(
  2375. new InvalidPDFException(exception.message));
  2376. }, this);
  2377. messageHandler.on('MissingPDF', function transportMissingPDF(exception) {
  2378. this.loadingTask._capability.reject(
  2379. new MissingPDFException(exception.message));
  2380. }, this);
  2381. messageHandler.on('UnexpectedResponse',
  2382. function transportUnexpectedResponse(exception) {
  2383. this.loadingTask._capability.reject(
  2384. new UnexpectedResponseException(exception.message, exception.status));
  2385. }, this);
  2386. messageHandler.on('UnknownError',
  2387. function transportUnknownError(exception) {
  2388. this.loadingTask._capability.reject(
  2389. new UnknownErrorException(exception.message, exception.details));
  2390. }, this);
  2391. messageHandler.on('DataLoaded', function transportPage(data) {
  2392. this.downloadInfoCapability.resolve(data);
  2393. }, this);
  2394. messageHandler.on('PDFManagerReady', function transportPage(data) {
  2395. if (this.pdfDataRangeTransport) {
  2396. this.pdfDataRangeTransport.transportReady();
  2397. }
  2398. }, this);
  2399. messageHandler.on('StartRenderPage', function transportRender(data) {
  2400. var page = this.pageCache[data.pageIndex];
  2401. page.stats.timeEnd('Page Request');
  2402. page._startRenderPage(data.transparency, data.intent);
  2403. }, this);
  2404. messageHandler.on('RenderPageChunk', function transportRender(data) {
  2405. var page = this.pageCache[data.pageIndex];
  2406. page._renderPageChunk(data.operatorList, data.intent);
  2407. }, this);
  2408. messageHandler.on('commonobj', function transportObj(data) {
  2409. var id = data[0];
  2410. var type = data[1];
  2411. if (this.commonObjs.hasData(id)) {
  2412. return;
  2413. }
  2414. switch (type) {
  2415. case 'Font':
  2416. var exportedData = data[2];
  2417. var font;
  2418. if ('error' in exportedData) {
  2419. var error = exportedData.error;
  2420. warn('Error during font loading: ' + error);
  2421. this.commonObjs.resolve(id, error);
  2422. break;
  2423. } else {
  2424. font = new FontFaceObject(exportedData);
  2425. }
  2426. FontLoader.bind(
  2427. [font],
  2428. function fontReady(fontObjs) {
  2429. this.commonObjs.resolve(id, font);
  2430. }.bind(this)
  2431. );
  2432. break;
  2433. case 'FontPath':
  2434. this.commonObjs.resolve(id, data[2]);
  2435. break;
  2436. default:
  2437. error('Got unknown common object type ' + type);
  2438. }
  2439. }, this);
  2440. messageHandler.on('obj', function transportObj(data) {
  2441. var id = data[0];
  2442. var pageIndex = data[1];
  2443. var type = data[2];
  2444. var pageProxy = this.pageCache[pageIndex];
  2445. var imageData;
  2446. if (pageProxy.objs.hasData(id)) {
  2447. return;
  2448. }
  2449. switch (type) {
  2450. case 'JpegStream':
  2451. imageData = data[3];
  2452. loadJpegStream(id, imageData, pageProxy.objs);
  2453. break;
  2454. case 'Image':
  2455. imageData = data[3];
  2456. pageProxy.objs.resolve(id, imageData);
  2457. // heuristics that will allow not to store large data
  2458. var MAX_IMAGE_SIZE_TO_STORE = 8000000;
  2459. if (imageData && 'data' in imageData &&
  2460. imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) {
  2461. pageProxy.cleanupAfterRender = true;
  2462. }
  2463. break;
  2464. default:
  2465. error('Got unknown object type ' + type);
  2466. }
  2467. }, this);
  2468. messageHandler.on('DocProgress', function transportDocProgress(data) {
  2469. var loadingTask = this.loadingTask;
  2470. if (loadingTask.onProgress) {
  2471. loadingTask.onProgress({
  2472. loaded: data.loaded,
  2473. total: data.total
  2474. });
  2475. }
  2476. }, this);
  2477. messageHandler.on('PageError', function transportError(data) {
  2478. var page = this.pageCache[data.pageNum - 1];
  2479. var intentState = page.intentStates[data.intent];
  2480. if (intentState.displayReadyCapability) {
  2481. intentState.displayReadyCapability.reject(data.error);
  2482. } else {
  2483. error(data.error);
  2484. }
  2485. }, this);
  2486. messageHandler.on('JpegDecode', function(data) {
  2487. var imageUrl = data[0];
  2488. var components = data[1];
  2489. if (components !== 3 && components !== 1) {
  2490. return Promise.reject(
  2491. new Error('Only 3 components or 1 component can be returned'));
  2492. }
  2493. return new Promise(function (resolve, reject) {
  2494. var img = new Image();
  2495. img.onload = function () {
  2496. var width = img.width;
  2497. var height = img.height;
  2498. var size = width * height;
  2499. var rgbaLength = size * 4;
  2500. var buf = new Uint8Array(size * components);
  2501. var tmpCanvas = createScratchCanvas(width, height);
  2502. var tmpCtx = tmpCanvas.getContext('2d');
  2503. tmpCtx.drawImage(img, 0, 0);
  2504. var data = tmpCtx.getImageData(0, 0, width, height).data;
  2505. var i, j;
  2506. if (components === 3) {
  2507. for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) {
  2508. buf[j] = data[i];
  2509. buf[j + 1] = data[i + 1];
  2510. buf[j + 2] = data[i + 2];
  2511. }
  2512. } else if (components === 1) {
  2513. for (i = 0, j = 0; i < rgbaLength; i += 4, j++) {
  2514. buf[j] = data[i];
  2515. }
  2516. }
  2517. resolve({ data: buf, width: width, height: height});
  2518. };
  2519. img.onerror = function () {
  2520. reject(new Error('JpegDecode failed to load image'));
  2521. };
  2522. img.src = imageUrl;
  2523. });
  2524. });
  2525. },
  2526. fetchDocument: function WorkerTransport_fetchDocument(loadingTask, source) {
  2527. this.loadingTask = loadingTask;
  2528. source.disableAutoFetch = PDFJS.disableAutoFetch;
  2529. source.disableStream = PDFJS.disableStream;
  2530. source.chunkedViewerLoading = !!this.pdfDataRangeTransport;
  2531. if (this.pdfDataRangeTransport) {
  2532. source.length = this.pdfDataRangeTransport.length;
  2533. source.initialData = this.pdfDataRangeTransport.initialData;
  2534. }
  2535. this.messageHandler.send('GetDocRequest', {
  2536. source: source,
  2537. disableRange: PDFJS.disableRange,
  2538. maxImageSize: PDFJS.maxImageSize,
  2539. cMapUrl: PDFJS.cMapUrl,
  2540. cMapPacked: PDFJS.cMapPacked,
  2541. disableFontFace: PDFJS.disableFontFace,
  2542. disableCreateObjectURL: PDFJS.disableCreateObjectURL,
  2543. verbosity: PDFJS.verbosity
  2544. });
  2545. },
  2546. getData: function WorkerTransport_getData() {
  2547. return this.messageHandler.sendWithPromise('GetData', null);
  2548. },
  2549. getPage: function WorkerTransport_getPage(pageNumber, capability) {
  2550. if (pageNumber <= 0 || pageNumber > this.numPages ||
  2551. (pageNumber|0) !== pageNumber) {
  2552. return Promise.reject(new Error('Invalid page request'));
  2553. }
  2554. var pageIndex = pageNumber - 1;
  2555. if (pageIndex in this.pagePromises) {
  2556. return this.pagePromises[pageIndex];
  2557. }
  2558. var promise = this.messageHandler.sendWithPromise('GetPage', {
  2559. pageIndex: pageIndex
  2560. }).then(function (pageInfo) {
  2561. var page = new PDFPageProxy(pageIndex, pageInfo, this);
  2562. this.pageCache[pageIndex] = page;
  2563. return page;
  2564. }.bind(this));
  2565. this.pagePromises[pageIndex] = promise;
  2566. return promise;
  2567. },
  2568. getPageIndex: function WorkerTransport_getPageIndexByRef(ref) {
  2569. return this.messageHandler.sendWithPromise('GetPageIndex', { ref: ref });
  2570. },
  2571. getAnnotations: function WorkerTransport_getAnnotations(pageIndex) {
  2572. return this.messageHandler.sendWithPromise('GetAnnotations',
  2573. { pageIndex: pageIndex });
  2574. },
  2575. getDestinations: function WorkerTransport_getDestinations() {
  2576. return this.messageHandler.sendWithPromise('GetDestinations', null);
  2577. },
  2578. getDestination: function WorkerTransport_getDestination(id) {
  2579. return this.messageHandler.sendWithPromise('GetDestination', { id: id } );
  2580. },
  2581. getAttachments: function WorkerTransport_getAttachments() {
  2582. return this.messageHandler.sendWithPromise('GetAttachments', null);
  2583. },
  2584. getJavaScript: function WorkerTransport_getJavaScript() {
  2585. return this.messageHandler.sendWithPromise('GetJavaScript', null);
  2586. },
  2587. getOutline: function WorkerTransport_getOutline() {
  2588. return this.messageHandler.sendWithPromise('GetOutline', null);
  2589. },
  2590. getMetadata: function WorkerTransport_getMetadata() {
  2591. return this.messageHandler.sendWithPromise('GetMetadata', null).
  2592. then(function transportMetadata(results) {
  2593. return {
  2594. info: results[0],
  2595. metadata: (results[1] ? new PDFJS.Metadata(results[1]) : null)
  2596. };
  2597. });
  2598. },
  2599. getStats: function WorkerTransport_getStats() {
  2600. return this.messageHandler.sendWithPromise('GetStats', null);
  2601. },
  2602. startCleanup: function WorkerTransport_startCleanup() {
  2603. this.messageHandler.sendWithPromise('Cleanup', null).
  2604. then(function endCleanup() {
  2605. for (var i = 0, ii = this.pageCache.length; i < ii; i++) {
  2606. var page = this.pageCache[i];
  2607. if (page) {
  2608. page.destroy();
  2609. }
  2610. }
  2611. this.commonObjs.clear();
  2612. FontLoader.clear();
  2613. }.bind(this));
  2614. }
  2615. };
  2616. return WorkerTransport;
  2617. })();
  2618. /**
  2619. * A PDF document and page is built of many objects. E.g. there are objects
  2620. * for fonts, images, rendering code and such. These objects might get processed
  2621. * inside of a worker. The `PDFObjects` implements some basic functions to
  2622. * manage these objects.
  2623. * @ignore
  2624. */
  2625. var PDFObjects = (function PDFObjectsClosure() {
  2626. function PDFObjects() {
  2627. this.objs = {};
  2628. }
  2629. PDFObjects.prototype = {
  2630. /**
  2631. * Internal function.
  2632. * Ensures there is an object defined for `objId`.
  2633. */
  2634. ensureObj: function PDFObjects_ensureObj(objId) {
  2635. if (this.objs[objId]) {
  2636. return this.objs[objId];
  2637. }
  2638. var obj = {
  2639. capability: createPromiseCapability(),
  2640. data: null,
  2641. resolved: false
  2642. };
  2643. this.objs[objId] = obj;
  2644. return obj;
  2645. },
  2646. /**
  2647. * If called *without* callback, this returns the data of `objId` but the
  2648. * object needs to be resolved. If it isn't, this function throws.
  2649. *
  2650. * If called *with* a callback, the callback is called with the data of the
  2651. * object once the object is resolved. That means, if you call this
  2652. * function and the object is already resolved, the callback gets called
  2653. * right away.
  2654. */
  2655. get: function PDFObjects_get(objId, callback) {
  2656. // If there is a callback, then the get can be async and the object is
  2657. // not required to be resolved right now
  2658. if (callback) {
  2659. this.ensureObj(objId).capability.promise.then(callback);
  2660. return null;
  2661. }
  2662. // If there isn't a callback, the user expects to get the resolved data
  2663. // directly.
  2664. var obj = this.objs[objId];
  2665. // If there isn't an object yet or the object isn't resolved, then the
  2666. // data isn't ready yet!
  2667. if (!obj || !obj.resolved) {
  2668. error('Requesting object that isn\'t resolved yet ' + objId);
  2669. }
  2670. return obj.data;
  2671. },
  2672. /**
  2673. * Resolves the object `objId` with optional `data`.
  2674. */
  2675. resolve: function PDFObjects_resolve(objId, data) {
  2676. var obj = this.ensureObj(objId);
  2677. obj.resolved = true;
  2678. obj.data = data;
  2679. obj.capability.resolve(data);
  2680. },
  2681. isResolved: function PDFObjects_isResolved(objId) {
  2682. var objs = this.objs;
  2683. if (!objs[objId]) {
  2684. return false;
  2685. } else {
  2686. return objs[objId].resolved;
  2687. }
  2688. },
  2689. hasData: function PDFObjects_hasData(objId) {
  2690. return this.isResolved(objId);
  2691. },
  2692. /**
  2693. * Returns the data of `objId` if object exists, null otherwise.
  2694. */
  2695. getData: function PDFObjects_getData(objId) {
  2696. var objs = this.objs;
  2697. if (!objs[objId] || !objs[objId].resolved) {
  2698. return null;
  2699. } else {
  2700. return objs[objId].data;
  2701. }
  2702. },
  2703. clear: function PDFObjects_clear() {
  2704. this.objs = {};
  2705. }
  2706. };
  2707. return PDFObjects;
  2708. })();
  2709. /**
  2710. * Allows controlling of the rendering tasks.
  2711. * @class
  2712. */
  2713. var RenderTask = (function RenderTaskClosure() {
  2714. function RenderTask(internalRenderTask) {
  2715. this._internalRenderTask = internalRenderTask;
  2716. /**
  2717. * Callback for incremental rendering -- a function that will be called
  2718. * each time the rendering is paused. To continue rendering call the
  2719. * function that is the first argument to the callback.
  2720. * @type {function}
  2721. */
  2722. this.onContinue = null;
  2723. }
  2724. RenderTask.prototype = /** @lends RenderTask.prototype */ {
  2725. /**
  2726. * Promise for rendering task completion.
  2727. * @return {Promise}
  2728. */
  2729. get promise() {
  2730. return this._internalRenderTask.capability.promise;
  2731. },
  2732. /**
  2733. * Cancels the rendering task. If the task is currently rendering it will
  2734. * not be cancelled until graphics pauses with a timeout. The promise that
  2735. * this object extends will resolved when cancelled.
  2736. */
  2737. cancel: function RenderTask_cancel() {
  2738. this._internalRenderTask.cancel();
  2739. },
  2740. /**
  2741. * Registers callbacks to indicate the rendering task completion.
  2742. *
  2743. * @param {function} onFulfilled The callback for the rendering completion.
  2744. * @param {function} onRejected The callback for the rendering failure.
  2745. * @return {Promise} A promise that is resolved after the onFulfilled or
  2746. * onRejected callback.
  2747. */
  2748. then: function RenderTask_then(onFulfilled, onRejected) {
  2749. return this.promise.then.apply(this.promise, arguments);
  2750. }
  2751. };
  2752. return RenderTask;
  2753. })();
  2754. /**
  2755. * For internal use only.
  2756. * @ignore
  2757. */
  2758. var InternalRenderTask = (function InternalRenderTaskClosure() {
  2759. function InternalRenderTask(callback, params, objs, commonObjs, operatorList,
  2760. pageNumber) {
  2761. this.callback = callback;
  2762. this.params = params;
  2763. this.objs = objs;
  2764. this.commonObjs = commonObjs;
  2765. this.operatorListIdx = null;
  2766. this.operatorList = operatorList;
  2767. this.pageNumber = pageNumber;
  2768. this.running = false;
  2769. this.graphicsReadyCallback = null;
  2770. this.graphicsReady = false;
  2771. this.useRequestAnimationFrame = false;
  2772. this.cancelled = false;
  2773. this.capability = createPromiseCapability();
  2774. this.task = new RenderTask(this);
  2775. // caching this-bound methods
  2776. this._continueBound = this._continue.bind(this);
  2777. this._scheduleNextBound = this._scheduleNext.bind(this);
  2778. this._nextBound = this._next.bind(this);
  2779. }
  2780. InternalRenderTask.prototype = {
  2781. initalizeGraphics:
  2782. function InternalRenderTask_initalizeGraphics(transparency) {
  2783. if (this.cancelled) {
  2784. return;
  2785. }
  2786. if (PDFJS.pdfBug && 'StepperManager' in globalScope &&
  2787. globalScope.StepperManager.enabled) {
  2788. this.stepper = globalScope.StepperManager.create(this.pageNumber - 1);
  2789. this.stepper.init(this.operatorList);
  2790. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  2791. }
  2792. var params = this.params;
  2793. this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs,
  2794. this.objs, params.imageLayer);
  2795. this.gfx.beginDrawing(params.viewport, transparency);
  2796. this.operatorListIdx = 0;
  2797. this.graphicsReady = true;
  2798. if (this.graphicsReadyCallback) {
  2799. this.graphicsReadyCallback();
  2800. }
  2801. },
  2802. cancel: function InternalRenderTask_cancel() {
  2803. this.running = false;
  2804. this.cancelled = true;
  2805. this.callback('cancelled');
  2806. },
  2807. operatorListChanged: function InternalRenderTask_operatorListChanged() {
  2808. if (!this.graphicsReady) {
  2809. if (!this.graphicsReadyCallback) {
  2810. this.graphicsReadyCallback = this._continueBound;
  2811. }
  2812. return;
  2813. }
  2814. if (this.stepper) {
  2815. this.stepper.updateOperatorList(this.operatorList);
  2816. }
  2817. if (this.running) {
  2818. return;
  2819. }
  2820. this._continue();
  2821. },
  2822. _continue: function InternalRenderTask__continue() {
  2823. this.running = true;
  2824. if (this.cancelled) {
  2825. return;
  2826. }
  2827. if (this.task.onContinue) {
  2828. this.task.onContinue.call(this.task, this._scheduleNextBound);
  2829. } else {
  2830. this._scheduleNext();
  2831. }
  2832. },
  2833. _scheduleNext: function InternalRenderTask__scheduleNext() {
  2834. if (this.useRequestAnimationFrame) {
  2835. window.requestAnimationFrame(this._nextBound);
  2836. } else {
  2837. Promise.resolve(undefined).then(this._nextBound);
  2838. }
  2839. },
  2840. _next: function InternalRenderTask__next() {
  2841. if (this.cancelled) {
  2842. return;
  2843. }
  2844. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList,
  2845. this.operatorListIdx,
  2846. this._continueBound,
  2847. this.stepper);
  2848. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  2849. this.running = false;
  2850. if (this.operatorList.lastChunk) {
  2851. this.gfx.endDrawing();
  2852. this.callback();
  2853. }
  2854. }
  2855. }
  2856. };
  2857. return InternalRenderTask;
  2858. })();
  2859. var Metadata = PDFJS.Metadata = (function MetadataClosure() {
  2860. function fixMetadata(meta) {
  2861. return meta.replace(/>\\376\\377([^<]+)/g, function(all, codes) {
  2862. var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g,
  2863. function(code, d1, d2, d3) {
  2864. return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1);
  2865. });
  2866. var chars = '';
  2867. for (var i = 0; i < bytes.length; i += 2) {
  2868. var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1);
  2869. chars += code >= 32 && code < 127 && code !== 60 && code !== 62 &&
  2870. code !== 38 && false ? String.fromCharCode(code) :
  2871. '&#x' + (0x10000 + code).toString(16).substring(1) + ';';
  2872. }
  2873. return '>' + chars;
  2874. });
  2875. }
  2876. function Metadata(meta) {
  2877. if (typeof meta === 'string') {
  2878. // Ghostscript produces invalid metadata
  2879. meta = fixMetadata(meta);
  2880. var parser = new DOMParser();
  2881. meta = parser.parseFromString(meta, 'application/xml');
  2882. } else if (!(meta instanceof Document)) {
  2883. error('Metadata: Invalid metadata object');
  2884. }
  2885. this.metaDocument = meta;
  2886. this.metadata = {};
  2887. this.parse();
  2888. }
  2889. Metadata.prototype = {
  2890. parse: function Metadata_parse() {
  2891. var doc = this.metaDocument;
  2892. var rdf = doc.documentElement;
  2893. if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta>
  2894. rdf = rdf.firstChild;
  2895. while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') {
  2896. rdf = rdf.nextSibling;
  2897. }
  2898. }
  2899. var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null;
  2900. if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) {
  2901. return;
  2902. }
  2903. var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength;
  2904. for (i = 0, length = children.length; i < length; i++) {
  2905. desc = children[i];
  2906. if (desc.nodeName.toLowerCase() !== 'rdf:description') {
  2907. continue;
  2908. }
  2909. for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) {
  2910. if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') {
  2911. entry = desc.childNodes[ii];
  2912. name = entry.nodeName.toLowerCase();
  2913. this.metadata[name] = entry.textContent.trim();
  2914. }
  2915. }
  2916. }
  2917. },
  2918. get: function Metadata_get(name) {
  2919. return this.metadata[name] || null;
  2920. },
  2921. has: function Metadata_has(name) {
  2922. return typeof this.metadata[name] !== 'undefined';
  2923. }
  2924. };
  2925. return Metadata;
  2926. })();
  2927. // <canvas> contexts store most of the state we need natively.
  2928. // However, PDF needs a bit more state, which we store here.
  2929. // Minimal font size that would be used during canvas fillText operations.
  2930. var MIN_FONT_SIZE = 16;
  2931. // Maximum font size that would be used during canvas fillText operations.
  2932. var MAX_FONT_SIZE = 100;
  2933. var MAX_GROUP_SIZE = 4096;
  2934. // Heuristic value used when enforcing minimum line widths.
  2935. var MIN_WIDTH_FACTOR = 0.65;
  2936. var COMPILE_TYPE3_GLYPHS = true;
  2937. var MAX_SIZE_TO_COMPILE = 1000;
  2938. var FULL_CHUNK_HEIGHT = 16;
  2939. function createScratchCanvas(width, height) {
  2940. var canvas = document.createElement('canvas');
  2941. canvas.width = width;
  2942. canvas.height = height;
  2943. return canvas;
  2944. }
  2945. function addContextCurrentTransform(ctx) {
  2946. // If the context doesn't expose a `mozCurrentTransform`, add a JS based one.
  2947. if (!ctx.mozCurrentTransform) {
  2948. ctx._originalSave = ctx.save;
  2949. ctx._originalRestore = ctx.restore;
  2950. ctx._originalRotate = ctx.rotate;
  2951. ctx._originalScale = ctx.scale;
  2952. ctx._originalTranslate = ctx.translate;
  2953. ctx._originalTransform = ctx.transform;
  2954. ctx._originalSetTransform = ctx.setTransform;
  2955. ctx._transformMatrix = ctx._transformMatrix || [1, 0, 0, 1, 0, 0];
  2956. ctx._transformStack = [];
  2957. Object.defineProperty(ctx, 'mozCurrentTransform', {
  2958. get: function getCurrentTransform() {
  2959. return this._transformMatrix;
  2960. }
  2961. });
  2962. Object.defineProperty(ctx, 'mozCurrentTransformInverse', {
  2963. get: function getCurrentTransformInverse() {
  2964. // Calculation done using WolframAlpha:
  2965. // http://www.wolframalpha.com/input/?
  2966. // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}}
  2967. var m = this._transformMatrix;
  2968. var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];
  2969. var ad_bc = a * d - b * c;
  2970. var bc_ad = b * c - a * d;
  2971. return [
  2972. d / ad_bc,
  2973. b / bc_ad,
  2974. c / bc_ad,
  2975. a / ad_bc,
  2976. (d * e - c * f) / bc_ad,
  2977. (b * e - a * f) / ad_bc
  2978. ];
  2979. }
  2980. });
  2981. ctx.save = function ctxSave() {
  2982. var old = this._transformMatrix;
  2983. this._transformStack.push(old);
  2984. this._transformMatrix = old.slice(0, 6);
  2985. this._originalSave();
  2986. };
  2987. ctx.restore = function ctxRestore() {
  2988. var prev = this._transformStack.pop();
  2989. if (prev) {
  2990. this._transformMatrix = prev;
  2991. this._originalRestore();
  2992. }
  2993. };
  2994. ctx.translate = function ctxTranslate(x, y) {
  2995. var m = this._transformMatrix;
  2996. m[4] = m[0] * x + m[2] * y + m[4];
  2997. m[5] = m[1] * x + m[3] * y + m[5];
  2998. this._originalTranslate(x, y);
  2999. };
  3000. ctx.scale = function ctxScale(x, y) {
  3001. var m = this._transformMatrix;
  3002. m[0] = m[0] * x;
  3003. m[1] = m[1] * x;
  3004. m[2] = m[2] * y;
  3005. m[3] = m[3] * y;
  3006. this._originalScale(x, y);
  3007. };
  3008. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  3009. var m = this._transformMatrix;
  3010. this._transformMatrix = [
  3011. m[0] * a + m[2] * b,
  3012. m[1] * a + m[3] * b,
  3013. m[0] * c + m[2] * d,
  3014. m[1] * c + m[3] * d,
  3015. m[0] * e + m[2] * f + m[4],
  3016. m[1] * e + m[3] * f + m[5]
  3017. ];
  3018. ctx._originalTransform(a, b, c, d, e, f);
  3019. };
  3020. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  3021. this._transformMatrix = [a, b, c, d, e, f];
  3022. ctx._originalSetTransform(a, b, c, d, e, f);
  3023. };
  3024. ctx.rotate = function ctxRotate(angle) {
  3025. var cosValue = Math.cos(angle);
  3026. var sinValue = Math.sin(angle);
  3027. var m = this._transformMatrix;
  3028. this._transformMatrix = [
  3029. m[0] * cosValue + m[2] * sinValue,
  3030. m[1] * cosValue + m[3] * sinValue,
  3031. m[0] * (-sinValue) + m[2] * cosValue,
  3032. m[1] * (-sinValue) + m[3] * cosValue,
  3033. m[4],
  3034. m[5]
  3035. ];
  3036. this._originalRotate(angle);
  3037. };
  3038. }
  3039. }
  3040. var CachedCanvases = (function CachedCanvasesClosure() {
  3041. var cache = {};
  3042. return {
  3043. getCanvas: function CachedCanvases_getCanvas(id, width, height,
  3044. trackTransform) {
  3045. var canvasEntry;
  3046. if (cache[id] !== undefined) {
  3047. canvasEntry = cache[id];
  3048. canvasEntry.canvas.width = width;
  3049. canvasEntry.canvas.height = height;
  3050. // reset canvas transform for emulated mozCurrentTransform, if needed
  3051. canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
  3052. } else {
  3053. var canvas = createScratchCanvas(width, height);
  3054. var ctx = canvas.getContext('2d');
  3055. if (trackTransform) {
  3056. addContextCurrentTransform(ctx);
  3057. }
  3058. cache[id] = canvasEntry = {canvas: canvas, context: ctx};
  3059. }
  3060. return canvasEntry;
  3061. },
  3062. clear: function () {
  3063. for (var id in cache) {
  3064. var canvasEntry = cache[id];
  3065. // Zeroing the width and height causes Firefox to release graphics
  3066. // resources immediately, which can greatly reduce memory consumption.
  3067. canvasEntry.canvas.width = 0;
  3068. canvasEntry.canvas.height = 0;
  3069. delete cache[id];
  3070. }
  3071. }
  3072. };
  3073. })();
  3074. function compileType3Glyph(imgData) {
  3075. var POINT_TO_PROCESS_LIMIT = 1000;
  3076. var width = imgData.width, height = imgData.height;
  3077. var i, j, j0, width1 = width + 1;
  3078. var points = new Uint8Array(width1 * (height + 1));
  3079. var POINT_TYPES =
  3080. new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  3081. // decodes bit-packed mask data
  3082. var lineSize = (width + 7) & ~7, data0 = imgData.data;
  3083. var data = new Uint8Array(lineSize * height), pos = 0, ii;
  3084. for (i = 0, ii = data0.length; i < ii; i++) {
  3085. var mask = 128, elem = data0[i];
  3086. while (mask > 0) {
  3087. data[pos++] = (elem & mask) ? 0 : 255;
  3088. mask >>= 1;
  3089. }
  3090. }
  3091. // finding iteresting points: every point is located between mask pixels,
  3092. // so there will be points of the (width + 1)x(height + 1) grid. Every point
  3093. // will have flags assigned based on neighboring mask pixels:
  3094. // 4 | 8
  3095. // --P--
  3096. // 2 | 1
  3097. // We are interested only in points with the flags:
  3098. // - outside corners: 1, 2, 4, 8;
  3099. // - inside corners: 7, 11, 13, 14;
  3100. // - and, intersections: 5, 10.
  3101. var count = 0;
  3102. pos = 0;
  3103. if (data[pos] !== 0) {
  3104. points[0] = 1;
  3105. ++count;
  3106. }
  3107. for (j = 1; j < width; j++) {
  3108. if (data[pos] !== data[pos + 1]) {
  3109. points[j] = data[pos] ? 2 : 1;
  3110. ++count;
  3111. }
  3112. pos++;
  3113. }
  3114. if (data[pos] !== 0) {
  3115. points[j] = 2;
  3116. ++count;
  3117. }
  3118. for (i = 1; i < height; i++) {
  3119. pos = i * lineSize;
  3120. j0 = i * width1;
  3121. if (data[pos - lineSize] !== data[pos]) {
  3122. points[j0] = data[pos] ? 1 : 8;
  3123. ++count;
  3124. }
  3125. // 'sum' is the position of the current pixel configuration in the 'TYPES'
  3126. // array (in order 8-1-2-4, so we can use '>>2' to shift the column).
  3127. var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  3128. for (j = 1; j < width; j++) {
  3129. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) +
  3130. (data[pos - lineSize + 1] ? 8 : 0);
  3131. if (POINT_TYPES[sum]) {
  3132. points[j0 + j] = POINT_TYPES[sum];
  3133. ++count;
  3134. }
  3135. pos++;
  3136. }
  3137. if (data[pos - lineSize] !== data[pos]) {
  3138. points[j0 + j] = data[pos] ? 2 : 4;
  3139. ++count;
  3140. }
  3141. if (count > POINT_TO_PROCESS_LIMIT) {
  3142. return null;
  3143. }
  3144. }
  3145. pos = lineSize * (height - 1);
  3146. j0 = i * width1;
  3147. if (data[pos] !== 0) {
  3148. points[j0] = 8;
  3149. ++count;
  3150. }
  3151. for (j = 1; j < width; j++) {
  3152. if (data[pos] !== data[pos + 1]) {
  3153. points[j0 + j] = data[pos] ? 4 : 8;
  3154. ++count;
  3155. }
  3156. pos++;
  3157. }
  3158. if (data[pos] !== 0) {
  3159. points[j0 + j] = 4;
  3160. ++count;
  3161. }
  3162. if (count > POINT_TO_PROCESS_LIMIT) {
  3163. return null;
  3164. }
  3165. // building outlines
  3166. var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  3167. var outlines = [];
  3168. for (i = 0; count && i <= height; i++) {
  3169. var p = i * width1;
  3170. var end = p + width;
  3171. while (p < end && !points[p]) {
  3172. p++;
  3173. }
  3174. if (p === end) {
  3175. continue;
  3176. }
  3177. var coords = [p % width1, i];
  3178. var type = points[p], p0 = p, pp;
  3179. do {
  3180. var step = steps[type];
  3181. do {
  3182. p += step;
  3183. } while (!points[p]);
  3184. pp = points[p];
  3185. if (pp !== 5 && pp !== 10) {
  3186. // set new direction
  3187. type = pp;
  3188. // delete mark
  3189. points[p] = 0;
  3190. } else { // type is 5 or 10, ie, a crossing
  3191. // set new direction
  3192. type = pp & ((0x33 * type) >> 4);
  3193. // set new type for "future hit"
  3194. points[p] &= (type >> 2 | type << 2);
  3195. }
  3196. coords.push(p % width1);
  3197. coords.push((p / width1) | 0);
  3198. --count;
  3199. } while (p0 !== p);
  3200. outlines.push(coords);
  3201. --i;
  3202. }
  3203. var drawOutline = function(c) {
  3204. c.save();
  3205. // the path shall be painted in [0..1]x[0..1] space
  3206. c.scale(1 / width, -1 / height);
  3207. c.translate(0, -height);
  3208. c.beginPath();
  3209. for (var i = 0, ii = outlines.length; i < ii; i++) {
  3210. var o = outlines[i];
  3211. c.moveTo(o[0], o[1]);
  3212. for (var j = 2, jj = o.length; j < jj; j += 2) {
  3213. c.lineTo(o[j], o[j+1]);
  3214. }
  3215. }
  3216. c.fill();
  3217. c.beginPath();
  3218. c.restore();
  3219. };
  3220. return drawOutline;
  3221. }
  3222. var CanvasExtraState = (function CanvasExtraStateClosure() {
  3223. function CanvasExtraState(old) {
  3224. // Are soft masks and alpha values shapes or opacities?
  3225. this.alphaIsShape = false;
  3226. this.fontSize = 0;
  3227. this.fontSizeScale = 1;
  3228. this.textMatrix = IDENTITY_MATRIX;
  3229. this.textMatrixScale = 1;
  3230. this.fontMatrix = FONT_IDENTITY_MATRIX;
  3231. this.leading = 0;
  3232. // Current point (in user coordinates)
  3233. this.x = 0;
  3234. this.y = 0;
  3235. // Start of text line (in text coordinates)
  3236. this.lineX = 0;
  3237. this.lineY = 0;
  3238. // Character and word spacing
  3239. this.charSpacing = 0;
  3240. this.wordSpacing = 0;
  3241. this.textHScale = 1;
  3242. this.textRenderingMode = TextRenderingMode.FILL;
  3243. this.textRise = 0;
  3244. // Default fore and background colors
  3245. this.fillColor = '#000000';
  3246. this.strokeColor = '#000000';
  3247. this.patternFill = false;
  3248. // Note: fill alpha applies to all non-stroking operations
  3249. this.fillAlpha = 1;
  3250. this.strokeAlpha = 1;
  3251. this.lineWidth = 1;
  3252. this.activeSMask = null; // nonclonable field (see the save method below)
  3253. this.old = old;
  3254. }
  3255. CanvasExtraState.prototype = {
  3256. clone: function CanvasExtraState_clone() {
  3257. return Object.create(this);
  3258. },
  3259. setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {
  3260. this.x = x;
  3261. this.y = y;
  3262. }
  3263. };
  3264. return CanvasExtraState;
  3265. })();
  3266. var CanvasGraphics = (function CanvasGraphicsClosure() {
  3267. // Defines the time the executeOperatorList is going to be executing
  3268. // before it stops and shedules a continue of execution.
  3269. var EXECUTION_TIME = 15;
  3270. // Defines the number of steps before checking the execution time
  3271. var EXECUTION_STEPS = 10;
  3272. function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) {
  3273. this.ctx = canvasCtx;
  3274. this.current = new CanvasExtraState();
  3275. this.stateStack = [];
  3276. this.pendingClip = null;
  3277. this.pendingEOFill = false;
  3278. this.res = null;
  3279. this.xobjs = null;
  3280. this.commonObjs = commonObjs;
  3281. this.objs = objs;
  3282. this.imageLayer = imageLayer;
  3283. this.groupStack = [];
  3284. this.processingType3 = null;
  3285. // Patterns are painted relative to the initial page/form transform, see pdf
  3286. // spec 8.7.2 NOTE 1.
  3287. this.baseTransform = null;
  3288. this.baseTransformStack = [];
  3289. this.groupLevel = 0;
  3290. this.smaskStack = [];
  3291. this.smaskCounter = 0;
  3292. this.tempSMask = null;
  3293. if (canvasCtx) {
  3294. // NOTE: if mozCurrentTransform is polyfilled, then the current state of
  3295. // the transformation must already be set in canvasCtx._transformMatrix.
  3296. addContextCurrentTransform(canvasCtx);
  3297. }
  3298. this.cachedGetSinglePixelWidth = null;
  3299. }
  3300. function putBinaryImageData(ctx, imgData) {
  3301. if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) {
  3302. ctx.putImageData(imgData, 0, 0);
  3303. return;
  3304. }
  3305. // Put the image data to the canvas in chunks, rather than putting the
  3306. // whole image at once. This saves JS memory, because the ImageData object
  3307. // is smaller. It also possibly saves C++ memory within the implementation
  3308. // of putImageData(). (E.g. in Firefox we make two short-lived copies of
  3309. // the data passed to putImageData()). |n| shouldn't be too small, however,
  3310. // because too many putImageData() calls will slow things down.
  3311. //
  3312. // Note: as written, if the last chunk is partial, the putImageData() call
  3313. // will (conceptually) put pixels past the bounds of the canvas. But
  3314. // that's ok; any such pixels are ignored.
  3315. var height = imgData.height, width = imgData.width;
  3316. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  3317. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  3318. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  3319. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  3320. var srcPos = 0, destPos;
  3321. var src = imgData.data;
  3322. var dest = chunkImgData.data;
  3323. var i, j, thisChunkHeight, elemsInThisChunk;
  3324. // There are multiple forms in which the pixel data can be passed, and
  3325. // imgData.kind tells us which one this is.
  3326. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) {
  3327. // Grayscale, 1 bit per pixel (i.e. black-and-white).
  3328. var srcLength = src.byteLength;
  3329. var dest32 = PDFJS.hasCanvasTypedArrays ? new Uint32Array(dest.buffer) :
  3330. new Uint32ArrayView(dest);
  3331. var dest32DataLength = dest32.length;
  3332. var fullSrcDiff = (width + 7) >> 3;
  3333. var white = 0xFFFFFFFF;
  3334. var black = (PDFJS.isLittleEndian || !PDFJS.hasCanvasTypedArrays) ?
  3335. 0xFF000000 : 0x000000FF;
  3336. for (i = 0; i < totalChunks; i++) {
  3337. thisChunkHeight =
  3338. (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  3339. destPos = 0;
  3340. for (j = 0; j < thisChunkHeight; j++) {
  3341. var srcDiff = srcLength - srcPos;
  3342. var k = 0;
  3343. var kEnd = (srcDiff > fullSrcDiff) ? width : srcDiff * 8 - 7;
  3344. var kEndUnrolled = kEnd & ~7;
  3345. var mask = 0;
  3346. var srcByte = 0;
  3347. for (; k < kEndUnrolled; k += 8) {
  3348. srcByte = src[srcPos++];
  3349. dest32[destPos++] = (srcByte & 128) ? white : black;
  3350. dest32[destPos++] = (srcByte & 64) ? white : black;
  3351. dest32[destPos++] = (srcByte & 32) ? white : black;
  3352. dest32[destPos++] = (srcByte & 16) ? white : black;
  3353. dest32[destPos++] = (srcByte & 8) ? white : black;
  3354. dest32[destPos++] = (srcByte & 4) ? white : black;
  3355. dest32[destPos++] = (srcByte & 2) ? white : black;
  3356. dest32[destPos++] = (srcByte & 1) ? white : black;
  3357. }
  3358. for (; k < kEnd; k++) {
  3359. if (mask === 0) {
  3360. srcByte = src[srcPos++];
  3361. mask = 128;
  3362. }
  3363. dest32[destPos++] = (srcByte & mask) ? white : black;
  3364. mask >>= 1;
  3365. }
  3366. }
  3367. // We ran out of input. Make all remaining pixels transparent.
  3368. while (destPos < dest32DataLength) {
  3369. dest32[destPos++] = 0;
  3370. }
  3371. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  3372. }
  3373. } else if (imgData.kind === ImageKind.RGBA_32BPP) {
  3374. // RGBA, 32-bits per pixel.
  3375. j = 0;
  3376. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  3377. for (i = 0; i < fullChunks; i++) {
  3378. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  3379. srcPos += elemsInThisChunk;
  3380. ctx.putImageData(chunkImgData, 0, j);
  3381. j += FULL_CHUNK_HEIGHT;
  3382. }
  3383. if (i < totalChunks) {
  3384. elemsInThisChunk = width * partialChunkHeight * 4;
  3385. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  3386. ctx.putImageData(chunkImgData, 0, j);
  3387. }
  3388. } else if (imgData.kind === ImageKind.RGB_24BPP) {
  3389. // RGB, 24-bits per pixel.
  3390. thisChunkHeight = FULL_CHUNK_HEIGHT;
  3391. elemsInThisChunk = width * thisChunkHeight;
  3392. for (i = 0; i < totalChunks; i++) {
  3393. if (i >= fullChunks) {
  3394. thisChunkHeight = partialChunkHeight;
  3395. elemsInThisChunk = width * thisChunkHeight;
  3396. }
  3397. destPos = 0;
  3398. for (j = elemsInThisChunk; j--;) {
  3399. dest[destPos++] = src[srcPos++];
  3400. dest[destPos++] = src[srcPos++];
  3401. dest[destPos++] = src[srcPos++];
  3402. dest[destPos++] = 255;
  3403. }
  3404. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  3405. }
  3406. } else {
  3407. error('bad image kind: ' + imgData.kind);
  3408. }
  3409. }
  3410. function putBinaryImageMask(ctx, imgData) {
  3411. var height = imgData.height, width = imgData.width;
  3412. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  3413. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  3414. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  3415. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  3416. var srcPos = 0;
  3417. var src = imgData.data;
  3418. var dest = chunkImgData.data;
  3419. for (var i = 0; i < totalChunks; i++) {
  3420. var thisChunkHeight =
  3421. (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  3422. // Expand the mask so it can be used by the canvas. Any required
  3423. // inversion has already been handled.
  3424. var destPos = 3; // alpha component offset
  3425. for (var j = 0; j < thisChunkHeight; j++) {
  3426. var mask = 0;
  3427. for (var k = 0; k < width; k++) {
  3428. if (!mask) {
  3429. var elem = src[srcPos++];
  3430. mask = 128;
  3431. }
  3432. dest[destPos] = (elem & mask) ? 0 : 255;
  3433. destPos += 4;
  3434. mask >>= 1;
  3435. }
  3436. }
  3437. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  3438. }
  3439. }
  3440. function copyCtxState(sourceCtx, destCtx) {
  3441. var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha',
  3442. 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit',
  3443. 'globalCompositeOperation', 'font'];
  3444. for (var i = 0, ii = properties.length; i < ii; i++) {
  3445. var property = properties[i];
  3446. if (sourceCtx[property] !== undefined) {
  3447. destCtx[property] = sourceCtx[property];
  3448. }
  3449. }
  3450. if (sourceCtx.setLineDash !== undefined) {
  3451. destCtx.setLineDash(sourceCtx.getLineDash());
  3452. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  3453. } else if (sourceCtx.mozDashOffset !== undefined) {
  3454. destCtx.mozDash = sourceCtx.mozDash;
  3455. destCtx.mozDashOffset = sourceCtx.mozDashOffset;
  3456. }
  3457. }
  3458. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  3459. var length = bytes.length;
  3460. for (var i = 3; i < length; i += 4) {
  3461. var alpha = bytes[i];
  3462. if (alpha === 0) {
  3463. bytes[i - 3] = r0;
  3464. bytes[i - 2] = g0;
  3465. bytes[i - 1] = b0;
  3466. } else if (alpha < 255) {
  3467. var alpha_ = 255 - alpha;
  3468. bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) >> 8;
  3469. bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) >> 8;
  3470. bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) >> 8;
  3471. }
  3472. }
  3473. }
  3474. function composeSMaskAlpha(maskData, layerData) {
  3475. var length = maskData.length;
  3476. var scale = 1 / 255;
  3477. for (var i = 3; i < length; i += 4) {
  3478. var alpha = maskData[i];
  3479. layerData[i] = (layerData[i] * alpha * scale) | 0;
  3480. }
  3481. }
  3482. function composeSMaskLuminosity(maskData, layerData) {
  3483. var length = maskData.length;
  3484. for (var i = 3; i < length; i += 4) {
  3485. var y = (maskData[i - 3] * 77) + // * 0.3 / 255 * 0x10000
  3486. (maskData[i - 2] * 152) + // * 0.59 ....
  3487. (maskData[i - 1] * 28); // * 0.11 ....
  3488. layerData[i] = (layerData[i] * y) >> 16;
  3489. }
  3490. }
  3491. function genericComposeSMask(maskCtx, layerCtx, width, height,
  3492. subtype, backdrop) {
  3493. var hasBackdrop = !!backdrop;
  3494. var r0 = hasBackdrop ? backdrop[0] : 0;
  3495. var g0 = hasBackdrop ? backdrop[1] : 0;
  3496. var b0 = hasBackdrop ? backdrop[2] : 0;
  3497. var composeFn;
  3498. if (subtype === 'Luminosity') {
  3499. composeFn = composeSMaskLuminosity;
  3500. } else {
  3501. composeFn = composeSMaskAlpha;
  3502. }
  3503. // processing image in chunks to save memory
  3504. var PIXELS_TO_PROCESS = 1048576;
  3505. var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  3506. for (var row = 0; row < height; row += chunkSize) {
  3507. var chunkHeight = Math.min(chunkSize, height - row);
  3508. var maskData = maskCtx.getImageData(0, row, width, chunkHeight);
  3509. var layerData = layerCtx.getImageData(0, row, width, chunkHeight);
  3510. if (hasBackdrop) {
  3511. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  3512. }
  3513. composeFn(maskData.data, layerData.data);
  3514. maskCtx.putImageData(layerData, 0, row);
  3515. }
  3516. }
  3517. function composeSMask(ctx, smask, layerCtx) {
  3518. var mask = smask.canvas;
  3519. var maskCtx = smask.context;
  3520. ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY,
  3521. smask.offsetX, smask.offsetY);
  3522. var backdrop = smask.backdrop || null;
  3523. if (WebGLUtils.isEnabled) {
  3524. var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask,
  3525. {subtype: smask.subtype, backdrop: backdrop});
  3526. ctx.setTransform(1, 0, 0, 1, 0, 0);
  3527. ctx.drawImage(composed, smask.offsetX, smask.offsetY);
  3528. return;
  3529. }
  3530. genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height,
  3531. smask.subtype, backdrop);
  3532. ctx.drawImage(mask, 0, 0);
  3533. }
  3534. var LINE_CAP_STYLES = ['butt', 'round', 'square'];
  3535. var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
  3536. var NORMAL_CLIP = {};
  3537. var EO_CLIP = {};
  3538. CanvasGraphics.prototype = {
  3539. beginDrawing: function CanvasGraphics_beginDrawing(viewport, transparency) {
  3540. // For pdfs that use blend modes we have to clear the canvas else certain
  3541. // blend modes can look wrong since we'd be blending with a white
  3542. // backdrop. The problem with a transparent backdrop though is we then
  3543. // don't get sub pixel anti aliasing on text, so we fill with white if
  3544. // we can.
  3545. var width = this.ctx.canvas.width;
  3546. var height = this.ctx.canvas.height;
  3547. if (transparency) {
  3548. this.ctx.clearRect(0, 0, width, height);
  3549. } else {
  3550. this.ctx.mozOpaque = true;
  3551. this.ctx.save();
  3552. this.ctx.fillStyle = 'rgb(255, 255, 255)';
  3553. this.ctx.fillRect(0, 0, width, height);
  3554. this.ctx.restore();
  3555. }
  3556. var transform = viewport.transform;
  3557. this.ctx.save();
  3558. this.ctx.transform.apply(this.ctx, transform);
  3559. this.baseTransform = this.ctx.mozCurrentTransform.slice();
  3560. if (this.imageLayer) {
  3561. this.imageLayer.beginLayout();
  3562. }
  3563. },
  3564. executeOperatorList: function CanvasGraphics_executeOperatorList(
  3565. operatorList,
  3566. executionStartIdx, continueCallback,
  3567. stepper) {
  3568. var argsArray = operatorList.argsArray;
  3569. var fnArray = operatorList.fnArray;
  3570. var i = executionStartIdx || 0;
  3571. var argsArrayLen = argsArray.length;
  3572. // Sometimes the OperatorList to execute is empty.
  3573. if (argsArrayLen === i) {
  3574. return i;
  3575. }
  3576. var chunkOperations = (argsArrayLen - i > EXECUTION_STEPS &&
  3577. typeof continueCallback === 'function');
  3578. var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  3579. var steps = 0;
  3580. var commonObjs = this.commonObjs;
  3581. var objs = this.objs;
  3582. var fnId;
  3583. while (true) {
  3584. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  3585. stepper.breakIt(i, continueCallback);
  3586. return i;
  3587. }
  3588. fnId = fnArray[i];
  3589. if (fnId !== OPS.dependency) {
  3590. this[fnId].apply(this, argsArray[i]);
  3591. } else {
  3592. var deps = argsArray[i];
  3593. for (var n = 0, nn = deps.length; n < nn; n++) {
  3594. var depObjId = deps[n];
  3595. var common = depObjId[0] === 'g' && depObjId[1] === '_';
  3596. var objsPool = common ? commonObjs : objs;
  3597. // If the promise isn't resolved yet, add the continueCallback
  3598. // to the promise and bail out.
  3599. if (!objsPool.isResolved(depObjId)) {
  3600. objsPool.get(depObjId, continueCallback);
  3601. return i;
  3602. }
  3603. }
  3604. }
  3605. i++;
  3606. // If the entire operatorList was executed, stop as were done.
  3607. if (i === argsArrayLen) {
  3608. return i;
  3609. }
  3610. // If the execution took longer then a certain amount of time and
  3611. // `continueCallback` is specified, interrupt the execution.
  3612. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  3613. if (Date.now() > endTime) {
  3614. continueCallback();
  3615. return i;
  3616. }
  3617. steps = 0;
  3618. }
  3619. // If the operatorList isn't executed completely yet OR the execution
  3620. // time was short enough, do another execution round.
  3621. }
  3622. },
  3623. endDrawing: function CanvasGraphics_endDrawing() {
  3624. this.ctx.restore();
  3625. CachedCanvases.clear();
  3626. WebGLUtils.clear();
  3627. if (this.imageLayer) {
  3628. this.imageLayer.endLayout();
  3629. }
  3630. },
  3631. // Graphics state
  3632. setLineWidth: function CanvasGraphics_setLineWidth(width) {
  3633. this.current.lineWidth = width;
  3634. this.ctx.lineWidth = width;
  3635. },
  3636. setLineCap: function CanvasGraphics_setLineCap(style) {
  3637. this.ctx.lineCap = LINE_CAP_STYLES[style];
  3638. },
  3639. setLineJoin: function CanvasGraphics_setLineJoin(style) {
  3640. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  3641. },
  3642. setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {
  3643. this.ctx.miterLimit = limit;
  3644. },
  3645. setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {
  3646. var ctx = this.ctx;
  3647. if (ctx.setLineDash !== undefined) {
  3648. ctx.setLineDash(dashArray);
  3649. ctx.lineDashOffset = dashPhase;
  3650. } else {
  3651. ctx.mozDash = dashArray;
  3652. ctx.mozDashOffset = dashPhase;
  3653. }
  3654. },
  3655. setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {
  3656. // Maybe if we one day fully support color spaces this will be important
  3657. // for now we can ignore.
  3658. // TODO set rendering intent?
  3659. },
  3660. setFlatness: function CanvasGraphics_setFlatness(flatness) {
  3661. // There's no way to control this with canvas, but we can safely ignore.
  3662. // TODO set flatness?
  3663. },
  3664. setGState: function CanvasGraphics_setGState(states) {
  3665. for (var i = 0, ii = states.length; i < ii; i++) {
  3666. var state = states[i];
  3667. var key = state[0];
  3668. var value = state[1];
  3669. switch (key) {
  3670. case 'LW':
  3671. this.setLineWidth(value);
  3672. break;
  3673. case 'LC':
  3674. this.setLineCap(value);
  3675. break;
  3676. case 'LJ':
  3677. this.setLineJoin(value);
  3678. break;
  3679. case 'ML':
  3680. this.setMiterLimit(value);
  3681. break;
  3682. case 'D':
  3683. this.setDash(value[0], value[1]);
  3684. break;
  3685. case 'RI':
  3686. this.setRenderingIntent(value);
  3687. break;
  3688. case 'FL':
  3689. this.setFlatness(value);
  3690. break;
  3691. case 'Font':
  3692. this.setFont(value[0], value[1]);
  3693. break;
  3694. case 'CA':
  3695. this.current.strokeAlpha = state[1];
  3696. break;
  3697. case 'ca':
  3698. this.current.fillAlpha = state[1];
  3699. this.ctx.globalAlpha = state[1];
  3700. break;
  3701. case 'BM':
  3702. if (value && value.name && (value.name !== 'Normal')) {
  3703. var mode = value.name.replace(/([A-Z])/g,
  3704. function(c) {
  3705. return '-' + c.toLowerCase();
  3706. }
  3707. ).substring(1);
  3708. this.ctx.globalCompositeOperation = mode;
  3709. if (this.ctx.globalCompositeOperation !== mode) {
  3710. warn('globalCompositeOperation "' + mode +
  3711. '" is not supported');
  3712. }
  3713. } else {
  3714. this.ctx.globalCompositeOperation = 'source-over';
  3715. }
  3716. break;
  3717. case 'SMask':
  3718. if (this.current.activeSMask) {
  3719. this.endSMaskGroup();
  3720. }
  3721. this.current.activeSMask = value ? this.tempSMask : null;
  3722. if (this.current.activeSMask) {
  3723. this.beginSMaskGroup();
  3724. }
  3725. this.tempSMask = null;
  3726. break;
  3727. }
  3728. }
  3729. },
  3730. beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() {
  3731. var activeSMask = this.current.activeSMask;
  3732. var drawnWidth = activeSMask.canvas.width;
  3733. var drawnHeight = activeSMask.canvas.height;
  3734. var cacheId = 'smaskGroupAt' + this.groupLevel;
  3735. var scratchCanvas = CachedCanvases.getCanvas(
  3736. cacheId, drawnWidth, drawnHeight, true);
  3737. var currentCtx = this.ctx;
  3738. var currentTransform = currentCtx.mozCurrentTransform;
  3739. this.ctx.save();
  3740. var groupCtx = scratchCanvas.context;
  3741. groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
  3742. groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
  3743. groupCtx.transform.apply(groupCtx, currentTransform);
  3744. copyCtxState(currentCtx, groupCtx);
  3745. this.ctx = groupCtx;
  3746. this.setGState([
  3747. ['BM', 'Normal'],
  3748. ['ca', 1],
  3749. ['CA', 1]
  3750. ]);
  3751. this.groupStack.push(currentCtx);
  3752. this.groupLevel++;
  3753. },
  3754. endSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  3755. var groupCtx = this.ctx;
  3756. this.groupLevel--;
  3757. this.ctx = this.groupStack.pop();
  3758. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  3759. this.ctx.restore();
  3760. },
  3761. save: function CanvasGraphics_save() {
  3762. this.ctx.save();
  3763. var old = this.current;
  3764. this.stateStack.push(old);
  3765. this.current = old.clone();
  3766. this.current.activeSMask = null;
  3767. },
  3768. restore: function CanvasGraphics_restore() {
  3769. if (this.stateStack.length !== 0) {
  3770. if (this.current.activeSMask !== null) {
  3771. this.endSMaskGroup();
  3772. }
  3773. this.current = this.stateStack.pop();
  3774. this.ctx.restore();
  3775. this.cachedGetSinglePixelWidth = null;
  3776. }
  3777. },
  3778. transform: function CanvasGraphics_transform(a, b, c, d, e, f) {
  3779. this.ctx.transform(a, b, c, d, e, f);
  3780. this.cachedGetSinglePixelWidth = null;
  3781. },
  3782. // Path
  3783. constructPath: function CanvasGraphics_constructPath(ops, args) {
  3784. var ctx = this.ctx;
  3785. var current = this.current;
  3786. var x = current.x, y = current.y;
  3787. for (var i = 0, j = 0, ii = ops.length; i < ii; i++) {
  3788. switch (ops[i] | 0) {
  3789. case OPS.rectangle:
  3790. x = args[j++];
  3791. y = args[j++];
  3792. var width = args[j++];
  3793. var height = args[j++];
  3794. if (width === 0) {
  3795. width = this.getSinglePixelWidth();
  3796. }
  3797. if (height === 0) {
  3798. height = this.getSinglePixelWidth();
  3799. }
  3800. var xw = x + width;
  3801. var yh = y + height;
  3802. this.ctx.moveTo(x, y);
  3803. this.ctx.lineTo(xw, y);
  3804. this.ctx.lineTo(xw, yh);
  3805. this.ctx.lineTo(x, yh);
  3806. this.ctx.lineTo(x, y);
  3807. this.ctx.closePath();
  3808. break;
  3809. case OPS.moveTo:
  3810. x = args[j++];
  3811. y = args[j++];
  3812. ctx.moveTo(x, y);
  3813. break;
  3814. case OPS.lineTo:
  3815. x = args[j++];
  3816. y = args[j++];
  3817. ctx.lineTo(x, y);
  3818. break;
  3819. case OPS.curveTo:
  3820. x = args[j + 4];
  3821. y = args[j + 5];
  3822. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3],
  3823. x, y);
  3824. j += 6;
  3825. break;
  3826. case OPS.curveTo2:
  3827. ctx.bezierCurveTo(x, y, args[j], args[j + 1],
  3828. args[j + 2], args[j + 3]);
  3829. x = args[j + 2];
  3830. y = args[j + 3];
  3831. j += 4;
  3832. break;
  3833. case OPS.curveTo3:
  3834. x = args[j + 2];
  3835. y = args[j + 3];
  3836. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  3837. j += 4;
  3838. break;
  3839. case OPS.closePath:
  3840. ctx.closePath();
  3841. break;
  3842. }
  3843. }
  3844. current.setCurrentPoint(x, y);
  3845. },
  3846. closePath: function CanvasGraphics_closePath() {
  3847. this.ctx.closePath();
  3848. },
  3849. stroke: function CanvasGraphics_stroke(consumePath) {
  3850. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  3851. var ctx = this.ctx;
  3852. var strokeColor = this.current.strokeColor;
  3853. // Prevent drawing too thin lines by enforcing a minimum line width.
  3854. ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR,
  3855. this.current.lineWidth);
  3856. // For stroke we want to temporarily change the global alpha to the
  3857. // stroking alpha.
  3858. ctx.globalAlpha = this.current.strokeAlpha;
  3859. if (strokeColor && strokeColor.hasOwnProperty('type') &&
  3860. strokeColor.type === 'Pattern') {
  3861. // for patterns, we transform to pattern space, calculate
  3862. // the pattern, call stroke, and restore to user space
  3863. ctx.save();
  3864. ctx.strokeStyle = strokeColor.getPattern(ctx, this);
  3865. ctx.stroke();
  3866. ctx.restore();
  3867. } else {
  3868. ctx.stroke();
  3869. }
  3870. if (consumePath) {
  3871. this.consumePath();
  3872. }
  3873. // Restore the global alpha to the fill alpha
  3874. ctx.globalAlpha = this.current.fillAlpha;
  3875. },
  3876. closeStroke: function CanvasGraphics_closeStroke() {
  3877. this.closePath();
  3878. this.stroke();
  3879. },
  3880. fill: function CanvasGraphics_fill(consumePath) {
  3881. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  3882. var ctx = this.ctx;
  3883. var fillColor = this.current.fillColor;
  3884. var isPatternFill = this.current.patternFill;
  3885. var needRestore = false;
  3886. if (isPatternFill) {
  3887. ctx.save();
  3888. ctx.fillStyle = fillColor.getPattern(ctx, this);
  3889. needRestore = true;
  3890. }
  3891. if (this.pendingEOFill) {
  3892. if (ctx.mozFillRule !== undefined) {
  3893. ctx.mozFillRule = 'evenodd';
  3894. ctx.fill();
  3895. ctx.mozFillRule = 'nonzero';
  3896. } else {
  3897. try {
  3898. ctx.fill('evenodd');
  3899. } catch (ex) {
  3900. // shouldn't really happen, but browsers might think differently
  3901. ctx.fill();
  3902. }
  3903. }
  3904. this.pendingEOFill = false;
  3905. } else {
  3906. ctx.fill();
  3907. }
  3908. if (needRestore) {
  3909. ctx.restore();
  3910. }
  3911. if (consumePath) {
  3912. this.consumePath();
  3913. }
  3914. },
  3915. eoFill: function CanvasGraphics_eoFill() {
  3916. this.pendingEOFill = true;
  3917. this.fill();
  3918. },
  3919. fillStroke: function CanvasGraphics_fillStroke() {
  3920. this.fill(false);
  3921. this.stroke(false);
  3922. this.consumePath();
  3923. },
  3924. eoFillStroke: function CanvasGraphics_eoFillStroke() {
  3925. this.pendingEOFill = true;
  3926. this.fillStroke();
  3927. },
  3928. closeFillStroke: function CanvasGraphics_closeFillStroke() {
  3929. this.closePath();
  3930. this.fillStroke();
  3931. },
  3932. closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {
  3933. this.pendingEOFill = true;
  3934. this.closePath();
  3935. this.fillStroke();
  3936. },
  3937. endPath: function CanvasGraphics_endPath() {
  3938. this.consumePath();
  3939. },
  3940. // Clipping
  3941. clip: function CanvasGraphics_clip() {
  3942. this.pendingClip = NORMAL_CLIP;
  3943. },
  3944. eoClip: function CanvasGraphics_eoClip() {
  3945. this.pendingClip = EO_CLIP;
  3946. },
  3947. // Text
  3948. beginText: function CanvasGraphics_beginText() {
  3949. this.current.textMatrix = IDENTITY_MATRIX;
  3950. this.current.textMatrixScale = 1;
  3951. this.current.x = this.current.lineX = 0;
  3952. this.current.y = this.current.lineY = 0;
  3953. },
  3954. endText: function CanvasGraphics_endText() {
  3955. var paths = this.pendingTextPaths;
  3956. var ctx = this.ctx;
  3957. if (paths === undefined) {
  3958. ctx.beginPath();
  3959. return;
  3960. }
  3961. ctx.save();
  3962. ctx.beginPath();
  3963. for (var i = 0; i < paths.length; i++) {
  3964. var path = paths[i];
  3965. ctx.setTransform.apply(ctx, path.transform);
  3966. ctx.translate(path.x, path.y);
  3967. path.addToPath(ctx, path.fontSize);
  3968. }
  3969. ctx.restore();
  3970. ctx.clip();
  3971. ctx.beginPath();
  3972. delete this.pendingTextPaths;
  3973. },
  3974. setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {
  3975. this.current.charSpacing = spacing;
  3976. },
  3977. setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {
  3978. this.current.wordSpacing = spacing;
  3979. },
  3980. setHScale: function CanvasGraphics_setHScale(scale) {
  3981. this.current.textHScale = scale / 100;
  3982. },
  3983. setLeading: function CanvasGraphics_setLeading(leading) {
  3984. this.current.leading = -leading;
  3985. },
  3986. setFont: function CanvasGraphics_setFont(fontRefName, size) {
  3987. var fontObj = this.commonObjs.get(fontRefName);
  3988. var current = this.current;
  3989. if (!fontObj) {
  3990. error('Can\'t find font for ' + fontRefName);
  3991. }
  3992. current.fontMatrix = (fontObj.fontMatrix ?
  3993. fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
  3994. // A valid matrix needs all main diagonal elements to be non-zero
  3995. // This also ensures we bypass FF bugzilla bug #719844.
  3996. if (current.fontMatrix[0] === 0 ||
  3997. current.fontMatrix[3] === 0) {
  3998. warn('Invalid font matrix for font ' + fontRefName);
  3999. }
  4000. // The spec for Tf (setFont) says that 'size' specifies the font 'scale',
  4001. // and in some docs this can be negative (inverted x-y axes).
  4002. if (size < 0) {
  4003. size = -size;
  4004. current.fontDirection = -1;
  4005. } else {
  4006. current.fontDirection = 1;
  4007. }
  4008. this.current.font = fontObj;
  4009. this.current.fontSize = size;
  4010. if (fontObj.isType3Font) {
  4011. return; // we don't need ctx.font for Type3 fonts
  4012. }
  4013. var name = fontObj.loadedName || 'sans-serif';
  4014. var bold = fontObj.black ? (fontObj.bold ? '900' : 'bold') :
  4015. (fontObj.bold ? 'bold' : 'normal');
  4016. var italic = fontObj.italic ? 'italic' : 'normal';
  4017. var typeface = '"' + name + '", ' + fontObj.fallbackName;
  4018. // Some font backends cannot handle fonts below certain size.
  4019. // Keeping the font at minimal size and using the fontSizeScale to change
  4020. // the current transformation matrix before the fillText/strokeText.
  4021. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227
  4022. var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE :
  4023. size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size;
  4024. this.current.fontSizeScale = size / browserFontSize;
  4025. var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface;
  4026. this.ctx.font = rule;
  4027. },
  4028. setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {
  4029. this.current.textRenderingMode = mode;
  4030. },
  4031. setTextRise: function CanvasGraphics_setTextRise(rise) {
  4032. this.current.textRise = rise;
  4033. },
  4034. moveText: function CanvasGraphics_moveText(x, y) {
  4035. this.current.x = this.current.lineX += x;
  4036. this.current.y = this.current.lineY += y;
  4037. },
  4038. setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {
  4039. this.setLeading(-y);
  4040. this.moveText(x, y);
  4041. },
  4042. setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {
  4043. this.current.textMatrix = [a, b, c, d, e, f];
  4044. this.current.textMatrixScale = Math.sqrt(a * a + b * b);
  4045. this.current.x = this.current.lineX = 0;
  4046. this.current.y = this.current.lineY = 0;
  4047. },
  4048. nextLine: function CanvasGraphics_nextLine() {
  4049. this.moveText(0, this.current.leading);
  4050. },
  4051. paintChar: function CanvasGraphics_paintChar(character, x, y) {
  4052. var ctx = this.ctx;
  4053. var current = this.current;
  4054. var font = current.font;
  4055. var textRenderingMode = current.textRenderingMode;
  4056. var fontSize = current.fontSize / current.fontSizeScale;
  4057. var fillStrokeMode = textRenderingMode &
  4058. TextRenderingMode.FILL_STROKE_MASK;
  4059. var isAddToPathSet = !!(textRenderingMode &
  4060. TextRenderingMode.ADD_TO_PATH_FLAG);
  4061. var addToPath;
  4062. if (font.disableFontFace || isAddToPathSet) {
  4063. addToPath = font.getPathGenerator(this.commonObjs, character);
  4064. }
  4065. if (font.disableFontFace) {
  4066. ctx.save();
  4067. ctx.translate(x, y);
  4068. ctx.beginPath();
  4069. addToPath(ctx, fontSize);
  4070. if (fillStrokeMode === TextRenderingMode.FILL ||
  4071. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  4072. ctx.fill();
  4073. }
  4074. if (fillStrokeMode === TextRenderingMode.STROKE ||
  4075. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  4076. ctx.stroke();
  4077. }
  4078. ctx.restore();
  4079. } else {
  4080. if (fillStrokeMode === TextRenderingMode.FILL ||
  4081. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  4082. ctx.fillText(character, x, y);
  4083. }
  4084. if (fillStrokeMode === TextRenderingMode.STROKE ||
  4085. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  4086. ctx.strokeText(character, x, y);
  4087. }
  4088. }
  4089. if (isAddToPathSet) {
  4090. var paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  4091. paths.push({
  4092. transform: ctx.mozCurrentTransform,
  4093. x: x,
  4094. y: y,
  4095. fontSize: fontSize,
  4096. addToPath: addToPath
  4097. });
  4098. }
  4099. },
  4100. get isFontSubpixelAAEnabled() {
  4101. // Checks if anti-aliasing is enabled when scaled text is painted.
  4102. // On Windows GDI scaled fonts looks bad.
  4103. var ctx = document.createElement('canvas').getContext('2d');
  4104. ctx.scale(1.5, 1);
  4105. ctx.fillText('I', 0, 10);
  4106. var data = ctx.getImageData(0, 0, 10, 10).data;
  4107. var enabled = false;
  4108. for (var i = 3; i < data.length; i += 4) {
  4109. if (data[i] > 0 && data[i] < 255) {
  4110. enabled = true;
  4111. break;
  4112. }
  4113. }
  4114. return shadow(this, 'isFontSubpixelAAEnabled', enabled);
  4115. },
  4116. showText: function CanvasGraphics_showText(glyphs) {
  4117. var current = this.current;
  4118. var font = current.font;
  4119. if (font.isType3Font) {
  4120. return this.showType3Text(glyphs);
  4121. }
  4122. var fontSize = current.fontSize;
  4123. if (fontSize === 0) {
  4124. return;
  4125. }
  4126. var ctx = this.ctx;
  4127. var fontSizeScale = current.fontSizeScale;
  4128. var charSpacing = current.charSpacing;
  4129. var wordSpacing = current.wordSpacing;
  4130. var fontDirection = current.fontDirection;
  4131. var textHScale = current.textHScale * fontDirection;
  4132. var glyphsLength = glyphs.length;
  4133. var vertical = font.vertical;
  4134. var defaultVMetrics = font.defaultVMetrics;
  4135. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  4136. var simpleFillText =
  4137. current.textRenderingMode === TextRenderingMode.FILL &&
  4138. !font.disableFontFace;
  4139. ctx.save();
  4140. ctx.transform.apply(ctx, current.textMatrix);
  4141. ctx.translate(current.x, current.y + current.textRise);
  4142. if (fontDirection > 0) {
  4143. ctx.scale(textHScale, -1);
  4144. } else {
  4145. ctx.scale(textHScale, 1);
  4146. }
  4147. var lineWidth = current.lineWidth;
  4148. var scale = current.textMatrixScale;
  4149. if (scale === 0 || lineWidth === 0) {
  4150. var fillStrokeMode = current.textRenderingMode &
  4151. TextRenderingMode.FILL_STROKE_MASK;
  4152. if (fillStrokeMode === TextRenderingMode.STROKE ||
  4153. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  4154. this.cachedGetSinglePixelWidth = null;
  4155. lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR;
  4156. }
  4157. } else {
  4158. lineWidth /= scale;
  4159. }
  4160. if (fontSizeScale !== 1.0) {
  4161. ctx.scale(fontSizeScale, fontSizeScale);
  4162. lineWidth /= fontSizeScale;
  4163. }
  4164. ctx.lineWidth = lineWidth;
  4165. var x = 0, i;
  4166. for (i = 0; i < glyphsLength; ++i) {
  4167. var glyph = glyphs[i];
  4168. if (glyph === null) {
  4169. // word break
  4170. x += fontDirection * wordSpacing;
  4171. continue;
  4172. } else if (isNum(glyph)) {
  4173. x += -glyph * fontSize * 0.001;
  4174. continue;
  4175. }
  4176. var restoreNeeded = false;
  4177. var character = glyph.fontChar;
  4178. var accent = glyph.accent;
  4179. var scaledX, scaledY, scaledAccentX, scaledAccentY;
  4180. var width = glyph.width;
  4181. if (vertical) {
  4182. var vmetric, vx, vy;
  4183. vmetric = glyph.vmetric || defaultVMetrics;
  4184. vx = glyph.vmetric ? vmetric[1] : width * 0.5;
  4185. vx = -vx * widthAdvanceScale;
  4186. vy = vmetric[2] * widthAdvanceScale;
  4187. width = vmetric ? -vmetric[0] : width;
  4188. scaledX = vx / fontSizeScale;
  4189. scaledY = (x + vy) / fontSizeScale;
  4190. } else {
  4191. scaledX = x / fontSizeScale;
  4192. scaledY = 0;
  4193. }
  4194. if (font.remeasure && width > 0 && this.isFontSubpixelAAEnabled) {
  4195. // some standard fonts may not have the exact width, trying to
  4196. // rescale per character
  4197. var measuredWidth = ctx.measureText(character).width * 1000 /
  4198. fontSize * fontSizeScale;
  4199. var characterScaleX = width / measuredWidth;
  4200. restoreNeeded = true;
  4201. ctx.save();
  4202. ctx.scale(characterScaleX, 1);
  4203. scaledX /= characterScaleX;
  4204. }
  4205. if (simpleFillText && !accent) {
  4206. // common case
  4207. ctx.fillText(character, scaledX, scaledY);
  4208. } else {
  4209. this.paintChar(character, scaledX, scaledY);
  4210. if (accent) {
  4211. scaledAccentX = scaledX + accent.offset.x / fontSizeScale;
  4212. scaledAccentY = scaledY - accent.offset.y / fontSizeScale;
  4213. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY);
  4214. }
  4215. }
  4216. var charWidth = width * widthAdvanceScale + charSpacing * fontDirection;
  4217. x += charWidth;
  4218. if (restoreNeeded) {
  4219. ctx.restore();
  4220. }
  4221. }
  4222. if (vertical) {
  4223. current.y -= x * textHScale;
  4224. } else {
  4225. current.x += x * textHScale;
  4226. }
  4227. ctx.restore();
  4228. },
  4229. showType3Text: function CanvasGraphics_showType3Text(glyphs) {
  4230. // Type3 fonts - each glyph is a "mini-PDF"
  4231. var ctx = this.ctx;
  4232. var current = this.current;
  4233. var font = current.font;
  4234. var fontSize = current.fontSize;
  4235. var fontDirection = current.fontDirection;
  4236. var charSpacing = current.charSpacing;
  4237. var wordSpacing = current.wordSpacing;
  4238. var textHScale = current.textHScale * fontDirection;
  4239. var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
  4240. var glyphsLength = glyphs.length;
  4241. var isTextInvisible =
  4242. current.textRenderingMode === TextRenderingMode.INVISIBLE;
  4243. var i, glyph, width;
  4244. if (isTextInvisible || fontSize === 0) {
  4245. return;
  4246. }
  4247. this.cachedGetSinglePixelWidth = null;
  4248. ctx.save();
  4249. ctx.transform.apply(ctx, current.textMatrix);
  4250. ctx.translate(current.x, current.y);
  4251. ctx.scale(textHScale, fontDirection);
  4252. for (i = 0; i < glyphsLength; ++i) {
  4253. glyph = glyphs[i];
  4254. if (glyph === null) {
  4255. // word break
  4256. this.ctx.translate(wordSpacing, 0);
  4257. current.x += wordSpacing * textHScale;
  4258. continue;
  4259. } else if (isNum(glyph)) {
  4260. var spacingLength = -glyph * 0.001 * fontSize;
  4261. this.ctx.translate(spacingLength, 0);
  4262. current.x += spacingLength * textHScale;
  4263. continue;
  4264. }
  4265. var operatorList = font.charProcOperatorList[glyph.operatorListId];
  4266. if (!operatorList) {
  4267. warn('Type3 character \"' + glyph.operatorListId +
  4268. '\" is not available');
  4269. continue;
  4270. }
  4271. this.processingType3 = glyph;
  4272. this.save();
  4273. ctx.scale(fontSize, fontSize);
  4274. ctx.transform.apply(ctx, fontMatrix);
  4275. this.executeOperatorList(operatorList);
  4276. this.restore();
  4277. var transformed = Util.applyTransform([glyph.width, 0], fontMatrix);
  4278. width = transformed[0] * fontSize + charSpacing;
  4279. ctx.translate(width, 0);
  4280. current.x += width * textHScale;
  4281. }
  4282. ctx.restore();
  4283. this.processingType3 = null;
  4284. },
  4285. // Type3 fonts
  4286. setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {
  4287. // We can safely ignore this since the width should be the same
  4288. // as the width in the Widths array.
  4289. },
  4290. setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth,
  4291. yWidth,
  4292. llx,
  4293. lly,
  4294. urx,
  4295. ury) {
  4296. // TODO According to the spec we're also suppose to ignore any operators
  4297. // that set color or include images while processing this type3 font.
  4298. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  4299. this.clip();
  4300. this.endPath();
  4301. },
  4302. // Color
  4303. getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) {
  4304. var pattern;
  4305. if (IR[0] === 'TilingPattern') {
  4306. var color = IR[1];
  4307. pattern = new TilingPattern(IR, color, this.ctx, this.objs,
  4308. this.commonObjs, this.baseTransform);
  4309. } else {
  4310. pattern = getShadingPatternFromIR(IR);
  4311. }
  4312. return pattern;
  4313. },
  4314. setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) {
  4315. this.current.strokeColor = this.getColorN_Pattern(arguments);
  4316. },
  4317. setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) {
  4318. this.current.fillColor = this.getColorN_Pattern(arguments);
  4319. this.current.patternFill = true;
  4320. },
  4321. setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {
  4322. var color = Util.makeCssRgb(r, g, b);
  4323. this.ctx.strokeStyle = color;
  4324. this.current.strokeColor = color;
  4325. },
  4326. setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {
  4327. var color = Util.makeCssRgb(r, g, b);
  4328. this.ctx.fillStyle = color;
  4329. this.current.fillColor = color;
  4330. this.current.patternFill = false;
  4331. },
  4332. shadingFill: function CanvasGraphics_shadingFill(patternIR) {
  4333. var ctx = this.ctx;
  4334. this.save();
  4335. var pattern = getShadingPatternFromIR(patternIR);
  4336. ctx.fillStyle = pattern.getPattern(ctx, this, true);
  4337. var inv = ctx.mozCurrentTransformInverse;
  4338. if (inv) {
  4339. var canvas = ctx.canvas;
  4340. var width = canvas.width;
  4341. var height = canvas.height;
  4342. var bl = Util.applyTransform([0, 0], inv);
  4343. var br = Util.applyTransform([0, height], inv);
  4344. var ul = Util.applyTransform([width, 0], inv);
  4345. var ur = Util.applyTransform([width, height], inv);
  4346. var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  4347. var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  4348. var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  4349. var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  4350. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  4351. } else {
  4352. // HACK to draw the gradient onto an infinite rectangle.
  4353. // PDF gradients are drawn across the entire image while
  4354. // Canvas only allows gradients to be drawn in a rectangle
  4355. // The following bug should allow us to remove this.
  4356. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884
  4357. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  4358. }
  4359. this.restore();
  4360. },
  4361. // Images
  4362. beginInlineImage: function CanvasGraphics_beginInlineImage() {
  4363. error('Should not call beginInlineImage');
  4364. },
  4365. beginImageData: function CanvasGraphics_beginImageData() {
  4366. error('Should not call beginImageData');
  4367. },
  4368. paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix,
  4369. bbox) {
  4370. this.save();
  4371. this.baseTransformStack.push(this.baseTransform);
  4372. if (isArray(matrix) && 6 === matrix.length) {
  4373. this.transform.apply(this, matrix);
  4374. }
  4375. this.baseTransform = this.ctx.mozCurrentTransform;
  4376. if (isArray(bbox) && 4 === bbox.length) {
  4377. var width = bbox[2] - bbox[0];
  4378. var height = bbox[3] - bbox[1];
  4379. this.ctx.rect(bbox[0], bbox[1], width, height);
  4380. this.clip();
  4381. this.endPath();
  4382. }
  4383. },
  4384. paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {
  4385. this.restore();
  4386. this.baseTransform = this.baseTransformStack.pop();
  4387. },
  4388. beginGroup: function CanvasGraphics_beginGroup(group) {
  4389. this.save();
  4390. var currentCtx = this.ctx;
  4391. // TODO non-isolated groups - according to Rik at adobe non-isolated
  4392. // group results aren't usually that different and they even have tools
  4393. // that ignore this setting. Notes from Rik on implmenting:
  4394. // - When you encounter an transparency group, create a new canvas with
  4395. // the dimensions of the bbox
  4396. // - copy the content from the previous canvas to the new canvas
  4397. // - draw as usual
  4398. // - remove the backdrop alpha:
  4399. // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha
  4400. // value of your transparency group and 'alphaBackdrop' the alpha of the
  4401. // backdrop
  4402. // - remove background color:
  4403. // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)
  4404. if (!group.isolated) {
  4405. info('TODO: Support non-isolated groups.');
  4406. }
  4407. // TODO knockout - supposedly possible with the clever use of compositing
  4408. // modes.
  4409. if (group.knockout) {
  4410. warn('Knockout groups not supported.');
  4411. }
  4412. var currentTransform = currentCtx.mozCurrentTransform;
  4413. if (group.matrix) {
  4414. currentCtx.transform.apply(currentCtx, group.matrix);
  4415. }
  4416. assert(group.bbox, 'Bounding box is required.');
  4417. // Based on the current transform figure out how big the bounding box
  4418. // will actually be.
  4419. var bounds = Util.getAxialAlignedBoundingBox(
  4420. group.bbox,
  4421. currentCtx.mozCurrentTransform);
  4422. // Clip the bounding box to the current canvas.
  4423. var canvasBounds = [0,
  4424. 0,
  4425. currentCtx.canvas.width,
  4426. currentCtx.canvas.height];
  4427. bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  4428. // Use ceil in case we're between sizes so we don't create canvas that is
  4429. // too small and make the canvas at least 1x1 pixels.
  4430. var offsetX = Math.floor(bounds[0]);
  4431. var offsetY = Math.floor(bounds[1]);
  4432. var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  4433. var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  4434. var scaleX = 1, scaleY = 1;
  4435. if (drawnWidth > MAX_GROUP_SIZE) {
  4436. scaleX = drawnWidth / MAX_GROUP_SIZE;
  4437. drawnWidth = MAX_GROUP_SIZE;
  4438. }
  4439. if (drawnHeight > MAX_GROUP_SIZE) {
  4440. scaleY = drawnHeight / MAX_GROUP_SIZE;
  4441. drawnHeight = MAX_GROUP_SIZE;
  4442. }
  4443. var cacheId = 'groupAt' + this.groupLevel;
  4444. if (group.smask) {
  4445. // Using two cache entries is case if masks are used one after another.
  4446. cacheId += '_smask_' + ((this.smaskCounter++) % 2);
  4447. }
  4448. var scratchCanvas = CachedCanvases.getCanvas(
  4449. cacheId, drawnWidth, drawnHeight, true);
  4450. var groupCtx = scratchCanvas.context;
  4451. // Since we created a new canvas that is just the size of the bounding box
  4452. // we have to translate the group ctx.
  4453. groupCtx.scale(1 / scaleX, 1 / scaleY);
  4454. groupCtx.translate(-offsetX, -offsetY);
  4455. groupCtx.transform.apply(groupCtx, currentTransform);
  4456. if (group.smask) {
  4457. // Saving state and cached mask to be used in setGState.
  4458. this.smaskStack.push({
  4459. canvas: scratchCanvas.canvas,
  4460. context: groupCtx,
  4461. offsetX: offsetX,
  4462. offsetY: offsetY,
  4463. scaleX: scaleX,
  4464. scaleY: scaleY,
  4465. subtype: group.smask.subtype,
  4466. backdrop: group.smask.backdrop
  4467. });
  4468. } else {
  4469. // Setup the current ctx so when the group is popped we draw it at the
  4470. // right location.
  4471. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  4472. currentCtx.translate(offsetX, offsetY);
  4473. currentCtx.scale(scaleX, scaleY);
  4474. }
  4475. // The transparency group inherits all off the current graphics state
  4476. // except the blend mode, soft mask, and alpha constants.
  4477. copyCtxState(currentCtx, groupCtx);
  4478. this.ctx = groupCtx;
  4479. this.setGState([
  4480. ['BM', 'Normal'],
  4481. ['ca', 1],
  4482. ['CA', 1]
  4483. ]);
  4484. this.groupStack.push(currentCtx);
  4485. this.groupLevel++;
  4486. },
  4487. endGroup: function CanvasGraphics_endGroup(group) {
  4488. this.groupLevel--;
  4489. var groupCtx = this.ctx;
  4490. this.ctx = this.groupStack.pop();
  4491. // Turn off image smoothing to avoid sub pixel interpolation which can
  4492. // look kind of blurry for some pdfs.
  4493. if (this.ctx.imageSmoothingEnabled !== undefined) {
  4494. this.ctx.imageSmoothingEnabled = false;
  4495. } else {
  4496. this.ctx.mozImageSmoothingEnabled = false;
  4497. }
  4498. if (group.smask) {
  4499. this.tempSMask = this.smaskStack.pop();
  4500. } else {
  4501. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  4502. }
  4503. this.restore();
  4504. },
  4505. beginAnnotations: function CanvasGraphics_beginAnnotations() {
  4506. this.save();
  4507. this.current = new CanvasExtraState();
  4508. },
  4509. endAnnotations: function CanvasGraphics_endAnnotations() {
  4510. this.restore();
  4511. },
  4512. beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform,
  4513. matrix) {
  4514. this.save();
  4515. if (isArray(rect) && 4 === rect.length) {
  4516. var width = rect[2] - rect[0];
  4517. var height = rect[3] - rect[1];
  4518. this.ctx.rect(rect[0], rect[1], width, height);
  4519. this.clip();
  4520. this.endPath();
  4521. }
  4522. this.transform.apply(this, transform);
  4523. this.transform.apply(this, matrix);
  4524. },
  4525. endAnnotation: function CanvasGraphics_endAnnotation() {
  4526. this.restore();
  4527. },
  4528. paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {
  4529. var domImage = this.objs.get(objId);
  4530. if (!domImage) {
  4531. warn('Dependent image isn\'t ready yet');
  4532. return;
  4533. }
  4534. this.save();
  4535. var ctx = this.ctx;
  4536. // scale the image to the unit square
  4537. ctx.scale(1 / w, -1 / h);
  4538. ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height,
  4539. 0, -h, w, h);
  4540. if (this.imageLayer) {
  4541. var currentTransform = ctx.mozCurrentTransformInverse;
  4542. var position = this.getCanvasPosition(0, 0);
  4543. this.imageLayer.appendImage({
  4544. objId: objId,
  4545. left: position[0],
  4546. top: position[1],
  4547. width: w / currentTransform[0],
  4548. height: h / currentTransform[3]
  4549. });
  4550. }
  4551. this.restore();
  4552. },
  4553. paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {
  4554. var ctx = this.ctx;
  4555. var width = img.width, height = img.height;
  4556. var fillColor = this.current.fillColor;
  4557. var isPatternFill = this.current.patternFill;
  4558. var glyph = this.processingType3;
  4559. if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) {
  4560. if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
  4561. glyph.compiled =
  4562. compileType3Glyph({data: img.data, width: width, height: height});
  4563. } else {
  4564. glyph.compiled = null;
  4565. }
  4566. }
  4567. if (glyph && glyph.compiled) {
  4568. glyph.compiled(ctx);
  4569. return;
  4570. }
  4571. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  4572. var maskCtx = maskCanvas.context;
  4573. maskCtx.save();
  4574. putBinaryImageMask(maskCtx, img);
  4575. maskCtx.globalCompositeOperation = 'source-in';
  4576. maskCtx.fillStyle = isPatternFill ?
  4577. fillColor.getPattern(maskCtx, this) : fillColor;
  4578. maskCtx.fillRect(0, 0, width, height);
  4579. maskCtx.restore();
  4580. this.paintInlineImageXObject(maskCanvas.canvas);
  4581. },
  4582. paintImageMaskXObjectRepeat:
  4583. function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX,
  4584. scaleY, positions) {
  4585. var width = imgData.width;
  4586. var height = imgData.height;
  4587. var fillColor = this.current.fillColor;
  4588. var isPatternFill = this.current.patternFill;
  4589. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  4590. var maskCtx = maskCanvas.context;
  4591. maskCtx.save();
  4592. putBinaryImageMask(maskCtx, imgData);
  4593. maskCtx.globalCompositeOperation = 'source-in';
  4594. maskCtx.fillStyle = isPatternFill ?
  4595. fillColor.getPattern(maskCtx, this) : fillColor;
  4596. maskCtx.fillRect(0, 0, width, height);
  4597. maskCtx.restore();
  4598. var ctx = this.ctx;
  4599. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  4600. ctx.save();
  4601. ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]);
  4602. ctx.scale(1, -1);
  4603. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  4604. 0, -1, 1, 1);
  4605. ctx.restore();
  4606. }
  4607. },
  4608. paintImageMaskXObjectGroup:
  4609. function CanvasGraphics_paintImageMaskXObjectGroup(images) {
  4610. var ctx = this.ctx;
  4611. var fillColor = this.current.fillColor;
  4612. var isPatternFill = this.current.patternFill;
  4613. for (var i = 0, ii = images.length; i < ii; i++) {
  4614. var image = images[i];
  4615. var width = image.width, height = image.height;
  4616. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  4617. var maskCtx = maskCanvas.context;
  4618. maskCtx.save();
  4619. putBinaryImageMask(maskCtx, image);
  4620. maskCtx.globalCompositeOperation = 'source-in';
  4621. maskCtx.fillStyle = isPatternFill ?
  4622. fillColor.getPattern(maskCtx, this) : fillColor;
  4623. maskCtx.fillRect(0, 0, width, height);
  4624. maskCtx.restore();
  4625. ctx.save();
  4626. ctx.transform.apply(ctx, image.transform);
  4627. ctx.scale(1, -1);
  4628. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  4629. 0, -1, 1, 1);
  4630. ctx.restore();
  4631. }
  4632. },
  4633. paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
  4634. var imgData = this.objs.get(objId);
  4635. if (!imgData) {
  4636. warn('Dependent image isn\'t ready yet');
  4637. return;
  4638. }
  4639. this.paintInlineImageXObject(imgData);
  4640. },
  4641. paintImageXObjectRepeat:
  4642. function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY,
  4643. positions) {
  4644. var imgData = this.objs.get(objId);
  4645. if (!imgData) {
  4646. warn('Dependent image isn\'t ready yet');
  4647. return;
  4648. }
  4649. var width = imgData.width;
  4650. var height = imgData.height;
  4651. var map = [];
  4652. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  4653. map.push({transform: [scaleX, 0, 0, scaleY, positions[i],
  4654. positions[i + 1]], x: 0, y: 0, w: width, h: height});
  4655. }
  4656. this.paintInlineImageXObjectGroup(imgData, map);
  4657. },
  4658. paintInlineImageXObject:
  4659. function CanvasGraphics_paintInlineImageXObject(imgData) {
  4660. var width = imgData.width;
  4661. var height = imgData.height;
  4662. var ctx = this.ctx;
  4663. this.save();
  4664. // scale the image to the unit square
  4665. ctx.scale(1 / width, -1 / height);
  4666. var currentTransform = ctx.mozCurrentTransformInverse;
  4667. var a = currentTransform[0], b = currentTransform[1];
  4668. var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);
  4669. var c = currentTransform[2], d = currentTransform[3];
  4670. var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);
  4671. var imgToPaint, tmpCanvas;
  4672. // instanceof HTMLElement does not work in jsdom node.js module
  4673. if (imgData instanceof HTMLElement || !imgData.data) {
  4674. imgToPaint = imgData;
  4675. } else {
  4676. tmpCanvas = CachedCanvases.getCanvas('inlineImage', width, height);
  4677. var tmpCtx = tmpCanvas.context;
  4678. putBinaryImageData(tmpCtx, imgData);
  4679. imgToPaint = tmpCanvas.canvas;
  4680. }
  4681. var paintWidth = width, paintHeight = height;
  4682. var tmpCanvasId = 'prescale1';
  4683. // Vertial or horizontal scaling shall not be more than 2 to not loose the
  4684. // pixels during drawImage operation, painting on the temporary canvas(es)
  4685. // that are twice smaller in size
  4686. while ((widthScale > 2 && paintWidth > 1) ||
  4687. (heightScale > 2 && paintHeight > 1)) {
  4688. var newWidth = paintWidth, newHeight = paintHeight;
  4689. if (widthScale > 2 && paintWidth > 1) {
  4690. newWidth = Math.ceil(paintWidth / 2);
  4691. widthScale /= paintWidth / newWidth;
  4692. }
  4693. if (heightScale > 2 && paintHeight > 1) {
  4694. newHeight = Math.ceil(paintHeight / 2);
  4695. heightScale /= paintHeight / newHeight;
  4696. }
  4697. tmpCanvas = CachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
  4698. tmpCtx = tmpCanvas.context;
  4699. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  4700. tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  4701. 0, 0, newWidth, newHeight);
  4702. imgToPaint = tmpCanvas.canvas;
  4703. paintWidth = newWidth;
  4704. paintHeight = newHeight;
  4705. tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';
  4706. }
  4707. ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  4708. 0, -height, width, height);
  4709. if (this.imageLayer) {
  4710. var position = this.getCanvasPosition(0, -height);
  4711. this.imageLayer.appendImage({
  4712. imgData: imgData,
  4713. left: position[0],
  4714. top: position[1],
  4715. width: width / currentTransform[0],
  4716. height: height / currentTransform[3]
  4717. });
  4718. }
  4719. this.restore();
  4720. },
  4721. paintInlineImageXObjectGroup:
  4722. function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {
  4723. var ctx = this.ctx;
  4724. var w = imgData.width;
  4725. var h = imgData.height;
  4726. var tmpCanvas = CachedCanvases.getCanvas('inlineImage', w, h);
  4727. var tmpCtx = tmpCanvas.context;
  4728. putBinaryImageData(tmpCtx, imgData);
  4729. for (var i = 0, ii = map.length; i < ii; i++) {
  4730. var entry = map[i];
  4731. ctx.save();
  4732. ctx.transform.apply(ctx, entry.transform);
  4733. ctx.scale(1, -1);
  4734. ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h,
  4735. 0, -1, 1, 1);
  4736. if (this.imageLayer) {
  4737. var position = this.getCanvasPosition(entry.x, entry.y);
  4738. this.imageLayer.appendImage({
  4739. imgData: imgData,
  4740. left: position[0],
  4741. top: position[1],
  4742. width: w,
  4743. height: h
  4744. });
  4745. }
  4746. ctx.restore();
  4747. }
  4748. },
  4749. paintSolidColorImageMask:
  4750. function CanvasGraphics_paintSolidColorImageMask() {
  4751. this.ctx.fillRect(0, 0, 1, 1);
  4752. },
  4753. // Marked content
  4754. markPoint: function CanvasGraphics_markPoint(tag) {
  4755. // TODO Marked content.
  4756. },
  4757. markPointProps: function CanvasGraphics_markPointProps(tag, properties) {
  4758. // TODO Marked content.
  4759. },
  4760. beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {
  4761. // TODO Marked content.
  4762. },
  4763. beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(
  4764. tag, properties) {
  4765. // TODO Marked content.
  4766. },
  4767. endMarkedContent: function CanvasGraphics_endMarkedContent() {
  4768. // TODO Marked content.
  4769. },
  4770. // Compatibility
  4771. beginCompat: function CanvasGraphics_beginCompat() {
  4772. // TODO ignore undefined operators (should we do that anyway?)
  4773. },
  4774. endCompat: function CanvasGraphics_endCompat() {
  4775. // TODO stop ignoring undefined operators
  4776. },
  4777. // Helper functions
  4778. consumePath: function CanvasGraphics_consumePath() {
  4779. var ctx = this.ctx;
  4780. if (this.pendingClip) {
  4781. if (this.pendingClip === EO_CLIP) {
  4782. if (ctx.mozFillRule !== undefined) {
  4783. ctx.mozFillRule = 'evenodd';
  4784. ctx.clip();
  4785. ctx.mozFillRule = 'nonzero';
  4786. } else {
  4787. try {
  4788. ctx.clip('evenodd');
  4789. } catch (ex) {
  4790. // shouldn't really happen, but browsers might think differently
  4791. ctx.clip();
  4792. }
  4793. }
  4794. } else {
  4795. ctx.clip();
  4796. }
  4797. this.pendingClip = null;
  4798. }
  4799. ctx.beginPath();
  4800. },
  4801. getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {
  4802. if (this.cachedGetSinglePixelWidth === null) {
  4803. var inverse = this.ctx.mozCurrentTransformInverse;
  4804. // max of the current horizontal and vertical scale
  4805. this.cachedGetSinglePixelWidth = Math.sqrt(Math.max(
  4806. (inverse[0] * inverse[0] + inverse[1] * inverse[1]),
  4807. (inverse[2] * inverse[2] + inverse[3] * inverse[3])));
  4808. }
  4809. return this.cachedGetSinglePixelWidth;
  4810. },
  4811. getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {
  4812. var transform = this.ctx.mozCurrentTransform;
  4813. return [
  4814. transform[0] * x + transform[2] * y + transform[4],
  4815. transform[1] * x + transform[3] * y + transform[5]
  4816. ];
  4817. }
  4818. };
  4819. for (var op in OPS) {
  4820. CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
  4821. }
  4822. return CanvasGraphics;
  4823. })();
  4824. var WebGLUtils = (function WebGLUtilsClosure() {
  4825. function loadShader(gl, code, shaderType) {
  4826. var shader = gl.createShader(shaderType);
  4827. gl.shaderSource(shader, code);
  4828. gl.compileShader(shader);
  4829. var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  4830. if (!compiled) {
  4831. var errorMsg = gl.getShaderInfoLog(shader);
  4832. throw new Error('Error during shader compilation: ' + errorMsg);
  4833. }
  4834. return shader;
  4835. }
  4836. function createVertexShader(gl, code) {
  4837. return loadShader(gl, code, gl.VERTEX_SHADER);
  4838. }
  4839. function createFragmentShader(gl, code) {
  4840. return loadShader(gl, code, gl.FRAGMENT_SHADER);
  4841. }
  4842. function createProgram(gl, shaders) {
  4843. var program = gl.createProgram();
  4844. for (var i = 0, ii = shaders.length; i < ii; ++i) {
  4845. gl.attachShader(program, shaders[i]);
  4846. }
  4847. gl.linkProgram(program);
  4848. var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  4849. if (!linked) {
  4850. var errorMsg = gl.getProgramInfoLog(program);
  4851. throw new Error('Error during program linking: ' + errorMsg);
  4852. }
  4853. return program;
  4854. }
  4855. function createTexture(gl, image, textureId) {
  4856. gl.activeTexture(textureId);
  4857. var texture = gl.createTexture();
  4858. gl.bindTexture(gl.TEXTURE_2D, texture);
  4859. // Set the parameters so we can render any size image.
  4860. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4861. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4862. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  4863. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  4864. // Upload the image into the texture.
  4865. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  4866. return texture;
  4867. }
  4868. var currentGL, currentCanvas;
  4869. function generateGL() {
  4870. if (currentGL) {
  4871. return;
  4872. }
  4873. currentCanvas = document.createElement('canvas');
  4874. currentGL = currentCanvas.getContext('webgl',
  4875. { premultipliedalpha: false });
  4876. }
  4877. var smaskVertexShaderCode = '\
  4878. attribute vec2 a_position; \
  4879. attribute vec2 a_texCoord; \
  4880. \
  4881. uniform vec2 u_resolution; \
  4882. \
  4883. varying vec2 v_texCoord; \
  4884. \
  4885. void main() { \
  4886. vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \
  4887. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  4888. \
  4889. v_texCoord = a_texCoord; \
  4890. } ';
  4891. var smaskFragmentShaderCode = '\
  4892. precision mediump float; \
  4893. \
  4894. uniform vec4 u_backdrop; \
  4895. uniform int u_subtype; \
  4896. uniform sampler2D u_image; \
  4897. uniform sampler2D u_mask; \
  4898. \
  4899. varying vec2 v_texCoord; \
  4900. \
  4901. void main() { \
  4902. vec4 imageColor = texture2D(u_image, v_texCoord); \
  4903. vec4 maskColor = texture2D(u_mask, v_texCoord); \
  4904. if (u_backdrop.a > 0.0) { \
  4905. maskColor.rgb = maskColor.rgb * maskColor.a + \
  4906. u_backdrop.rgb * (1.0 - maskColor.a); \
  4907. } \
  4908. float lum; \
  4909. if (u_subtype == 0) { \
  4910. lum = maskColor.a; \
  4911. } else { \
  4912. lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \
  4913. maskColor.b * 0.11; \
  4914. } \
  4915. imageColor.a *= lum; \
  4916. imageColor.rgb *= imageColor.a; \
  4917. gl_FragColor = imageColor; \
  4918. } ';
  4919. var smaskCache = null;
  4920. function initSmaskGL() {
  4921. var canvas, gl;
  4922. generateGL();
  4923. canvas = currentCanvas;
  4924. currentCanvas = null;
  4925. gl = currentGL;
  4926. currentGL = null;
  4927. // setup a GLSL program
  4928. var vertexShader = createVertexShader(gl, smaskVertexShaderCode);
  4929. var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode);
  4930. var program = createProgram(gl, [vertexShader, fragmentShader]);
  4931. gl.useProgram(program);
  4932. var cache = {};
  4933. cache.gl = gl;
  4934. cache.canvas = canvas;
  4935. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  4936. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  4937. cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop');
  4938. cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype');
  4939. var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');
  4940. var texLayerLocation = gl.getUniformLocation(program, 'u_image');
  4941. var texMaskLocation = gl.getUniformLocation(program, 'u_mask');
  4942. // provide texture coordinates for the rectangle.
  4943. var texCoordBuffer = gl.createBuffer();
  4944. gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
  4945. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  4946. 0.0, 0.0,
  4947. 1.0, 0.0,
  4948. 0.0, 1.0,
  4949. 0.0, 1.0,
  4950. 1.0, 0.0,
  4951. 1.0, 1.0]), gl.STATIC_DRAW);
  4952. gl.enableVertexAttribArray(texCoordLocation);
  4953. gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
  4954. gl.uniform1i(texLayerLocation, 0);
  4955. gl.uniform1i(texMaskLocation, 1);
  4956. smaskCache = cache;
  4957. }
  4958. function composeSMask(layer, mask, properties) {
  4959. var width = layer.width, height = layer.height;
  4960. if (!smaskCache) {
  4961. initSmaskGL();
  4962. }
  4963. var cache = smaskCache,canvas = cache.canvas, gl = cache.gl;
  4964. canvas.width = width;
  4965. canvas.height = height;
  4966. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  4967. gl.uniform2f(cache.resolutionLocation, width, height);
  4968. if (properties.backdrop) {
  4969. gl.uniform4f(cache.resolutionLocation, properties.backdrop[0],
  4970. properties.backdrop[1], properties.backdrop[2], 1);
  4971. } else {
  4972. gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0);
  4973. }
  4974. gl.uniform1i(cache.subtypeLocation,
  4975. properties.subtype === 'Luminosity' ? 1 : 0);
  4976. // Create a textures
  4977. var texture = createTexture(gl, layer, gl.TEXTURE0);
  4978. var maskTexture = createTexture(gl, mask, gl.TEXTURE1);
  4979. // Create a buffer and put a single clipspace rectangle in
  4980. // it (2 triangles)
  4981. var buffer = gl.createBuffer();
  4982. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  4983. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  4984. 0, 0,
  4985. width, 0,
  4986. 0, height,
  4987. 0, height,
  4988. width, 0,
  4989. width, height]), gl.STATIC_DRAW);
  4990. gl.enableVertexAttribArray(cache.positionLocation);
  4991. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  4992. // draw
  4993. gl.clearColor(0, 0, 0, 0);
  4994. gl.enable(gl.BLEND);
  4995. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  4996. gl.clear(gl.COLOR_BUFFER_BIT);
  4997. gl.drawArrays(gl.TRIANGLES, 0, 6);
  4998. gl.flush();
  4999. gl.deleteTexture(texture);
  5000. gl.deleteTexture(maskTexture);
  5001. gl.deleteBuffer(buffer);
  5002. return canvas;
  5003. }
  5004. var figuresVertexShaderCode = '\
  5005. attribute vec2 a_position; \
  5006. attribute vec3 a_color; \
  5007. \
  5008. uniform vec2 u_resolution; \
  5009. uniform vec2 u_scale; \
  5010. uniform vec2 u_offset; \
  5011. \
  5012. varying vec4 v_color; \
  5013. \
  5014. void main() { \
  5015. vec2 position = (a_position + u_offset) * u_scale; \
  5016. vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \
  5017. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  5018. \
  5019. v_color = vec4(a_color / 255.0, 1.0); \
  5020. } ';
  5021. var figuresFragmentShaderCode = '\
  5022. precision mediump float; \
  5023. \
  5024. varying vec4 v_color; \
  5025. \
  5026. void main() { \
  5027. gl_FragColor = v_color; \
  5028. } ';
  5029. var figuresCache = null;
  5030. function initFiguresGL() {
  5031. var canvas, gl;
  5032. generateGL();
  5033. canvas = currentCanvas;
  5034. currentCanvas = null;
  5035. gl = currentGL;
  5036. currentGL = null;
  5037. // setup a GLSL program
  5038. var vertexShader = createVertexShader(gl, figuresVertexShaderCode);
  5039. var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode);
  5040. var program = createProgram(gl, [vertexShader, fragmentShader]);
  5041. gl.useProgram(program);
  5042. var cache = {};
  5043. cache.gl = gl;
  5044. cache.canvas = canvas;
  5045. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5046. cache.scaleLocation = gl.getUniformLocation(program, 'u_scale');
  5047. cache.offsetLocation = gl.getUniformLocation(program, 'u_offset');
  5048. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5049. cache.colorLocation = gl.getAttribLocation(program, 'a_color');
  5050. figuresCache = cache;
  5051. }
  5052. function drawFigures(width, height, backgroundColor, figures, context) {
  5053. if (!figuresCache) {
  5054. initFiguresGL();
  5055. }
  5056. var cache = figuresCache, canvas = cache.canvas, gl = cache.gl;
  5057. canvas.width = width;
  5058. canvas.height = height;
  5059. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5060. gl.uniform2f(cache.resolutionLocation, width, height);
  5061. // count triangle points
  5062. var count = 0;
  5063. var i, ii, rows;
  5064. for (i = 0, ii = figures.length; i < ii; i++) {
  5065. switch (figures[i].type) {
  5066. case 'lattice':
  5067. rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0;
  5068. count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6;
  5069. break;
  5070. case 'triangles':
  5071. count += figures[i].coords.length;
  5072. break;
  5073. }
  5074. }
  5075. // transfer data
  5076. var coords = new Float32Array(count * 2);
  5077. var colors = new Uint8Array(count * 3);
  5078. var coordsMap = context.coords, colorsMap = context.colors;
  5079. var pIndex = 0, cIndex = 0;
  5080. for (i = 0, ii = figures.length; i < ii; i++) {
  5081. var figure = figures[i], ps = figure.coords, cs = figure.colors;
  5082. switch (figure.type) {
  5083. case 'lattice':
  5084. var cols = figure.verticesPerRow;
  5085. rows = (ps.length / cols) | 0;
  5086. for (var row = 1; row < rows; row++) {
  5087. var offset = row * cols + 1;
  5088. for (var col = 1; col < cols; col++, offset++) {
  5089. coords[pIndex] = coordsMap[ps[offset - cols - 1]];
  5090. coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1];
  5091. coords[pIndex + 2] = coordsMap[ps[offset - cols]];
  5092. coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1];
  5093. coords[pIndex + 4] = coordsMap[ps[offset - 1]];
  5094. coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1];
  5095. colors[cIndex] = colorsMap[cs[offset - cols - 1]];
  5096. colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1];
  5097. colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2];
  5098. colors[cIndex + 3] = colorsMap[cs[offset - cols]];
  5099. colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1];
  5100. colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2];
  5101. colors[cIndex + 6] = colorsMap[cs[offset - 1]];
  5102. colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1];
  5103. colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2];
  5104. coords[pIndex + 6] = coords[pIndex + 2];
  5105. coords[pIndex + 7] = coords[pIndex + 3];
  5106. coords[pIndex + 8] = coords[pIndex + 4];
  5107. coords[pIndex + 9] = coords[pIndex + 5];
  5108. coords[pIndex + 10] = coordsMap[ps[offset]];
  5109. coords[pIndex + 11] = coordsMap[ps[offset] + 1];
  5110. colors[cIndex + 9] = colors[cIndex + 3];
  5111. colors[cIndex + 10] = colors[cIndex + 4];
  5112. colors[cIndex + 11] = colors[cIndex + 5];
  5113. colors[cIndex + 12] = colors[cIndex + 6];
  5114. colors[cIndex + 13] = colors[cIndex + 7];
  5115. colors[cIndex + 14] = colors[cIndex + 8];
  5116. colors[cIndex + 15] = colorsMap[cs[offset]];
  5117. colors[cIndex + 16] = colorsMap[cs[offset] + 1];
  5118. colors[cIndex + 17] = colorsMap[cs[offset] + 2];
  5119. pIndex += 12;
  5120. cIndex += 18;
  5121. }
  5122. }
  5123. break;
  5124. case 'triangles':
  5125. for (var j = 0, jj = ps.length; j < jj; j++) {
  5126. coords[pIndex] = coordsMap[ps[j]];
  5127. coords[pIndex + 1] = coordsMap[ps[j] + 1];
  5128. colors[cIndex] = colorsMap[cs[i]];
  5129. colors[cIndex + 1] = colorsMap[cs[j] + 1];
  5130. colors[cIndex + 2] = colorsMap[cs[j] + 2];
  5131. pIndex += 2;
  5132. cIndex += 3;
  5133. }
  5134. break;
  5135. }
  5136. }
  5137. // draw
  5138. if (backgroundColor) {
  5139. gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255,
  5140. backgroundColor[2] / 255, 1.0);
  5141. } else {
  5142. gl.clearColor(0, 0, 0, 0);
  5143. }
  5144. gl.clear(gl.COLOR_BUFFER_BIT);
  5145. var coordsBuffer = gl.createBuffer();
  5146. gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer);
  5147. gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW);
  5148. gl.enableVertexAttribArray(cache.positionLocation);
  5149. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5150. var colorsBuffer = gl.createBuffer();
  5151. gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);
  5152. gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
  5153. gl.enableVertexAttribArray(cache.colorLocation);
  5154. gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false,
  5155. 0, 0);
  5156. gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY);
  5157. gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY);
  5158. gl.drawArrays(gl.TRIANGLES, 0, count);
  5159. gl.flush();
  5160. gl.deleteBuffer(coordsBuffer);
  5161. gl.deleteBuffer(colorsBuffer);
  5162. return canvas;
  5163. }
  5164. function cleanup() {
  5165. if (smaskCache && smaskCache.canvas) {
  5166. smaskCache.canvas.width = 0;
  5167. smaskCache.canvas.height = 0;
  5168. }
  5169. if (figuresCache && figuresCache.canvas) {
  5170. figuresCache.canvas.width = 0;
  5171. figuresCache.canvas.height = 0;
  5172. }
  5173. smaskCache = null;
  5174. figuresCache = null;
  5175. }
  5176. return {
  5177. get isEnabled() {
  5178. if (PDFJS.disableWebGL) {
  5179. return false;
  5180. }
  5181. var enabled = false;
  5182. try {
  5183. generateGL();
  5184. enabled = !!currentGL;
  5185. } catch (e) { }
  5186. return shadow(this, 'isEnabled', enabled);
  5187. },
  5188. composeSMask: composeSMask,
  5189. drawFigures: drawFigures,
  5190. clear: cleanup
  5191. };
  5192. })();
  5193. var ShadingIRs = {};
  5194. ShadingIRs.RadialAxial = {
  5195. fromIR: function RadialAxial_fromIR(raw) {
  5196. var type = raw[1];
  5197. var colorStops = raw[2];
  5198. var p0 = raw[3];
  5199. var p1 = raw[4];
  5200. var r0 = raw[5];
  5201. var r1 = raw[6];
  5202. return {
  5203. type: 'Pattern',
  5204. getPattern: function RadialAxial_getPattern(ctx) {
  5205. var grad;
  5206. if (type === 'axial') {
  5207. grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
  5208. } else if (type === 'radial') {
  5209. grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);
  5210. }
  5211. for (var i = 0, ii = colorStops.length; i < ii; ++i) {
  5212. var c = colorStops[i];
  5213. grad.addColorStop(c[0], c[1]);
  5214. }
  5215. return grad;
  5216. }
  5217. };
  5218. }
  5219. };
  5220. var createMeshCanvas = (function createMeshCanvasClosure() {
  5221. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  5222. // Very basic Gouraud-shaded triangle rasterization algorithm.
  5223. var coords = context.coords, colors = context.colors;
  5224. var bytes = data.data, rowSize = data.width * 4;
  5225. var tmp;
  5226. if (coords[p1 + 1] > coords[p2 + 1]) {
  5227. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5228. }
  5229. if (coords[p2 + 1] > coords[p3 + 1]) {
  5230. tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp;
  5231. }
  5232. if (coords[p1 + 1] > coords[p2 + 1]) {
  5233. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5234. }
  5235. var x1 = (coords[p1] + context.offsetX) * context.scaleX;
  5236. var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  5237. var x2 = (coords[p2] + context.offsetX) * context.scaleX;
  5238. var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  5239. var x3 = (coords[p3] + context.offsetX) * context.scaleX;
  5240. var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  5241. if (y1 >= y3) {
  5242. return;
  5243. }
  5244. var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2];
  5245. var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2];
  5246. var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2];
  5247. var minY = Math.round(y1), maxY = Math.round(y3);
  5248. var xa, car, cag, cab;
  5249. var xb, cbr, cbg, cbb;
  5250. var k;
  5251. for (var y = minY; y <= maxY; y++) {
  5252. if (y < y2) {
  5253. k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2);
  5254. xa = x1 - (x1 - x2) * k;
  5255. car = c1r - (c1r - c2r) * k;
  5256. cag = c1g - (c1g - c2g) * k;
  5257. cab = c1b - (c1b - c2b) * k;
  5258. } else {
  5259. k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3);
  5260. xa = x2 - (x2 - x3) * k;
  5261. car = c2r - (c2r - c3r) * k;
  5262. cag = c2g - (c2g - c3g) * k;
  5263. cab = c2b - (c2b - c3b) * k;
  5264. }
  5265. k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3);
  5266. xb = x1 - (x1 - x3) * k;
  5267. cbr = c1r - (c1r - c3r) * k;
  5268. cbg = c1g - (c1g - c3g) * k;
  5269. cbb = c1b - (c1b - c3b) * k;
  5270. var x1_ = Math.round(Math.min(xa, xb));
  5271. var x2_ = Math.round(Math.max(xa, xb));
  5272. var j = rowSize * y + x1_ * 4;
  5273. for (var x = x1_; x <= x2_; x++) {
  5274. k = (xa - x) / (xa - xb);
  5275. k = k < 0 ? 0 : k > 1 ? 1 : k;
  5276. bytes[j++] = (car - (car - cbr) * k) | 0;
  5277. bytes[j++] = (cag - (cag - cbg) * k) | 0;
  5278. bytes[j++] = (cab - (cab - cbb) * k) | 0;
  5279. bytes[j++] = 255;
  5280. }
  5281. }
  5282. }
  5283. function drawFigure(data, figure, context) {
  5284. var ps = figure.coords;
  5285. var cs = figure.colors;
  5286. var i, ii;
  5287. switch (figure.type) {
  5288. case 'lattice':
  5289. var verticesPerRow = figure.verticesPerRow;
  5290. var rows = Math.floor(ps.length / verticesPerRow) - 1;
  5291. var cols = verticesPerRow - 1;
  5292. for (i = 0; i < rows; i++) {
  5293. var q = i * verticesPerRow;
  5294. for (var j = 0; j < cols; j++, q++) {
  5295. drawTriangle(data, context,
  5296. ps[q], ps[q + 1], ps[q + verticesPerRow],
  5297. cs[q], cs[q + 1], cs[q + verticesPerRow]);
  5298. drawTriangle(data, context,
  5299. ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow],
  5300. cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  5301. }
  5302. }
  5303. break;
  5304. case 'triangles':
  5305. for (i = 0, ii = ps.length; i < ii; i += 3) {
  5306. drawTriangle(data, context,
  5307. ps[i], ps[i + 1], ps[i + 2],
  5308. cs[i], cs[i + 1], cs[i + 2]);
  5309. }
  5310. break;
  5311. default:
  5312. error('illigal figure');
  5313. break;
  5314. }
  5315. }
  5316. function createMeshCanvas(bounds, combinesScale, coords, colors, figures,
  5317. backgroundColor) {
  5318. // we will increase scale on some weird factor to let antialiasing take
  5319. // care of "rough" edges
  5320. var EXPECTED_SCALE = 1.1;
  5321. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5322. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5323. var offsetX = Math.floor(bounds[0]);
  5324. var offsetY = Math.floor(bounds[1]);
  5325. var boundsWidth = Math.ceil(bounds[2]) - offsetX;
  5326. var boundsHeight = Math.ceil(bounds[3]) - offsetY;
  5327. var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] *
  5328. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5329. var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] *
  5330. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5331. var scaleX = boundsWidth / width;
  5332. var scaleY = boundsHeight / height;
  5333. var context = {
  5334. coords: coords,
  5335. colors: colors,
  5336. offsetX: -offsetX,
  5337. offsetY: -offsetY,
  5338. scaleX: 1 / scaleX,
  5339. scaleY: 1 / scaleY
  5340. };
  5341. var canvas, tmpCanvas, i, ii;
  5342. if (WebGLUtils.isEnabled) {
  5343. canvas = WebGLUtils.drawFigures(width, height, backgroundColor,
  5344. figures, context);
  5345. // https://bugzilla.mozilla.org/show_bug.cgi?id=972126
  5346. tmpCanvas = CachedCanvases.getCanvas('mesh', width, height, false);
  5347. tmpCanvas.context.drawImage(canvas, 0, 0);
  5348. canvas = tmpCanvas.canvas;
  5349. } else {
  5350. tmpCanvas = CachedCanvases.getCanvas('mesh', width, height, false);
  5351. var tmpCtx = tmpCanvas.context;
  5352. var data = tmpCtx.createImageData(width, height);
  5353. if (backgroundColor) {
  5354. var bytes = data.data;
  5355. for (i = 0, ii = bytes.length; i < ii; i += 4) {
  5356. bytes[i] = backgroundColor[0];
  5357. bytes[i + 1] = backgroundColor[1];
  5358. bytes[i + 2] = backgroundColor[2];
  5359. bytes[i + 3] = 255;
  5360. }
  5361. }
  5362. for (i = 0; i < figures.length; i++) {
  5363. drawFigure(data, figures[i], context);
  5364. }
  5365. tmpCtx.putImageData(data, 0, 0);
  5366. canvas = tmpCanvas.canvas;
  5367. }
  5368. return {canvas: canvas, offsetX: offsetX, offsetY: offsetY,
  5369. scaleX: scaleX, scaleY: scaleY};
  5370. }
  5371. return createMeshCanvas;
  5372. })();
  5373. ShadingIRs.Mesh = {
  5374. fromIR: function Mesh_fromIR(raw) {
  5375. //var type = raw[1];
  5376. var coords = raw[2];
  5377. var colors = raw[3];
  5378. var figures = raw[4];
  5379. var bounds = raw[5];
  5380. var matrix = raw[6];
  5381. //var bbox = raw[7];
  5382. var background = raw[8];
  5383. return {
  5384. type: 'Pattern',
  5385. getPattern: function Mesh_getPattern(ctx, owner, shadingFill) {
  5386. var scale;
  5387. if (shadingFill) {
  5388. scale = Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);
  5389. } else {
  5390. // Obtain scale from matrix and current transformation matrix.
  5391. scale = Util.singularValueDecompose2dScale(owner.baseTransform);
  5392. if (matrix) {
  5393. var matrixScale = Util.singularValueDecompose2dScale(matrix);
  5394. scale = [scale[0] * matrixScale[0],
  5395. scale[1] * matrixScale[1]];
  5396. }
  5397. }
  5398. // Rasterizing on the main thread since sending/queue large canvases
  5399. // might cause OOM.
  5400. var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords,
  5401. colors, figures, shadingFill ? null : background);
  5402. if (!shadingFill) {
  5403. ctx.setTransform.apply(ctx, owner.baseTransform);
  5404. if (matrix) {
  5405. ctx.transform.apply(ctx, matrix);
  5406. }
  5407. }
  5408. ctx.translate(temporaryPatternCanvas.offsetX,
  5409. temporaryPatternCanvas.offsetY);
  5410. ctx.scale(temporaryPatternCanvas.scaleX,
  5411. temporaryPatternCanvas.scaleY);
  5412. return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat');
  5413. }
  5414. };
  5415. }
  5416. };
  5417. ShadingIRs.Dummy = {
  5418. fromIR: function Dummy_fromIR() {
  5419. return {
  5420. type: 'Pattern',
  5421. getPattern: function Dummy_fromIR_getPattern() {
  5422. return 'hotpink';
  5423. }
  5424. };
  5425. }
  5426. };
  5427. function getShadingPatternFromIR(raw) {
  5428. var shadingIR = ShadingIRs[raw[0]];
  5429. if (!shadingIR) {
  5430. error('Unknown IR type: ' + raw[0]);
  5431. }
  5432. return shadingIR.fromIR(raw);
  5433. }
  5434. var TilingPattern = (function TilingPatternClosure() {
  5435. var PaintType = {
  5436. COLORED: 1,
  5437. UNCOLORED: 2
  5438. };
  5439. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5440. function TilingPattern(IR, color, ctx, objs, commonObjs, baseTransform) {
  5441. this.operatorList = IR[2];
  5442. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  5443. this.bbox = IR[4];
  5444. this.xstep = IR[5];
  5445. this.ystep = IR[6];
  5446. this.paintType = IR[7];
  5447. this.tilingType = IR[8];
  5448. this.color = color;
  5449. this.objs = objs;
  5450. this.commonObjs = commonObjs;
  5451. this.baseTransform = baseTransform;
  5452. this.type = 'Pattern';
  5453. this.ctx = ctx;
  5454. }
  5455. TilingPattern.prototype = {
  5456. createPatternCanvas: function TilinPattern_createPatternCanvas(owner) {
  5457. var operatorList = this.operatorList;
  5458. var bbox = this.bbox;
  5459. var xstep = this.xstep;
  5460. var ystep = this.ystep;
  5461. var paintType = this.paintType;
  5462. var tilingType = this.tilingType;
  5463. var color = this.color;
  5464. var objs = this.objs;
  5465. var commonObjs = this.commonObjs;
  5466. info('TilingType: ' + tilingType);
  5467. var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];
  5468. var topLeft = [x0, y0];
  5469. // we want the canvas to be as large as the step size
  5470. var botRight = [x0 + xstep, y0 + ystep];
  5471. var width = botRight[0] - topLeft[0];
  5472. var height = botRight[1] - topLeft[1];
  5473. // Obtain scale from matrix and current transformation matrix.
  5474. var matrixScale = Util.singularValueDecompose2dScale(this.matrix);
  5475. var curMatrixScale = Util.singularValueDecompose2dScale(
  5476. this.baseTransform);
  5477. var combinedScale = [matrixScale[0] * curMatrixScale[0],
  5478. matrixScale[1] * curMatrixScale[1]];
  5479. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5480. // Use width and height values that are as close as possible to the end
  5481. // result when the pattern is used. Too low value makes the pattern look
  5482. // blurry. Too large value makes it look too crispy.
  5483. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])),
  5484. MAX_PATTERN_SIZE);
  5485. height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])),
  5486. MAX_PATTERN_SIZE);
  5487. var tmpCanvas = CachedCanvases.getCanvas('pattern', width, height, true);
  5488. var tmpCtx = tmpCanvas.context;
  5489. var graphics = new CanvasGraphics(tmpCtx, commonObjs, objs);
  5490. graphics.groupLevel = owner.groupLevel;
  5491. this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color);
  5492. this.setScale(width, height, xstep, ystep);
  5493. this.transformToScale(graphics);
  5494. // transform coordinates to pattern space
  5495. var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]];
  5496. graphics.transform.apply(graphics, tmpTranslate);
  5497. this.clipBbox(graphics, bbox, x0, y0, x1, y1);
  5498. graphics.executeOperatorList(operatorList);
  5499. return tmpCanvas.canvas;
  5500. },
  5501. setScale: function TilingPattern_setScale(width, height, xstep, ystep) {
  5502. this.scale = [width / xstep, height / ystep];
  5503. },
  5504. transformToScale: function TilingPattern_transformToScale(graphics) {
  5505. var scale = this.scale;
  5506. var tmpScale = [scale[0], 0, 0, scale[1], 0, 0];
  5507. graphics.transform.apply(graphics, tmpScale);
  5508. },
  5509. scaleToContext: function TilingPattern_scaleToContext() {
  5510. var scale = this.scale;
  5511. this.ctx.scale(1 / scale[0], 1 / scale[1]);
  5512. },
  5513. clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {
  5514. if (bbox && isArray(bbox) && bbox.length === 4) {
  5515. var bboxWidth = x1 - x0;
  5516. var bboxHeight = y1 - y0;
  5517. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  5518. graphics.clip();
  5519. graphics.endPath();
  5520. }
  5521. },
  5522. setFillAndStrokeStyleToContext:
  5523. function setFillAndStrokeStyleToContext(context, paintType, color) {
  5524. switch (paintType) {
  5525. case PaintType.COLORED:
  5526. var ctx = this.ctx;
  5527. context.fillStyle = ctx.fillStyle;
  5528. context.strokeStyle = ctx.strokeStyle;
  5529. break;
  5530. case PaintType.UNCOLORED:
  5531. var cssColor = Util.makeCssRgb(color[0], color[1], color[2]);
  5532. context.fillStyle = cssColor;
  5533. context.strokeStyle = cssColor;
  5534. break;
  5535. default:
  5536. error('Unsupported paint type: ' + paintType);
  5537. }
  5538. },
  5539. getPattern: function TilingPattern_getPattern(ctx, owner) {
  5540. var temporaryPatternCanvas = this.createPatternCanvas(owner);
  5541. ctx = this.ctx;
  5542. ctx.setTransform.apply(ctx, this.baseTransform);
  5543. ctx.transform.apply(ctx, this.matrix);
  5544. this.scaleToContext();
  5545. return ctx.createPattern(temporaryPatternCanvas, 'repeat');
  5546. }
  5547. };
  5548. return TilingPattern;
  5549. })();
  5550. PDFJS.disableFontFace = false;
  5551. var FontLoader = {
  5552. insertRule: function fontLoaderInsertRule(rule) {
  5553. var styleElement = document.getElementById('PDFJS_FONT_STYLE_TAG');
  5554. if (!styleElement) {
  5555. styleElement = document.createElement('style');
  5556. styleElement.id = 'PDFJS_FONT_STYLE_TAG';
  5557. document.documentElement.getElementsByTagName('head')[0].appendChild(
  5558. styleElement);
  5559. }
  5560. var styleSheet = styleElement.sheet;
  5561. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  5562. },
  5563. clear: function fontLoaderClear() {
  5564. var styleElement = document.getElementById('PDFJS_FONT_STYLE_TAG');
  5565. if (styleElement) {
  5566. styleElement.parentNode.removeChild(styleElement);
  5567. }
  5568. this.nativeFontFaces.forEach(function(nativeFontFace) {
  5569. document.fonts.delete(nativeFontFace);
  5570. });
  5571. this.nativeFontFaces.length = 0;
  5572. },
  5573. get loadTestFont() {
  5574. // This is a CFF font with 1 glyph for '.' that fills its entire width and
  5575. // height.
  5576. return shadow(this, 'loadTestFont', atob(
  5577. 'T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' +
  5578. 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' +
  5579. 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' +
  5580. 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' +
  5581. 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' +
  5582. 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' +
  5583. 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' +
  5584. 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' +
  5585. 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' +
  5586. 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' +
  5587. 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' +
  5588. 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' +
  5589. 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' +
  5590. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  5591. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  5592. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  5593. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' +
  5594. 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' +
  5595. 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' +
  5596. 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' +
  5597. 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' +
  5598. 'ABAAAAAAAAAAAD6AAAAAAAAA=='
  5599. ));
  5600. },
  5601. loadTestFontId: 0,
  5602. loadingContext: {
  5603. requests: [],
  5604. nextRequestId: 0
  5605. },
  5606. isSyncFontLoadingSupported: (function detectSyncFontLoadingSupport() {
  5607. if (isWorker) {
  5608. return false;
  5609. }
  5610. // User agent string sniffing is bad, but there is no reliable way to tell
  5611. // if font is fully loaded and ready to be used with canvas.
  5612. var userAgent = window.navigator.userAgent;
  5613. var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(userAgent);
  5614. if (m && m[1] >= 14) {
  5615. return true;
  5616. }
  5617. // TODO other browsers
  5618. if (userAgent === 'node') {
  5619. return true;
  5620. }
  5621. return false;
  5622. })(),
  5623. nativeFontFaces: [],
  5624. isFontLoadingAPISupported: (!isWorker && typeof document !== 'undefined' &&
  5625. !!document.fonts),
  5626. addNativeFontFace: function fontLoader_addNativeFontFace(nativeFontFace) {
  5627. this.nativeFontFaces.push(nativeFontFace);
  5628. document.fonts.add(nativeFontFace);
  5629. },
  5630. bind: function fontLoaderBind(fonts, callback) {
  5631. assert(!isWorker, 'bind() shall be called from main thread');
  5632. var rules = [];
  5633. var fontsToLoad = [];
  5634. var fontLoadPromises = [];
  5635. for (var i = 0, ii = fonts.length; i < ii; i++) {
  5636. var font = fonts[i];
  5637. // Add the font to the DOM only once or skip if the font
  5638. // is already loaded.
  5639. if (font.attached || font.loading === false) {
  5640. continue;
  5641. }
  5642. font.attached = true;
  5643. if (this.isFontLoadingAPISupported) {
  5644. var nativeFontFace = font.createNativeFontFace();
  5645. if (nativeFontFace) {
  5646. fontLoadPromises.push(nativeFontFace.loaded);
  5647. }
  5648. } else {
  5649. var rule = font.bindDOM();
  5650. if (rule) {
  5651. rules.push(rule);
  5652. fontsToLoad.push(font);
  5653. }
  5654. }
  5655. }
  5656. var request = FontLoader.queueLoadingCallback(callback);
  5657. if (this.isFontLoadingAPISupported) {
  5658. Promise.all(fontsToLoad).then(function() {
  5659. request.complete();
  5660. });
  5661. } else if (rules.length > 0 && !this.isSyncFontLoadingSupported) {
  5662. FontLoader.prepareFontLoadEvent(rules, fontsToLoad, request);
  5663. } else {
  5664. request.complete();
  5665. }
  5666. },
  5667. queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) {
  5668. function LoadLoader_completeRequest() {
  5669. assert(!request.end, 'completeRequest() cannot be called twice');
  5670. request.end = Date.now();
  5671. // sending all completed requests in order how they were queued
  5672. while (context.requests.length > 0 && context.requests[0].end) {
  5673. var otherRequest = context.requests.shift();
  5674. setTimeout(otherRequest.callback, 0);
  5675. }
  5676. }
  5677. var context = FontLoader.loadingContext;
  5678. var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++);
  5679. var request = {
  5680. id: requestId,
  5681. complete: LoadLoader_completeRequest,
  5682. callback: callback,
  5683. started: Date.now()
  5684. };
  5685. context.requests.push(request);
  5686. return request;
  5687. },
  5688. prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules,
  5689. fonts,
  5690. request) {
  5691. /** Hack begin */
  5692. // There's currently no event when a font has finished downloading so the
  5693. // following code is a dirty hack to 'guess' when a font is
  5694. // ready. It's assumed fonts are loaded in order, so add a known test
  5695. // font after the desired fonts and then test for the loading of that
  5696. // test font.
  5697. function int32(data, offset) {
  5698. return (data.charCodeAt(offset) << 24) |
  5699. (data.charCodeAt(offset + 1) << 16) |
  5700. (data.charCodeAt(offset + 2) << 8) |
  5701. (data.charCodeAt(offset + 3) & 0xff);
  5702. }
  5703. function spliceString(s, offset, remove, insert) {
  5704. var chunk1 = s.substr(0, offset);
  5705. var chunk2 = s.substr(offset + remove);
  5706. return chunk1 + insert + chunk2;
  5707. }
  5708. var i, ii;
  5709. var canvas = document.createElement('canvas');
  5710. canvas.width = 1;
  5711. canvas.height = 1;
  5712. var ctx = canvas.getContext('2d');
  5713. var called = 0;
  5714. function isFontReady(name, callback) {
  5715. called++;
  5716. // With setTimeout clamping this gives the font ~100ms to load.
  5717. if(called > 30) {
  5718. warn('Load test font never loaded.');
  5719. callback();
  5720. return;
  5721. }
  5722. ctx.font = '30px ' + name;
  5723. ctx.fillText('.', 0, 20);
  5724. var imageData = ctx.getImageData(0, 0, 1, 1);
  5725. if (imageData.data[3] > 0) {
  5726. callback();
  5727. return;
  5728. }
  5729. setTimeout(isFontReady.bind(null, name, callback));
  5730. }
  5731. var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++;
  5732. // Chromium seems to cache fonts based on a hash of the actual font data,
  5733. // so the font must be modified for each load test else it will appear to
  5734. // be loaded already.
  5735. // TODO: This could maybe be made faster by avoiding the btoa of the full
  5736. // font by splitting it in chunks before hand and padding the font id.
  5737. var data = this.loadTestFont;
  5738. var COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum)
  5739. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length,
  5740. loadTestFontId);
  5741. // CFF checksum is important for IE, adjusting it
  5742. var CFF_CHECKSUM_OFFSET = 16;
  5743. var XXXX_VALUE = 0x58585858; // the "comment" filled with 'X'
  5744. var checksum = int32(data, CFF_CHECKSUM_OFFSET);
  5745. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  5746. checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0;
  5747. }
  5748. if (i < loadTestFontId.length) { // align to 4 bytes boundary
  5749. checksum = (checksum - XXXX_VALUE +
  5750. int32(loadTestFontId + 'XXX', i)) | 0;
  5751. }
  5752. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
  5753. var url = 'url(data:font/opentype;base64,' + btoa(data) + ');';
  5754. var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' +
  5755. url + '}';
  5756. FontLoader.insertRule(rule);
  5757. var names = [];
  5758. for (i = 0, ii = fonts.length; i < ii; i++) {
  5759. names.push(fonts[i].loadedName);
  5760. }
  5761. names.push(loadTestFontId);
  5762. var div = document.createElement('div');
  5763. div.setAttribute('style',
  5764. 'visibility: hidden;' +
  5765. 'width: 10px; height: 10px;' +
  5766. 'position: absolute; top: 0px; left: 0px;');
  5767. for (i = 0, ii = names.length; i < ii; ++i) {
  5768. var span = document.createElement('span');
  5769. span.textContent = 'Hi';
  5770. span.style.fontFamily = names[i];
  5771. div.appendChild(span);
  5772. }
  5773. document.body.appendChild(div);
  5774. isFontReady(loadTestFontId, function() {
  5775. document.body.removeChild(div);
  5776. request.complete();
  5777. });
  5778. /** Hack end */
  5779. }
  5780. };
  5781. var FontFaceObject = (function FontFaceObjectClosure() {
  5782. function FontFaceObject(name, file, properties) {
  5783. this.compiledGlyphs = {};
  5784. if (arguments.length === 1) {
  5785. // importing translated data
  5786. var data = arguments[0];
  5787. for (var i in data) {
  5788. this[i] = data[i];
  5789. }
  5790. return;
  5791. }
  5792. }
  5793. FontFaceObject.prototype = {
  5794. createNativeFontFace: function FontFaceObject_createNativeFontFace() {
  5795. if (!this.data) {
  5796. return null;
  5797. }
  5798. if (PDFJS.disableFontFace) {
  5799. this.disableFontFace = true;
  5800. return null;
  5801. }
  5802. var nativeFontFace = new FontFace(this.loadedName, this.data, {});
  5803. FontLoader.addNativeFontFace(nativeFontFace);
  5804. if (PDFJS.pdfBug && 'FontInspector' in globalScope &&
  5805. globalScope['FontInspector'].enabled) {
  5806. globalScope['FontInspector'].fontAdded(this);
  5807. }
  5808. return nativeFontFace;
  5809. },
  5810. bindDOM: function FontFaceObject_bindDOM() {
  5811. if (!this.data) {
  5812. return null;
  5813. }
  5814. if (PDFJS.disableFontFace) {
  5815. this.disableFontFace = true;
  5816. return null;
  5817. }
  5818. var data = bytesToString(new Uint8Array(this.data));
  5819. var fontName = this.loadedName;
  5820. // Add the font-face rule to the document
  5821. var url = ('url(data:' + this.mimetype + ';base64,' +
  5822. window.btoa(data) + ');');
  5823. var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}';
  5824. FontLoader.insertRule(rule);
  5825. if (PDFJS.pdfBug && 'FontInspector' in globalScope &&
  5826. globalScope['FontInspector'].enabled) {
  5827. globalScope['FontInspector'].fontAdded(this, url);
  5828. }
  5829. return rule;
  5830. },
  5831. getPathGenerator: function FontLoader_getPathGenerator(objs, character) {
  5832. if (!(character in this.compiledGlyphs)) {
  5833. var js = objs.get(this.loadedName + '_path_' + character);
  5834. /*jshint -W054 */
  5835. this.compiledGlyphs[character] = new Function('c', 'size', js);
  5836. }
  5837. return this.compiledGlyphs[character];
  5838. }
  5839. };
  5840. return FontFaceObject;
  5841. })();
  5842. var ANNOT_MIN_SIZE = 10; // px
  5843. var AnnotationUtils = (function AnnotationUtilsClosure() {
  5844. // TODO(mack): This dupes some of the logic in CanvasGraphics.setFont()
  5845. function setTextStyles(element, item, fontObj) {
  5846. var style = element.style;
  5847. style.fontSize = item.fontSize + 'px';
  5848. style.direction = item.fontDirection < 0 ? 'rtl': 'ltr';
  5849. if (!fontObj) {
  5850. return;
  5851. }
  5852. style.fontWeight = fontObj.black ?
  5853. (fontObj.bold ? 'bolder' : 'bold') :
  5854. (fontObj.bold ? 'bold' : 'normal');
  5855. style.fontStyle = fontObj.italic ? 'italic' : 'normal';
  5856. var fontName = fontObj.loadedName;
  5857. var fontFamily = fontName ? '"' + fontName + '", ' : '';
  5858. // Use a reasonable default font if the font doesn't specify a fallback
  5859. var fallbackName = fontObj.fallbackName || 'Helvetica, sans-serif';
  5860. style.fontFamily = fontFamily + fallbackName;
  5861. }
  5862. function initContainer(item, drawBorder) {
  5863. var container = document.createElement('section');
  5864. var cstyle = container.style;
  5865. var width = item.rect[2] - item.rect[0];
  5866. var height = item.rect[3] - item.rect[1];
  5867. var bWidth = item.borderWidth || 0;
  5868. if (bWidth) {
  5869. width = width - 2 * bWidth;
  5870. height = height - 2 * bWidth;
  5871. cstyle.borderWidth = bWidth + 'px';
  5872. var color = item.color;
  5873. if (drawBorder && color) {
  5874. cstyle.borderStyle = 'solid';
  5875. cstyle.borderColor = Util.makeCssRgb(Math.round(color[0] * 255),
  5876. Math.round(color[1] * 255),
  5877. Math.round(color[2] * 255));
  5878. }
  5879. }
  5880. cstyle.width = width + 'px';
  5881. cstyle.height = height + 'px';
  5882. return container;
  5883. }
  5884. function getHtmlElementForTextWidgetAnnotation(item, commonObjs) {
  5885. var element = document.createElement('div');
  5886. var width = item.rect[2] - item.rect[0];
  5887. var height = item.rect[3] - item.rect[1];
  5888. element.style.width = width + 'px';
  5889. element.style.height = height + 'px';
  5890. element.style.display = 'table';
  5891. var content = document.createElement('div');
  5892. content.textContent = item.fieldValue;
  5893. var textAlignment = item.textAlignment;
  5894. content.style.textAlign = ['left', 'center', 'right'][textAlignment];
  5895. content.style.verticalAlign = 'middle';
  5896. content.style.display = 'table-cell';
  5897. var fontObj = item.fontRefName ?
  5898. commonObjs.getData(item.fontRefName) : null;
  5899. setTextStyles(content, item, fontObj);
  5900. element.appendChild(content);
  5901. return element;
  5902. }
  5903. function getHtmlElementForTextAnnotation(item) {
  5904. var rect = item.rect;
  5905. // sanity check because of OOo-generated PDFs
  5906. if ((rect[3] - rect[1]) < ANNOT_MIN_SIZE) {
  5907. rect[3] = rect[1] + ANNOT_MIN_SIZE;
  5908. }
  5909. if ((rect[2] - rect[0]) < ANNOT_MIN_SIZE) {
  5910. rect[2] = rect[0] + (rect[3] - rect[1]); // make it square
  5911. }
  5912. var container = initContainer(item, false);
  5913. container.className = 'annotText';
  5914. var image = document.createElement('img');
  5915. image.style.height = container.style.height;
  5916. image.style.width = container.style.width;
  5917. var iconName = item.name;
  5918. image.src = PDFJS.imageResourcesPath + 'annotation-' +
  5919. iconName.toLowerCase() + '.svg';
  5920. image.alt = '[{{type}} Annotation]';
  5921. image.dataset.l10nId = 'text_annotation_type';
  5922. image.dataset.l10nArgs = JSON.stringify({type: iconName});
  5923. var contentWrapper = document.createElement('div');
  5924. contentWrapper.className = 'annotTextContentWrapper';
  5925. contentWrapper.style.left = Math.floor(rect[2] - rect[0] + 5) + 'px';
  5926. contentWrapper.style.top = '-10px';
  5927. var content = document.createElement('div');
  5928. content.className = 'annotTextContent';
  5929. content.setAttribute('hidden', true);
  5930. var i, ii;
  5931. if (item.hasBgColor) {
  5932. var color = item.color;
  5933. // Enlighten the color (70%)
  5934. var BACKGROUND_ENLIGHT = 0.7;
  5935. var r = BACKGROUND_ENLIGHT * (1.0 - color[0]) + color[0];
  5936. var g = BACKGROUND_ENLIGHT * (1.0 - color[1]) + color[1];
  5937. var b = BACKGROUND_ENLIGHT * (1.0 - color[2]) + color[2];
  5938. content.style.backgroundColor = Util.makeCssRgb((r * 255) | 0,
  5939. (g * 255) | 0,
  5940. (b * 255) | 0);
  5941. }
  5942. var title = document.createElement('h1');
  5943. var text = document.createElement('p');
  5944. title.textContent = item.title;
  5945. if (!item.content && !item.title) {
  5946. content.setAttribute('hidden', true);
  5947. } else {
  5948. var e = document.createElement('span');
  5949. var lines = item.content.split(/(?:\r\n?|\n)/);
  5950. for (i = 0, ii = lines.length; i < ii; ++i) {
  5951. var line = lines[i];
  5952. e.appendChild(document.createTextNode(line));
  5953. if (i < (ii - 1)) {
  5954. e.appendChild(document.createElement('br'));
  5955. }
  5956. }
  5957. text.appendChild(e);
  5958. var pinned = false;
  5959. var showAnnotation = function showAnnotation(pin) {
  5960. if (pin) {
  5961. pinned = true;
  5962. }
  5963. if (content.hasAttribute('hidden')) {
  5964. container.style.zIndex += 1;
  5965. content.removeAttribute('hidden');
  5966. }
  5967. };
  5968. var hideAnnotation = function hideAnnotation(unpin) {
  5969. if (unpin) {
  5970. pinned = false;
  5971. }
  5972. if (!content.hasAttribute('hidden') && !pinned) {
  5973. container.style.zIndex -= 1;
  5974. content.setAttribute('hidden', true);
  5975. }
  5976. };
  5977. var toggleAnnotation = function toggleAnnotation() {
  5978. if (pinned) {
  5979. hideAnnotation(true);
  5980. } else {
  5981. showAnnotation(true);
  5982. }
  5983. };
  5984. image.addEventListener('click', function image_clickHandler() {
  5985. toggleAnnotation();
  5986. }, false);
  5987. image.addEventListener('mouseover', function image_mouseOverHandler() {
  5988. showAnnotation();
  5989. }, false);
  5990. image.addEventListener('mouseout', function image_mouseOutHandler() {
  5991. hideAnnotation();
  5992. }, false);
  5993. content.addEventListener('click', function content_clickHandler() {
  5994. hideAnnotation(true);
  5995. }, false);
  5996. }
  5997. content.appendChild(title);
  5998. content.appendChild(text);
  5999. contentWrapper.appendChild(content);
  6000. container.appendChild(image);
  6001. container.appendChild(contentWrapper);
  6002. return container;
  6003. }
  6004. function getHtmlElementForLinkAnnotation(item) {
  6005. var container = initContainer(item, true);
  6006. container.className = 'annotLink';
  6007. var link = document.createElement('a');
  6008. link.href = link.title = item.url || '';
  6009. if (item.url && PDFJS.openExternalLinksInNewWindow) {
  6010. link.target = '_blank';
  6011. }
  6012. container.appendChild(link);
  6013. return container;
  6014. }
  6015. function getHtmlElement(data, objs) {
  6016. switch (data.annotationType) {
  6017. case AnnotationType.WIDGET:
  6018. return getHtmlElementForTextWidgetAnnotation(data, objs);
  6019. case AnnotationType.TEXT:
  6020. return getHtmlElementForTextAnnotation(data);
  6021. case AnnotationType.LINK:
  6022. return getHtmlElementForLinkAnnotation(data);
  6023. default:
  6024. throw new Error('Unsupported annotationType: ' + data.annotationType);
  6025. }
  6026. }
  6027. return {
  6028. getHtmlElement: getHtmlElement
  6029. };
  6030. })();
  6031. PDFJS.AnnotationUtils = AnnotationUtils;
  6032. var SVG_DEFAULTS = {
  6033. fontStyle: 'normal',
  6034. fontWeight: 'normal',
  6035. fillColor: '#000000'
  6036. };
  6037. var convertImgDataToPng = (function convertImgDataToPngClosure() {
  6038. var PNG_HEADER =
  6039. new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
  6040. var CHUNK_WRAPPER_SIZE = 12;
  6041. var crcTable = new Int32Array(256);
  6042. for (var i = 0; i < 256; i++) {
  6043. var c = i;
  6044. for (var h = 0; h < 8; h++) {
  6045. if (c & 1) {
  6046. c = 0xedB88320 ^ ((c >> 1) & 0x7fffffff);
  6047. } else {
  6048. c = (c >> 1) & 0x7fffffff;
  6049. }
  6050. }
  6051. crcTable[i] = c;
  6052. }
  6053. function crc32(data, start, end) {
  6054. var crc = -1;
  6055. for (var i = start; i < end; i++) {
  6056. var a = (crc ^ data[i]) & 0xff;
  6057. var b = crcTable[a];
  6058. crc = (crc >>> 8) ^ b;
  6059. }
  6060. return crc ^ -1;
  6061. }
  6062. function writePngChunk(type, body, data, offset) {
  6063. var p = offset;
  6064. var len = body.length;
  6065. data[p] = len >> 24 & 0xff;
  6066. data[p + 1] = len >> 16 & 0xff;
  6067. data[p + 2] = len >> 8 & 0xff;
  6068. data[p + 3] = len & 0xff;
  6069. p += 4;
  6070. data[p] = type.charCodeAt(0) & 0xff;
  6071. data[p + 1] = type.charCodeAt(1) & 0xff;
  6072. data[p + 2] = type.charCodeAt(2) & 0xff;
  6073. data[p + 3] = type.charCodeAt(3) & 0xff;
  6074. p += 4;
  6075. data.set(body, p);
  6076. p += body.length;
  6077. var crc = crc32(data, offset + 4, p);
  6078. data[p] = crc >> 24 & 0xff;
  6079. data[p + 1] = crc >> 16 & 0xff;
  6080. data[p + 2] = crc >> 8 & 0xff;
  6081. data[p + 3] = crc & 0xff;
  6082. }
  6083. function adler32(data, start, end) {
  6084. var a = 1;
  6085. var b = 0;
  6086. for (var i = start; i < end; ++i) {
  6087. a = (a + (data[i] & 0xff)) % 65521;
  6088. b = (b + a) % 65521;
  6089. }
  6090. return (b << 16) | a;
  6091. }
  6092. function encode(imgData, kind) {
  6093. var width = imgData.width;
  6094. var height = imgData.height;
  6095. var bitDepth, colorType, lineSize;
  6096. var bytes = imgData.data;
  6097. switch (kind) {
  6098. case ImageKind.GRAYSCALE_1BPP:
  6099. colorType = 0;
  6100. bitDepth = 1;
  6101. lineSize = (width + 7) >> 3;
  6102. break;
  6103. case ImageKind.RGB_24BPP:
  6104. colorType = 2;
  6105. bitDepth = 8;
  6106. lineSize = width * 3;
  6107. break;
  6108. case ImageKind.RGBA_32BPP:
  6109. colorType = 6;
  6110. bitDepth = 8;
  6111. lineSize = width * 4;
  6112. break;
  6113. default:
  6114. throw new Error('invalid format');
  6115. }
  6116. // prefix every row with predictor 0
  6117. var literals = new Uint8Array((1 + lineSize) * height);
  6118. var offsetLiterals = 0, offsetBytes = 0;
  6119. var y, i;
  6120. for (y = 0; y < height; ++y) {
  6121. literals[offsetLiterals++] = 0; // no prediction
  6122. literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize),
  6123. offsetLiterals);
  6124. offsetBytes += lineSize;
  6125. offsetLiterals += lineSize;
  6126. }
  6127. if (kind === ImageKind.GRAYSCALE_1BPP) {
  6128. // inverting for B/W
  6129. offsetLiterals = 0;
  6130. for (y = 0; y < height; y++) {
  6131. offsetLiterals++; // skipping predictor
  6132. for (i = 0; i < lineSize; i++) {
  6133. literals[offsetLiterals++] ^= 0xFF;
  6134. }
  6135. }
  6136. }
  6137. var ihdr = new Uint8Array([
  6138. width >> 24 & 0xff,
  6139. width >> 16 & 0xff,
  6140. width >> 8 & 0xff,
  6141. width & 0xff,
  6142. height >> 24 & 0xff,
  6143. height >> 16 & 0xff,
  6144. height >> 8 & 0xff,
  6145. height & 0xff,
  6146. bitDepth, // bit depth
  6147. colorType, // color type
  6148. 0x00, // compression method
  6149. 0x00, // filter method
  6150. 0x00 // interlace method
  6151. ]);
  6152. var len = literals.length;
  6153. var maxBlockLength = 0xFFFF;
  6154. var deflateBlocks = Math.ceil(len / maxBlockLength);
  6155. var idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
  6156. var pi = 0;
  6157. idat[pi++] = 0x78; // compression method and flags
  6158. idat[pi++] = 0x9c; // flags
  6159. var pos = 0;
  6160. while (len > maxBlockLength) {
  6161. // writing non-final DEFLATE blocks type 0 and length of 65535
  6162. idat[pi++] = 0x00;
  6163. idat[pi++] = 0xff;
  6164. idat[pi++] = 0xff;
  6165. idat[pi++] = 0x00;
  6166. idat[pi++] = 0x00;
  6167. idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
  6168. pi += maxBlockLength;
  6169. pos += maxBlockLength;
  6170. len -= maxBlockLength;
  6171. }
  6172. // writing non-final DEFLATE blocks type 0
  6173. idat[pi++] = 0x01;
  6174. idat[pi++] = len & 0xff;
  6175. idat[pi++] = len >> 8 & 0xff;
  6176. idat[pi++] = (~len & 0xffff) & 0xff;
  6177. idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
  6178. idat.set(literals.subarray(pos), pi);
  6179. pi += literals.length - pos;
  6180. var adler = adler32(literals, 0, literals.length); // checksum
  6181. idat[pi++] = adler >> 24 & 0xff;
  6182. idat[pi++] = adler >> 16 & 0xff;
  6183. idat[pi++] = adler >> 8 & 0xff;
  6184. idat[pi++] = adler & 0xff;
  6185. // PNG will consists: header, IHDR+data, IDAT+data, and IEND.
  6186. var pngLength = PNG_HEADER.length + (CHUNK_WRAPPER_SIZE * 3) +
  6187. ihdr.length + idat.length;
  6188. var data = new Uint8Array(pngLength);
  6189. var offset = 0;
  6190. data.set(PNG_HEADER, offset);
  6191. offset += PNG_HEADER.length;
  6192. writePngChunk('IHDR', ihdr, data, offset);
  6193. offset += CHUNK_WRAPPER_SIZE + ihdr.length;
  6194. writePngChunk('IDATA', idat, data, offset);
  6195. offset += CHUNK_WRAPPER_SIZE + idat.length;
  6196. writePngChunk('IEND', new Uint8Array(0), data, offset);
  6197. return PDFJS.createObjectURL(data, 'image/png');
  6198. }
  6199. return function convertImgDataToPng(imgData) {
  6200. var kind = (imgData.kind === undefined ?
  6201. ImageKind.GRAYSCALE_1BPP : imgData.kind);
  6202. return encode(imgData, kind);
  6203. };
  6204. })();
  6205. var SVGExtraState = (function SVGExtraStateClosure() {
  6206. function SVGExtraState() {
  6207. this.fontSizeScale = 1;
  6208. this.fontWeight = SVG_DEFAULTS.fontWeight;
  6209. this.fontSize = 0;
  6210. this.textMatrix = IDENTITY_MATRIX;
  6211. this.fontMatrix = FONT_IDENTITY_MATRIX;
  6212. this.leading = 0;
  6213. // Current point (in user coordinates)
  6214. this.x = 0;
  6215. this.y = 0;
  6216. // Start of text line (in text coordinates)
  6217. this.lineX = 0;
  6218. this.lineY = 0;
  6219. // Character and word spacing
  6220. this.charSpacing = 0;
  6221. this.wordSpacing = 0;
  6222. this.textHScale = 1;
  6223. this.textRise = 0;
  6224. // Default foreground and background colors
  6225. this.fillColor = SVG_DEFAULTS.fillColor;
  6226. this.strokeColor = '#000000';
  6227. this.fillAlpha = 1;
  6228. this.strokeAlpha = 1;
  6229. this.lineWidth = 1;
  6230. this.lineJoin = '';
  6231. this.lineCap = '';
  6232. this.miterLimit = 0;
  6233. this.dashArray = [];
  6234. this.dashPhase = 0;
  6235. this.dependencies = [];
  6236. // Clipping
  6237. this.clipId = '';
  6238. this.pendingClip = false;
  6239. this.maskId = '';
  6240. }
  6241. SVGExtraState.prototype = {
  6242. clone: function SVGExtraState_clone() {
  6243. return Object.create(this);
  6244. },
  6245. setCurrentPoint: function SVGExtraState_setCurrentPoint(x, y) {
  6246. this.x = x;
  6247. this.y = y;
  6248. }
  6249. };
  6250. return SVGExtraState;
  6251. })();
  6252. var SVGGraphics = (function SVGGraphicsClosure() {
  6253. function createScratchSVG(width, height) {
  6254. var NS = 'http://www.w3.org/2000/svg';
  6255. var svg = document.createElementNS(NS, 'svg:svg');
  6256. svg.setAttributeNS(null, 'version', '1.1');
  6257. svg.setAttributeNS(null, 'width', width + 'px');
  6258. svg.setAttributeNS(null, 'height', height + 'px');
  6259. svg.setAttributeNS(null, 'viewBox', '0 0 ' + width + ' ' + height);
  6260. return svg;
  6261. }
  6262. function opListToTree(opList) {
  6263. var opTree = [];
  6264. var tmp = [];
  6265. var opListLen = opList.length;
  6266. for (var x = 0; x < opListLen; x++) {
  6267. if (opList[x].fn === 'save') {
  6268. opTree.push({'fnId': 92, 'fn': 'group', 'items': []});
  6269. tmp.push(opTree);
  6270. opTree = opTree[opTree.length - 1].items;
  6271. continue;
  6272. }
  6273. if(opList[x].fn === 'restore') {
  6274. opTree = tmp.pop();
  6275. } else {
  6276. opTree.push(opList[x]);
  6277. }
  6278. }
  6279. return opTree;
  6280. }
  6281. /**
  6282. * Formats float number.
  6283. * @param value {number} number to format.
  6284. * @returns {string}
  6285. */
  6286. function pf(value) {
  6287. if (value === (value | 0)) { // integer number
  6288. return value.toString();
  6289. }
  6290. var s = value.toFixed(10);
  6291. var i = s.length - 1;
  6292. if (s[i] !== '0') {
  6293. return s;
  6294. }
  6295. // removing trailing zeros
  6296. do {
  6297. i--;
  6298. } while (s[i] === '0');
  6299. return s.substr(0, s[i] === '.' ? i : i + 1);
  6300. }
  6301. /**
  6302. * Formats transform matrix. The standard rotation, scale and translate
  6303. * matrices are replaced by their shorter forms, and for identity matrix
  6304. * returns empty string to save the memory.
  6305. * @param m {Array} matrix to format.
  6306. * @returns {string}
  6307. */
  6308. function pm(m) {
  6309. if (m[4] === 0 && m[5] === 0) {
  6310. if (m[1] === 0 && m[2] === 0) {
  6311. if (m[0] === 1 && m[3] === 1) {
  6312. return '';
  6313. }
  6314. return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')';
  6315. }
  6316. if (m[0] === m[3] && m[1] === -m[2]) {
  6317. var a = Math.acos(m[0]) * 180 / Math.PI;
  6318. return 'rotate(' + pf(a) + ')';
  6319. }
  6320. } else {
  6321. if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
  6322. return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  6323. }
  6324. }
  6325. return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' +
  6326. pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  6327. }
  6328. function SVGGraphics(commonObjs, objs) {
  6329. this.current = new SVGExtraState();
  6330. this.transformMatrix = IDENTITY_MATRIX; // Graphics state matrix
  6331. this.transformStack = [];
  6332. this.extraStack = [];
  6333. this.commonObjs = commonObjs;
  6334. this.objs = objs;
  6335. this.pendingEOFill = false;
  6336. this.embedFonts = false;
  6337. this.embeddedFonts = {};
  6338. this.cssStyle = null;
  6339. }
  6340. var NS = 'http://www.w3.org/2000/svg';
  6341. var XML_NS = 'http://www.w3.org/XML/1998/namespace';
  6342. var XLINK_NS = 'http://www.w3.org/1999/xlink';
  6343. var LINE_CAP_STYLES = ['butt', 'round', 'square'];
  6344. var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
  6345. var clipCount = 0;
  6346. var maskCount = 0;
  6347. SVGGraphics.prototype = {
  6348. save: function SVGGraphics_save() {
  6349. this.transformStack.push(this.transformMatrix);
  6350. var old = this.current;
  6351. this.extraStack.push(old);
  6352. this.current = old.clone();
  6353. },
  6354. restore: function SVGGraphics_restore() {
  6355. this.transformMatrix = this.transformStack.pop();
  6356. this.current = this.extraStack.pop();
  6357. this.tgrp = document.createElementNS(NS, 'svg:g');
  6358. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  6359. this.pgrp.appendChild(this.tgrp);
  6360. },
  6361. group: function SVGGraphics_group(items) {
  6362. this.save();
  6363. this.executeOpTree(items);
  6364. this.restore();
  6365. },
  6366. loadDependencies: function SVGGraphics_loadDependencies(operatorList) {
  6367. var fnArray = operatorList.fnArray;
  6368. var fnArrayLen = fnArray.length;
  6369. var argsArray = operatorList.argsArray;
  6370. var self = this;
  6371. for (var i = 0; i < fnArrayLen; i++) {
  6372. if (OPS.dependency === fnArray[i]) {
  6373. var deps = argsArray[i];
  6374. for (var n = 0, nn = deps.length; n < nn; n++) {
  6375. var obj = deps[n];
  6376. var common = obj.substring(0, 2) === 'g_';
  6377. var promise;
  6378. if (common) {
  6379. promise = new Promise(function(resolve) {
  6380. self.commonObjs.get(obj, resolve);
  6381. });
  6382. } else {
  6383. promise = new Promise(function(resolve) {
  6384. self.objs.get(obj, resolve);
  6385. });
  6386. }
  6387. this.current.dependencies.push(promise);
  6388. }
  6389. }
  6390. }
  6391. return Promise.all(this.current.dependencies);
  6392. },
  6393. transform: function SVGGraphics_transform(a, b, c, d, e, f) {
  6394. var transformMatrix = [a, b, c, d, e, f];
  6395. this.transformMatrix = PDFJS.Util.transform(this.transformMatrix,
  6396. transformMatrix);
  6397. this.tgrp = document.createElementNS(NS, 'svg:g');
  6398. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  6399. },
  6400. getSVG: function SVGGraphics_getSVG(operatorList, viewport) {
  6401. this.svg = createScratchSVG(viewport.width, viewport.height);
  6402. this.viewport = viewport;
  6403. return this.loadDependencies(operatorList).then(function () {
  6404. this.transformMatrix = IDENTITY_MATRIX;
  6405. this.pgrp = document.createElementNS(NS, 'svg:g'); // Parent group
  6406. this.pgrp.setAttributeNS(null, 'transform', pm(viewport.transform));
  6407. this.tgrp = document.createElementNS(NS, 'svg:g'); // Transform group
  6408. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  6409. this.defs = document.createElementNS(NS, 'svg:defs');
  6410. this.pgrp.appendChild(this.defs);
  6411. this.pgrp.appendChild(this.tgrp);
  6412. this.svg.appendChild(this.pgrp);
  6413. var opTree = this.convertOpList(operatorList);
  6414. this.executeOpTree(opTree);
  6415. return this.svg;
  6416. }.bind(this));
  6417. },
  6418. convertOpList: function SVGGraphics_convertOpList(operatorList) {
  6419. var argsArray = operatorList.argsArray;
  6420. var fnArray = operatorList.fnArray;
  6421. var fnArrayLen = fnArray.length;
  6422. var REVOPS = [];
  6423. var opList = [];
  6424. for (var op in OPS) {
  6425. REVOPS[OPS[op]] = op;
  6426. }
  6427. for (var x = 0; x < fnArrayLen; x++) {
  6428. var fnId = fnArray[x];
  6429. opList.push({'fnId' : fnId, 'fn': REVOPS[fnId], 'args': argsArray[x]});
  6430. }
  6431. return opListToTree(opList);
  6432. },
  6433. executeOpTree: function SVGGraphics_executeOpTree(opTree) {
  6434. var opTreeLen = opTree.length;
  6435. for(var x = 0; x < opTreeLen; x++) {
  6436. var fn = opTree[x].fn;
  6437. var fnId = opTree[x].fnId;
  6438. var args = opTree[x].args;
  6439. switch (fnId | 0) {
  6440. case OPS.beginText:
  6441. this.beginText();
  6442. break;
  6443. case OPS.setLeading:
  6444. this.setLeading(args);
  6445. break;
  6446. case OPS.setLeadingMoveText:
  6447. this.setLeadingMoveText(args[0], args[1]);
  6448. break;
  6449. case OPS.setFont:
  6450. this.setFont(args);
  6451. break;
  6452. case OPS.showText:
  6453. this.showText(args[0]);
  6454. break;
  6455. case OPS.showSpacedText:
  6456. this.showText(args[0]);
  6457. break;
  6458. case OPS.endText:
  6459. this.endText();
  6460. break;
  6461. case OPS.moveText:
  6462. this.moveText(args[0], args[1]);
  6463. break;
  6464. case OPS.setCharSpacing:
  6465. this.setCharSpacing(args[0]);
  6466. break;
  6467. case OPS.setWordSpacing:
  6468. this.setWordSpacing(args[0]);
  6469. break;
  6470. case OPS.setHScale:
  6471. this.setHScale(args[0]);
  6472. break;
  6473. case OPS.setTextMatrix:
  6474. this.setTextMatrix(args[0], args[1], args[2],
  6475. args[3], args[4], args[5]);
  6476. break;
  6477. case OPS.setLineWidth:
  6478. this.setLineWidth(args[0]);
  6479. break;
  6480. case OPS.setLineJoin:
  6481. this.setLineJoin(args[0]);
  6482. break;
  6483. case OPS.setLineCap:
  6484. this.setLineCap(args[0]);
  6485. break;
  6486. case OPS.setMiterLimit:
  6487. this.setMiterLimit(args[0]);
  6488. break;
  6489. case OPS.setFillRGBColor:
  6490. this.setFillRGBColor(args[0], args[1], args[2]);
  6491. break;
  6492. case OPS.setStrokeRGBColor:
  6493. this.setStrokeRGBColor(args[0], args[1], args[2]);
  6494. break;
  6495. case OPS.setDash:
  6496. this.setDash(args[0], args[1]);
  6497. break;
  6498. case OPS.setGState:
  6499. this.setGState(args[0]);
  6500. break;
  6501. case OPS.fill:
  6502. this.fill();
  6503. break;
  6504. case OPS.eoFill:
  6505. this.eoFill();
  6506. break;
  6507. case OPS.stroke:
  6508. this.stroke();
  6509. break;
  6510. case OPS.fillStroke:
  6511. this.fillStroke();
  6512. break;
  6513. case OPS.eoFillStroke:
  6514. this.eoFillStroke();
  6515. break;
  6516. case OPS.clip:
  6517. this.clip('nonzero');
  6518. break;
  6519. case OPS.eoClip:
  6520. this.clip('evenodd');
  6521. break;
  6522. case OPS.paintSolidColorImageMask:
  6523. this.paintSolidColorImageMask();
  6524. break;
  6525. case OPS.paintJpegXObject:
  6526. this.paintJpegXObject(args[0], args[1], args[2]);
  6527. break;
  6528. case OPS.paintImageXObject:
  6529. this.paintImageXObject(args[0]);
  6530. break;
  6531. case OPS.paintInlineImageXObject:
  6532. this.paintInlineImageXObject(args[0]);
  6533. break;
  6534. case OPS.paintImageMaskXObject:
  6535. this.paintImageMaskXObject(args[0]);
  6536. break;
  6537. case OPS.paintFormXObjectBegin:
  6538. this.paintFormXObjectBegin(args[0], args[1]);
  6539. break;
  6540. case OPS.paintFormXObjectEnd:
  6541. this.paintFormXObjectEnd();
  6542. break;
  6543. case OPS.closePath:
  6544. this.closePath();
  6545. break;
  6546. case OPS.closeStroke:
  6547. this.closeStroke();
  6548. break;
  6549. case OPS.closeFillStroke:
  6550. this.closeFillStroke();
  6551. break;
  6552. case OPS.nextLine:
  6553. this.nextLine();
  6554. break;
  6555. case OPS.transform:
  6556. this.transform(args[0], args[1], args[2], args[3],
  6557. args[4], args[5]);
  6558. break;
  6559. case OPS.constructPath:
  6560. this.constructPath(args[0], args[1]);
  6561. break;
  6562. case OPS.endPath:
  6563. this.endPath();
  6564. break;
  6565. case 92:
  6566. this.group(opTree[x].items);
  6567. break;
  6568. default:
  6569. warn('Unimplemented method '+ fn);
  6570. break;
  6571. }
  6572. }
  6573. },
  6574. setWordSpacing: function SVGGraphics_setWordSpacing(wordSpacing) {
  6575. this.current.wordSpacing = wordSpacing;
  6576. },
  6577. setCharSpacing: function SVGGraphics_setCharSpacing(charSpacing) {
  6578. this.current.charSpacing = charSpacing;
  6579. },
  6580. nextLine: function SVGGraphics_nextLine() {
  6581. this.moveText(0, this.current.leading);
  6582. },
  6583. setTextMatrix: function SVGGraphics_setTextMatrix(a, b, c, d, e, f) {
  6584. var current = this.current;
  6585. this.current.textMatrix = this.current.lineMatrix = [a, b, c, d, e, f];
  6586. this.current.x = this.current.lineX = 0;
  6587. this.current.y = this.current.lineY = 0;
  6588. current.xcoords = [];
  6589. current.tspan = document.createElementNS(NS, 'svg:tspan');
  6590. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  6591. current.tspan.setAttributeNS(null, 'font-size',
  6592. pf(current.fontSize) + 'px');
  6593. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  6594. current.txtElement = document.createElementNS(NS, 'svg:text');
  6595. current.txtElement.appendChild(current.tspan);
  6596. },
  6597. beginText: function SVGGraphics_beginText() {
  6598. this.current.x = this.current.lineX = 0;
  6599. this.current.y = this.current.lineY = 0;
  6600. this.current.textMatrix = IDENTITY_MATRIX;
  6601. this.current.lineMatrix = IDENTITY_MATRIX;
  6602. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  6603. this.current.txtElement = document.createElementNS(NS, 'svg:text');
  6604. this.current.txtgrp = document.createElementNS(NS, 'svg:g');
  6605. this.current.xcoords = [];
  6606. },
  6607. moveText: function SVGGraphics_moveText(x, y) {
  6608. var current = this.current;
  6609. this.current.x = this.current.lineX += x;
  6610. this.current.y = this.current.lineY += y;
  6611. current.xcoords = [];
  6612. current.tspan = document.createElementNS(NS, 'svg:tspan');
  6613. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  6614. current.tspan.setAttributeNS(null, 'font-size',
  6615. pf(current.fontSize) + 'px');
  6616. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  6617. },
  6618. showText: function SVGGraphics_showText(glyphs) {
  6619. var current = this.current;
  6620. var font = current.font;
  6621. var fontSize = current.fontSize;
  6622. if (fontSize === 0) {
  6623. return;
  6624. }
  6625. var charSpacing = current.charSpacing;
  6626. var wordSpacing = current.wordSpacing;
  6627. var fontDirection = current.fontDirection;
  6628. var textHScale = current.textHScale * fontDirection;
  6629. var glyphsLength = glyphs.length;
  6630. var vertical = font.vertical;
  6631. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  6632. var x = 0, i;
  6633. for (i = 0; i < glyphsLength; ++i) {
  6634. var glyph = glyphs[i];
  6635. if (glyph === null) {
  6636. // word break
  6637. x += fontDirection * wordSpacing;
  6638. continue;
  6639. } else if (isNum(glyph)) {
  6640. x += -glyph * fontSize * 0.001;
  6641. continue;
  6642. }
  6643. current.xcoords.push(current.x + x * textHScale);
  6644. var width = glyph.width;
  6645. var character = glyph.fontChar;
  6646. var charWidth = width * widthAdvanceScale + charSpacing * fontDirection;
  6647. x += charWidth;
  6648. current.tspan.textContent += character;
  6649. }
  6650. if (vertical) {
  6651. current.y -= x * textHScale;
  6652. } else {
  6653. current.x += x * textHScale;
  6654. }
  6655. current.tspan.setAttributeNS(null, 'x',
  6656. current.xcoords.map(pf).join(' '));
  6657. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  6658. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  6659. current.tspan.setAttributeNS(null, 'font-size',
  6660. pf(current.fontSize) + 'px');
  6661. if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
  6662. current.tspan.setAttributeNS(null, 'font-style', current.fontStyle);
  6663. }
  6664. if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
  6665. current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight);
  6666. }
  6667. if (current.fillColor !== SVG_DEFAULTS.fillColor) {
  6668. current.tspan.setAttributeNS(null, 'fill', current.fillColor);
  6669. }
  6670. current.txtElement.setAttributeNS(null, 'transform',
  6671. pm(current.textMatrix) +
  6672. ' scale(1, -1)' );
  6673. current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve');
  6674. current.txtElement.appendChild(current.tspan);
  6675. current.txtgrp.appendChild(current.txtElement);
  6676. this.tgrp.appendChild(current.txtElement);
  6677. },
  6678. setLeadingMoveText: function SVGGraphics_setLeadingMoveText(x, y) {
  6679. this.setLeading(-y);
  6680. this.moveText(x, y);
  6681. },
  6682. addFontStyle: function SVGGraphics_addFontStyle(fontObj) {
  6683. if (!this.cssStyle) {
  6684. this.cssStyle = document.createElementNS(NS, 'svg:style');
  6685. this.cssStyle.setAttributeNS(null, 'type', 'text/css');
  6686. this.defs.appendChild(this.cssStyle);
  6687. }
  6688. var url = PDFJS.createObjectURL(fontObj.data, fontObj.mimetype);
  6689. this.cssStyle.textContent +=
  6690. '@font-face { font-family: "' + fontObj.loadedName + '";' +
  6691. ' src: url(' + url + '); }\n';
  6692. },
  6693. setFont: function SVGGraphics_setFont(details) {
  6694. var current = this.current;
  6695. var fontObj = this.commonObjs.get(details[0]);
  6696. var size = details[1];
  6697. this.current.font = fontObj;
  6698. if (this.embedFonts && fontObj.data &&
  6699. !this.embeddedFonts[fontObj.loadedName]) {
  6700. this.addFontStyle(fontObj);
  6701. this.embeddedFonts[fontObj.loadedName] = fontObj;
  6702. }
  6703. current.fontMatrix = (fontObj.fontMatrix ?
  6704. fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
  6705. var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') :
  6706. (fontObj.bold ? 'bold' : 'normal');
  6707. var italic = fontObj.italic ? 'italic' : 'normal';
  6708. if (size < 0) {
  6709. size = -size;
  6710. current.fontDirection = -1;
  6711. } else {
  6712. current.fontDirection = 1;
  6713. }
  6714. current.fontSize = size;
  6715. current.fontFamily = fontObj.loadedName;
  6716. current.fontWeight = bold;
  6717. current.fontStyle = italic;
  6718. current.tspan = document.createElementNS(NS, 'svg:tspan');
  6719. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  6720. current.xcoords = [];
  6721. },
  6722. endText: function SVGGraphics_endText() {
  6723. if (this.current.pendingClip) {
  6724. this.cgrp.appendChild(this.tgrp);
  6725. this.pgrp.appendChild(this.cgrp);
  6726. } else {
  6727. this.pgrp.appendChild(this.tgrp);
  6728. }
  6729. this.tgrp = document.createElementNS(NS, 'svg:g');
  6730. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  6731. },
  6732. // Path properties
  6733. setLineWidth: function SVGGraphics_setLineWidth(width) {
  6734. this.current.lineWidth = width;
  6735. },
  6736. setLineCap: function SVGGraphics_setLineCap(style) {
  6737. this.current.lineCap = LINE_CAP_STYLES[style];
  6738. },
  6739. setLineJoin: function SVGGraphics_setLineJoin(style) {
  6740. this.current.lineJoin = LINE_JOIN_STYLES[style];
  6741. },
  6742. setMiterLimit: function SVGGraphics_setMiterLimit(limit) {
  6743. this.current.miterLimit = limit;
  6744. },
  6745. setStrokeRGBColor: function SVGGraphics_setStrokeRGBColor(r, g, b) {
  6746. var color = Util.makeCssRgb(r, g, b);
  6747. this.current.strokeColor = color;
  6748. },
  6749. setFillRGBColor: function SVGGraphics_setFillRGBColor(r, g, b) {
  6750. var color = Util.makeCssRgb(r, g, b);
  6751. this.current.fillColor = color;
  6752. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  6753. this.current.xcoords = [];
  6754. },
  6755. setDash: function SVGGraphics_setDash(dashArray, dashPhase) {
  6756. this.current.dashArray = dashArray;
  6757. this.current.dashPhase = dashPhase;
  6758. },
  6759. constructPath: function SVGGraphics_constructPath(ops, args) {
  6760. var current = this.current;
  6761. var x = current.x, y = current.y;
  6762. current.path = document.createElementNS(NS, 'svg:path');
  6763. var d = [];
  6764. var opLength = ops.length;
  6765. for (var i = 0, j = 0; i < opLength; i++) {
  6766. switch (ops[i] | 0) {
  6767. case OPS.rectangle:
  6768. x = args[j++];
  6769. y = args[j++];
  6770. var width = args[j++];
  6771. var height = args[j++];
  6772. var xw = x + width;
  6773. var yh = y + height;
  6774. d.push('M', pf(x), pf(y), 'L', pf(xw) , pf(y), 'L', pf(xw), pf(yh),
  6775. 'L', pf(x), pf(yh), 'Z');
  6776. break;
  6777. case OPS.moveTo:
  6778. x = args[j++];
  6779. y = args[j++];
  6780. d.push('M', pf(x), pf(y));
  6781. break;
  6782. case OPS.lineTo:
  6783. x = args[j++];
  6784. y = args[j++];
  6785. d.push('L', pf(x) , pf(y));
  6786. break;
  6787. case OPS.curveTo:
  6788. x = args[j + 4];
  6789. y = args[j + 5];
  6790. d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]),
  6791. pf(args[j + 3]), pf(x), pf(y));
  6792. j += 6;
  6793. break;
  6794. case OPS.curveTo2:
  6795. x = args[j + 2];
  6796. y = args[j + 3];
  6797. d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]),
  6798. pf(args[j + 2]), pf(args[j + 3]));
  6799. j += 4;
  6800. break;
  6801. case OPS.curveTo3:
  6802. x = args[j + 2];
  6803. y = args[j + 3];
  6804. d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y),
  6805. pf(x), pf(y));
  6806. j += 4;
  6807. break;
  6808. case OPS.closePath:
  6809. d.push('Z');
  6810. break;
  6811. }
  6812. }
  6813. current.path.setAttributeNS(null, 'd', d.join(' '));
  6814. current.path.setAttributeNS(null, 'stroke-miterlimit',
  6815. pf(current.miterLimit));
  6816. current.path.setAttributeNS(null, 'stroke-linecap', current.lineCap);
  6817. current.path.setAttributeNS(null, 'stroke-linejoin', current.lineJoin);
  6818. current.path.setAttributeNS(null, 'stroke-width',
  6819. pf(current.lineWidth) + 'px');
  6820. current.path.setAttributeNS(null, 'stroke-dasharray',
  6821. current.dashArray.map(pf).join(' '));
  6822. current.path.setAttributeNS(null, 'stroke-dashoffset',
  6823. pf(current.dashPhase) + 'px');
  6824. current.path.setAttributeNS(null, 'fill', 'none');
  6825. this.tgrp.appendChild(current.path);
  6826. if (current.pendingClip) {
  6827. this.cgrp.appendChild(this.tgrp);
  6828. this.pgrp.appendChild(this.cgrp);
  6829. } else {
  6830. this.pgrp.appendChild(this.tgrp);
  6831. }
  6832. // Saving a reference in current.element so that it can be addressed
  6833. // in 'fill' and 'stroke'
  6834. current.element = current.path;
  6835. current.setCurrentPoint(x, y);
  6836. },
  6837. endPath: function SVGGraphics_endPath() {
  6838. var current = this.current;
  6839. if (current.pendingClip) {
  6840. this.cgrp.appendChild(this.tgrp);
  6841. this.pgrp.appendChild(this.cgrp);
  6842. } else {
  6843. this.pgrp.appendChild(this.tgrp);
  6844. }
  6845. this.tgrp = document.createElementNS(NS, 'svg:g');
  6846. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  6847. },
  6848. clip: function SVGGraphics_clip(type) {
  6849. var current = this.current;
  6850. // Add current path to clipping path
  6851. current.clipId = 'clippath' + clipCount;
  6852. clipCount++;
  6853. this.clippath = document.createElementNS(NS, 'svg:clipPath');
  6854. this.clippath.setAttributeNS(null, 'id', current.clipId);
  6855. var clipElement = current.element.cloneNode();
  6856. if (type === 'evenodd') {
  6857. clipElement.setAttributeNS(null, 'clip-rule', 'evenodd');
  6858. } else {
  6859. clipElement.setAttributeNS(null, 'clip-rule', 'nonzero');
  6860. }
  6861. this.clippath.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  6862. this.clippath.appendChild(clipElement);
  6863. this.defs.appendChild(this.clippath);
  6864. // Create a new group with that attribute
  6865. current.pendingClip = true;
  6866. this.cgrp = document.createElementNS(NS, 'svg:g');
  6867. this.cgrp.setAttributeNS(null, 'clip-path',
  6868. 'url(#' + current.clipId + ')');
  6869. this.pgrp.appendChild(this.cgrp);
  6870. },
  6871. closePath: function SVGGraphics_closePath() {
  6872. var current = this.current;
  6873. var d = current.path.getAttributeNS(null, 'd');
  6874. d += 'Z';
  6875. current.path.setAttributeNS(null, 'd', d);
  6876. },
  6877. setLeading: function SVGGraphics_setLeading(leading) {
  6878. this.current.leading = -leading;
  6879. },
  6880. setTextRise: function SVGGraphics_setTextRise(textRise) {
  6881. this.current.textRise = textRise;
  6882. },
  6883. setHScale: function SVGGraphics_setHScale(scale) {
  6884. this.current.textHScale = scale / 100;
  6885. },
  6886. setGState: function SVGGraphics_setGState(states) {
  6887. for (var i = 0, ii = states.length; i < ii; i++) {
  6888. var state = states[i];
  6889. var key = state[0];
  6890. var value = state[1];
  6891. switch (key) {
  6892. case 'LW':
  6893. this.setLineWidth(value);
  6894. break;
  6895. case 'LC':
  6896. this.setLineCap(value);
  6897. break;
  6898. case 'LJ':
  6899. this.setLineJoin(value);
  6900. break;
  6901. case 'ML':
  6902. this.setMiterLimit(value);
  6903. break;
  6904. case 'D':
  6905. this.setDash(value[0], value[1]);
  6906. break;
  6907. case 'RI':
  6908. break;
  6909. case 'FL':
  6910. break;
  6911. case 'Font':
  6912. this.setFont(value);
  6913. break;
  6914. case 'CA':
  6915. break;
  6916. case 'ca':
  6917. break;
  6918. case 'BM':
  6919. break;
  6920. case 'SMask':
  6921. break;
  6922. }
  6923. }
  6924. },
  6925. fill: function SVGGraphics_fill() {
  6926. var current = this.current;
  6927. current.element.setAttributeNS(null, 'fill', current.fillColor);
  6928. },
  6929. stroke: function SVGGraphics_stroke() {
  6930. var current = this.current;
  6931. current.element.setAttributeNS(null, 'stroke', current.strokeColor);
  6932. current.element.setAttributeNS(null, 'fill', 'none');
  6933. },
  6934. eoFill: function SVGGraphics_eoFill() {
  6935. var current = this.current;
  6936. current.element.setAttributeNS(null, 'fill', current.fillColor);
  6937. current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  6938. },
  6939. fillStroke: function SVGGraphics_fillStroke() {
  6940. // Order is important since stroke wants fill to be none.
  6941. // First stroke, then if fill needed, it will be overwritten.
  6942. this.stroke();
  6943. this.fill();
  6944. },
  6945. eoFillStroke: function SVGGraphics_eoFillStroke() {
  6946. this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  6947. this.fillStroke();
  6948. },
  6949. closeStroke: function SVGGraphics_closeStroke() {
  6950. this.closePath();
  6951. this.stroke();
  6952. },
  6953. closeFillStroke: function SVGGraphics_closeFillStroke() {
  6954. this.closePath();
  6955. this.fillStroke();
  6956. },
  6957. paintSolidColorImageMask:
  6958. function SVGGraphics_paintSolidColorImageMask() {
  6959. var current = this.current;
  6960. var rect = document.createElementNS(NS, 'svg:rect');
  6961. rect.setAttributeNS(null, 'x', '0');
  6962. rect.setAttributeNS(null, 'y', '0');
  6963. rect.setAttributeNS(null, 'width', '1px');
  6964. rect.setAttributeNS(null, 'height', '1px');
  6965. rect.setAttributeNS(null, 'fill', current.fillColor);
  6966. this.tgrp.appendChild(rect);
  6967. },
  6968. paintJpegXObject: function SVGGraphics_paintJpegXObject(objId, w, h) {
  6969. var current = this.current;
  6970. var imgObj = this.objs.get(objId);
  6971. var imgEl = document.createElementNS(NS, 'svg:image');
  6972. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src);
  6973. imgEl.setAttributeNS(null, 'width', imgObj.width + 'px');
  6974. imgEl.setAttributeNS(null, 'height', imgObj.height + 'px');
  6975. imgEl.setAttributeNS(null, 'x', '0');
  6976. imgEl.setAttributeNS(null, 'y', pf(-h));
  6977. imgEl.setAttributeNS(null, 'transform',
  6978. 'scale(' + pf(1 / w) + ' ' + pf(-1 / h) + ')');
  6979. this.tgrp.appendChild(imgEl);
  6980. if (current.pendingClip) {
  6981. this.cgrp.appendChild(this.tgrp);
  6982. this.pgrp.appendChild(this.cgrp);
  6983. } else {
  6984. this.pgrp.appendChild(this.tgrp);
  6985. }
  6986. },
  6987. paintImageXObject: function SVGGraphics_paintImageXObject(objId) {
  6988. var imgData = this.objs.get(objId);
  6989. if (!imgData) {
  6990. warn('Dependent image isn\'t ready yet');
  6991. return;
  6992. }
  6993. this.paintInlineImageXObject(imgData);
  6994. },
  6995. paintInlineImageXObject:
  6996. function SVGGraphics_paintInlineImageXObject(imgData, mask) {
  6997. var current = this.current;
  6998. var width = imgData.width;
  6999. var height = imgData.height;
  7000. var imgSrc = convertImgDataToPng(imgData);
  7001. var cliprect = document.createElementNS(NS, 'svg:rect');
  7002. cliprect.setAttributeNS(null, 'x', '0');
  7003. cliprect.setAttributeNS(null, 'y', '0');
  7004. cliprect.setAttributeNS(null, 'width', pf(width));
  7005. cliprect.setAttributeNS(null, 'height', pf(height));
  7006. current.element = cliprect;
  7007. this.clip('nonzero');
  7008. var imgEl = document.createElementNS(NS, 'svg:image');
  7009. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc);
  7010. imgEl.setAttributeNS(null, 'x', '0');
  7011. imgEl.setAttributeNS(null, 'y', pf(-height));
  7012. imgEl.setAttributeNS(null, 'width', pf(width) + 'px');
  7013. imgEl.setAttributeNS(null, 'height', pf(height) + 'px');
  7014. imgEl.setAttributeNS(null, 'transform',
  7015. 'scale(' + pf(1 / width) + ' ' +
  7016. pf(-1 / height) + ')');
  7017. if (mask) {
  7018. mask.appendChild(imgEl);
  7019. } else {
  7020. this.tgrp.appendChild(imgEl);
  7021. }
  7022. if (current.pendingClip) {
  7023. this.cgrp.appendChild(this.tgrp);
  7024. this.pgrp.appendChild(this.cgrp);
  7025. } else {
  7026. this.pgrp.appendChild(this.tgrp);
  7027. }
  7028. },
  7029. paintImageMaskXObject:
  7030. function SVGGraphics_paintImageMaskXObject(imgData) {
  7031. var current = this.current;
  7032. var width = imgData.width;
  7033. var height = imgData.height;
  7034. var fillColor = current.fillColor;
  7035. current.maskId = 'mask' + maskCount++;
  7036. var mask = document.createElementNS(NS, 'svg:mask');
  7037. mask.setAttributeNS(null, 'id', current.maskId);
  7038. var rect = document.createElementNS(NS, 'svg:rect');
  7039. rect.setAttributeNS(null, 'x', '0');
  7040. rect.setAttributeNS(null, 'y', '0');
  7041. rect.setAttributeNS(null, 'width', pf(width));
  7042. rect.setAttributeNS(null, 'height', pf(height));
  7043. rect.setAttributeNS(null, 'fill', fillColor);
  7044. rect.setAttributeNS(null, 'mask', 'url(#' + current.maskId +')');
  7045. this.defs.appendChild(mask);
  7046. this.tgrp.appendChild(rect);
  7047. this.paintInlineImageXObject(imgData, mask);
  7048. },
  7049. paintFormXObjectBegin:
  7050. function SVGGraphics_paintFormXObjectBegin(matrix, bbox) {
  7051. this.save();
  7052. if (isArray(matrix) && matrix.length === 6) {
  7053. this.transform(matrix[0], matrix[1], matrix[2],
  7054. matrix[3], matrix[4], matrix[5]);
  7055. }
  7056. if (isArray(bbox) && bbox.length === 4) {
  7057. var width = bbox[2] - bbox[0];
  7058. var height = bbox[3] - bbox[1];
  7059. var cliprect = document.createElementNS(NS, 'svg:rect');
  7060. cliprect.setAttributeNS(null, 'x', bbox[0]);
  7061. cliprect.setAttributeNS(null, 'y', bbox[1]);
  7062. cliprect.setAttributeNS(null, 'width', pf(width));
  7063. cliprect.setAttributeNS(null, 'height', pf(height));
  7064. this.current.element = cliprect;
  7065. this.clip('nonzero');
  7066. this.endPath();
  7067. }
  7068. },
  7069. paintFormXObjectEnd:
  7070. function SVGGraphics_paintFormXObjectEnd() {
  7071. this.restore();
  7072. }
  7073. };
  7074. return SVGGraphics;
  7075. })();
  7076. PDFJS.SVGGraphics = SVGGraphics;
  7077. var NetworkManager = (function NetworkManagerClosure() {
  7078. var OK_RESPONSE = 200;
  7079. var PARTIAL_CONTENT_RESPONSE = 206;
  7080. function NetworkManager(url, args) {
  7081. this.url = url;
  7082. args = args || {};
  7083. this.isHttp = /^https?:/i.test(url);
  7084. this.httpHeaders = (this.isHttp && args.httpHeaders) || {};
  7085. this.withCredentials = args.withCredentials || false;
  7086. this.getXhr = args.getXhr ||
  7087. function NetworkManager_getXhr() {
  7088. return new XMLHttpRequest();
  7089. };
  7090. this.currXhrId = 0;
  7091. this.pendingRequests = {};
  7092. this.loadedRequests = {};
  7093. }
  7094. function getArrayBuffer(xhr) {
  7095. var data = xhr.response;
  7096. if (typeof data !== 'string') {
  7097. return data;
  7098. }
  7099. var length = data.length;
  7100. var array = new Uint8Array(length);
  7101. for (var i = 0; i < length; i++) {
  7102. array[i] = data.charCodeAt(i) & 0xFF;
  7103. }
  7104. return array.buffer;
  7105. }
  7106. NetworkManager.prototype = {
  7107. requestRange: function NetworkManager_requestRange(begin, end, listeners) {
  7108. var args = {
  7109. begin: begin,
  7110. end: end
  7111. };
  7112. for (var prop in listeners) {
  7113. args[prop] = listeners[prop];
  7114. }
  7115. return this.request(args);
  7116. },
  7117. requestFull: function NetworkManager_requestFull(listeners) {
  7118. return this.request(listeners);
  7119. },
  7120. request: function NetworkManager_request(args) {
  7121. var xhr = this.getXhr();
  7122. var xhrId = this.currXhrId++;
  7123. var pendingRequest = this.pendingRequests[xhrId] = {
  7124. xhr: xhr
  7125. };
  7126. xhr.open('GET', this.url);
  7127. xhr.withCredentials = this.withCredentials;
  7128. for (var property in this.httpHeaders) {
  7129. var value = this.httpHeaders[property];
  7130. if (typeof value === 'undefined') {
  7131. continue;
  7132. }
  7133. xhr.setRequestHeader(property, value);
  7134. }
  7135. if (this.isHttp && 'begin' in args && 'end' in args) {
  7136. var rangeStr = args.begin + '-' + (args.end - 1);
  7137. xhr.setRequestHeader('Range', 'bytes=' + rangeStr);
  7138. pendingRequest.expectedStatus = 206;
  7139. } else {
  7140. pendingRequest.expectedStatus = 200;
  7141. }
  7142. if (args.onProgressiveData) {
  7143. // Some legacy browsers might throw an exception.
  7144. try {
  7145. xhr.responseType = 'moz-chunked-arraybuffer';
  7146. } catch(e) {}
  7147. if (xhr.responseType === 'moz-chunked-arraybuffer') {
  7148. pendingRequest.onProgressiveData = args.onProgressiveData;
  7149. pendingRequest.mozChunked = true;
  7150. } else {
  7151. xhr.responseType = 'arraybuffer';
  7152. }
  7153. } else {
  7154. xhr.responseType = 'arraybuffer';
  7155. }
  7156. if (args.onError) {
  7157. xhr.onerror = function(evt) {
  7158. args.onError(xhr.status);
  7159. };
  7160. }
  7161. xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);
  7162. xhr.onprogress = this.onProgress.bind(this, xhrId);
  7163. pendingRequest.onHeadersReceived = args.onHeadersReceived;
  7164. pendingRequest.onDone = args.onDone;
  7165. pendingRequest.onError = args.onError;
  7166. pendingRequest.onProgress = args.onProgress;
  7167. xhr.send(null);
  7168. return xhrId;
  7169. },
  7170. onProgress: function NetworkManager_onProgress(xhrId, evt) {
  7171. var pendingRequest = this.pendingRequests[xhrId];
  7172. if (!pendingRequest) {
  7173. // Maybe abortRequest was called...
  7174. return;
  7175. }
  7176. if (pendingRequest.mozChunked) {
  7177. var chunk = getArrayBuffer(pendingRequest.xhr);
  7178. pendingRequest.onProgressiveData(chunk);
  7179. }
  7180. var onProgress = pendingRequest.onProgress;
  7181. if (onProgress) {
  7182. onProgress(evt);
  7183. }
  7184. },
  7185. onStateChange: function NetworkManager_onStateChange(xhrId, evt) {
  7186. var pendingRequest = this.pendingRequests[xhrId];
  7187. if (!pendingRequest) {
  7188. // Maybe abortRequest was called...
  7189. return;
  7190. }
  7191. var xhr = pendingRequest.xhr;
  7192. if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {
  7193. pendingRequest.onHeadersReceived();
  7194. delete pendingRequest.onHeadersReceived;
  7195. }
  7196. if (xhr.readyState !== 4) {
  7197. return;
  7198. }
  7199. if (!(xhrId in this.pendingRequests)) {
  7200. // The XHR request might have been aborted in onHeadersReceived()
  7201. // callback, in which case we should abort request
  7202. return;
  7203. }
  7204. delete this.pendingRequests[xhrId];
  7205. // success status == 0 can be on ftp, file and other protocols
  7206. if (xhr.status === 0 && this.isHttp) {
  7207. if (pendingRequest.onError) {
  7208. pendingRequest.onError(xhr.status);
  7209. }
  7210. return;
  7211. }
  7212. var xhrStatus = xhr.status || OK_RESPONSE;
  7213. // From http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35.2:
  7214. // "A server MAY ignore the Range header". This means it's possible to
  7215. // get a 200 rather than a 206 response from a range request.
  7216. var ok_response_on_range_request =
  7217. xhrStatus === OK_RESPONSE &&
  7218. pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;
  7219. if (!ok_response_on_range_request &&
  7220. xhrStatus !== pendingRequest.expectedStatus) {
  7221. if (pendingRequest.onError) {
  7222. pendingRequest.onError(xhr.status);
  7223. }
  7224. return;
  7225. }
  7226. this.loadedRequests[xhrId] = true;
  7227. var chunk = getArrayBuffer(xhr);
  7228. if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {
  7229. var rangeHeader = xhr.getResponseHeader('Content-Range');
  7230. var matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);
  7231. var begin = parseInt(matches[1], 10);
  7232. pendingRequest.onDone({
  7233. begin: begin,
  7234. chunk: chunk
  7235. });
  7236. } else if (pendingRequest.onProgressiveData) {
  7237. pendingRequest.onDone(null);
  7238. } else {
  7239. pendingRequest.onDone({
  7240. begin: 0,
  7241. chunk: chunk
  7242. });
  7243. }
  7244. },
  7245. hasPendingRequests: function NetworkManager_hasPendingRequests() {
  7246. for (var xhrId in this.pendingRequests) {
  7247. return true;
  7248. }
  7249. return false;
  7250. },
  7251. getRequestXhr: function NetworkManager_getXhr(xhrId) {
  7252. return this.pendingRequests[xhrId].xhr;
  7253. },
  7254. isStreamingRequest: function NetworkManager_isStreamingRequest(xhrId) {
  7255. return !!(this.pendingRequests[xhrId].onProgressiveData);
  7256. },
  7257. isPendingRequest: function NetworkManager_isPendingRequest(xhrId) {
  7258. return xhrId in this.pendingRequests;
  7259. },
  7260. isLoadedRequest: function NetworkManager_isLoadedRequest(xhrId) {
  7261. return xhrId in this.loadedRequests;
  7262. },
  7263. abortAllRequests: function NetworkManager_abortAllRequests() {
  7264. for (var xhrId in this.pendingRequests) {
  7265. this.abortRequest(xhrId | 0);
  7266. }
  7267. },
  7268. abortRequest: function NetworkManager_abortRequest(xhrId) {
  7269. var xhr = this.pendingRequests[xhrId].xhr;
  7270. delete this.pendingRequests[xhrId];
  7271. xhr.abort();
  7272. }
  7273. };
  7274. return NetworkManager;
  7275. })();
  7276. var ChunkedStream = (function ChunkedStreamClosure() {
  7277. function ChunkedStream(length, chunkSize, manager) {
  7278. this.bytes = new Uint8Array(length);
  7279. this.start = 0;
  7280. this.pos = 0;
  7281. this.end = length;
  7282. this.chunkSize = chunkSize;
  7283. this.loadedChunks = [];
  7284. this.numChunksLoaded = 0;
  7285. this.numChunks = Math.ceil(length / chunkSize);
  7286. this.manager = manager;
  7287. this.progressiveDataLength = 0;
  7288. this.lastSuccessfulEnsureByteChunk = -1; // a single-entry cache
  7289. }
  7290. // required methods for a stream. if a particular stream does not
  7291. // implement these, an error should be thrown
  7292. ChunkedStream.prototype = {
  7293. getMissingChunks: function ChunkedStream_getMissingChunks() {
  7294. var chunks = [];
  7295. for (var chunk = 0, n = this.numChunks; chunk < n; ++chunk) {
  7296. if (!this.loadedChunks[chunk]) {
  7297. chunks.push(chunk);
  7298. }
  7299. }
  7300. return chunks;
  7301. },
  7302. getBaseStreams: function ChunkedStream_getBaseStreams() {
  7303. return [this];
  7304. },
  7305. allChunksLoaded: function ChunkedStream_allChunksLoaded() {
  7306. return this.numChunksLoaded === this.numChunks;
  7307. },
  7308. onReceiveData: function ChunkedStream_onReceiveData(begin, chunk) {
  7309. var end = begin + chunk.byteLength;
  7310. assert(begin % this.chunkSize === 0, 'Bad begin offset: ' + begin);
  7311. // Using this.length is inaccurate here since this.start can be moved
  7312. // See ChunkedStream.moveStart()
  7313. var length = this.bytes.length;
  7314. assert(end % this.chunkSize === 0 || end === length,
  7315. 'Bad end offset: ' + end);
  7316. this.bytes.set(new Uint8Array(chunk), begin);
  7317. var chunkSize = this.chunkSize;
  7318. var beginChunk = Math.floor(begin / chunkSize);
  7319. var endChunk = Math.floor((end - 1) / chunkSize) + 1;
  7320. var curChunk;
  7321. for (curChunk = beginChunk; curChunk < endChunk; ++curChunk) {
  7322. if (!this.loadedChunks[curChunk]) {
  7323. this.loadedChunks[curChunk] = true;
  7324. ++this.numChunksLoaded;
  7325. }
  7326. }
  7327. },
  7328. onReceiveProgressiveData:
  7329. function ChunkedStream_onReceiveProgressiveData(data) {
  7330. var position = this.progressiveDataLength;
  7331. var beginChunk = Math.floor(position / this.chunkSize);
  7332. this.bytes.set(new Uint8Array(data), position);
  7333. position += data.byteLength;
  7334. this.progressiveDataLength = position;
  7335. var endChunk = position >= this.end ? this.numChunks :
  7336. Math.floor(position / this.chunkSize);
  7337. var curChunk;
  7338. for (curChunk = beginChunk; curChunk < endChunk; ++curChunk) {
  7339. if (!this.loadedChunks[curChunk]) {
  7340. this.loadedChunks[curChunk] = true;
  7341. ++this.numChunksLoaded;
  7342. }
  7343. }
  7344. },
  7345. ensureByte: function ChunkedStream_ensureByte(pos) {
  7346. var chunk = Math.floor(pos / this.chunkSize);
  7347. if (chunk === this.lastSuccessfulEnsureByteChunk) {
  7348. return;
  7349. }
  7350. if (!this.loadedChunks[chunk]) {
  7351. throw new MissingDataException(pos, pos + 1);
  7352. }
  7353. this.lastSuccessfulEnsureByteChunk = chunk;
  7354. },
  7355. ensureRange: function ChunkedStream_ensureRange(begin, end) {
  7356. if (begin >= end) {
  7357. return;
  7358. }
  7359. if (end <= this.progressiveDataLength) {
  7360. return;
  7361. }
  7362. var chunkSize = this.chunkSize;
  7363. var beginChunk = Math.floor(begin / chunkSize);
  7364. var endChunk = Math.floor((end - 1) / chunkSize) + 1;
  7365. for (var chunk = beginChunk; chunk < endChunk; ++chunk) {
  7366. if (!this.loadedChunks[chunk]) {
  7367. throw new MissingDataException(begin, end);
  7368. }
  7369. }
  7370. },
  7371. nextEmptyChunk: function ChunkedStream_nextEmptyChunk(beginChunk) {
  7372. var chunk, n;
  7373. for (chunk = beginChunk, n = this.numChunks; chunk < n; ++chunk) {
  7374. if (!this.loadedChunks[chunk]) {
  7375. return chunk;
  7376. }
  7377. }
  7378. // Wrap around to beginning
  7379. for (chunk = 0; chunk < beginChunk; ++chunk) {
  7380. if (!this.loadedChunks[chunk]) {
  7381. return chunk;
  7382. }
  7383. }
  7384. return null;
  7385. },
  7386. hasChunk: function ChunkedStream_hasChunk(chunk) {
  7387. return !!this.loadedChunks[chunk];
  7388. },
  7389. get length() {
  7390. return this.end - this.start;
  7391. },
  7392. get isEmpty() {
  7393. return this.length === 0;
  7394. },
  7395. getByte: function ChunkedStream_getByte() {
  7396. var pos = this.pos;
  7397. if (pos >= this.end) {
  7398. return -1;
  7399. }
  7400. this.ensureByte(pos);
  7401. return this.bytes[this.pos++];
  7402. },
  7403. getUint16: function ChunkedStream_getUint16() {
  7404. var b0 = this.getByte();
  7405. var b1 = this.getByte();
  7406. if (b0 === -1 || b1 === -1) {
  7407. return -1;
  7408. }
  7409. return (b0 << 8) + b1;
  7410. },
  7411. getInt32: function ChunkedStream_getInt32() {
  7412. var b0 = this.getByte();
  7413. var b1 = this.getByte();
  7414. var b2 = this.getByte();
  7415. var b3 = this.getByte();
  7416. return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;
  7417. },
  7418. // returns subarray of original buffer
  7419. // should only be read
  7420. getBytes: function ChunkedStream_getBytes(length) {
  7421. var bytes = this.bytes;
  7422. var pos = this.pos;
  7423. var strEnd = this.end;
  7424. if (!length) {
  7425. this.ensureRange(pos, strEnd);
  7426. return bytes.subarray(pos, strEnd);
  7427. }
  7428. var end = pos + length;
  7429. if (end > strEnd) {
  7430. end = strEnd;
  7431. }
  7432. this.ensureRange(pos, end);
  7433. this.pos = end;
  7434. return bytes.subarray(pos, end);
  7435. },
  7436. peekByte: function ChunkedStream_peekByte() {
  7437. var peekedByte = this.getByte();
  7438. this.pos--;
  7439. return peekedByte;
  7440. },
  7441. peekBytes: function ChunkedStream_peekBytes(length) {
  7442. var bytes = this.getBytes(length);
  7443. this.pos -= bytes.length;
  7444. return bytes;
  7445. },
  7446. getByteRange: function ChunkedStream_getBytes(begin, end) {
  7447. this.ensureRange(begin, end);
  7448. return this.bytes.subarray(begin, end);
  7449. },
  7450. skip: function ChunkedStream_skip(n) {
  7451. if (!n) {
  7452. n = 1;
  7453. }
  7454. this.pos += n;
  7455. },
  7456. reset: function ChunkedStream_reset() {
  7457. this.pos = this.start;
  7458. },
  7459. moveStart: function ChunkedStream_moveStart() {
  7460. this.start = this.pos;
  7461. },
  7462. makeSubStream: function ChunkedStream_makeSubStream(start, length, dict) {
  7463. this.ensureRange(start, start + length);
  7464. function ChunkedStreamSubstream() {}
  7465. ChunkedStreamSubstream.prototype = Object.create(this);
  7466. ChunkedStreamSubstream.prototype.getMissingChunks = function() {
  7467. var chunkSize = this.chunkSize;
  7468. var beginChunk = Math.floor(this.start / chunkSize);
  7469. var endChunk = Math.floor((this.end - 1) / chunkSize) + 1;
  7470. var missingChunks = [];
  7471. for (var chunk = beginChunk; chunk < endChunk; ++chunk) {
  7472. if (!this.loadedChunks[chunk]) {
  7473. missingChunks.push(chunk);
  7474. }
  7475. }
  7476. return missingChunks;
  7477. };
  7478. var subStream = new ChunkedStreamSubstream();
  7479. subStream.pos = subStream.start = start;
  7480. subStream.end = start + length || this.end;
  7481. subStream.dict = dict;
  7482. return subStream;
  7483. },
  7484. isStream: true
  7485. };
  7486. return ChunkedStream;
  7487. })();
  7488. var ChunkedStreamManager = (function ChunkedStreamManagerClosure() {
  7489. function ChunkedStreamManager(length, chunkSize, url, args) {
  7490. this.stream = new ChunkedStream(length, chunkSize, this);
  7491. this.length = length;
  7492. this.chunkSize = chunkSize;
  7493. this.url = url;
  7494. this.disableAutoFetch = args.disableAutoFetch;
  7495. var msgHandler = this.msgHandler = args.msgHandler;
  7496. if (args.chunkedViewerLoading) {
  7497. msgHandler.on('OnDataRange', this.onReceiveData.bind(this));
  7498. msgHandler.on('OnDataProgress', this.onProgress.bind(this));
  7499. this.sendRequest = function ChunkedStreamManager_sendRequest(begin, end) {
  7500. msgHandler.send('RequestDataRange', { begin: begin, end: end });
  7501. };
  7502. } else {
  7503. var getXhr = function getXhr() {
  7504. return new XMLHttpRequest();
  7505. };
  7506. this.networkManager = new NetworkManager(this.url, {
  7507. getXhr: getXhr,
  7508. httpHeaders: args.httpHeaders,
  7509. withCredentials: args.withCredentials
  7510. });
  7511. this.sendRequest = function ChunkedStreamManager_sendRequest(begin, end) {
  7512. this.networkManager.requestRange(begin, end, {
  7513. onDone: this.onReceiveData.bind(this),
  7514. onProgress: this.onProgress.bind(this)
  7515. });
  7516. };
  7517. }
  7518. this.currRequestId = 0;
  7519. this.chunksNeededByRequest = {};
  7520. this.requestsByChunk = {};
  7521. this.callbacksByRequest = {};
  7522. this.progressiveDataLength = 0;
  7523. this._loadedStreamCapability = createPromiseCapability();
  7524. if (args.initialData) {
  7525. this.onReceiveData({chunk: args.initialData});
  7526. }
  7527. }
  7528. ChunkedStreamManager.prototype = {
  7529. onLoadedStream: function ChunkedStreamManager_getLoadedStream() {
  7530. return this._loadedStreamCapability.promise;
  7531. },
  7532. // Get all the chunks that are not yet loaded and groups them into
  7533. // contiguous ranges to load in as few requests as possible
  7534. requestAllChunks: function ChunkedStreamManager_requestAllChunks() {
  7535. var missingChunks = this.stream.getMissingChunks();
  7536. this.requestChunks(missingChunks);
  7537. return this._loadedStreamCapability.promise;
  7538. },
  7539. requestChunks: function ChunkedStreamManager_requestChunks(chunks,
  7540. callback) {
  7541. var requestId = this.currRequestId++;
  7542. var chunksNeeded;
  7543. var i, ii;
  7544. this.chunksNeededByRequest[requestId] = chunksNeeded = {};
  7545. for (i = 0, ii = chunks.length; i < ii; i++) {
  7546. if (!this.stream.hasChunk(chunks[i])) {
  7547. chunksNeeded[chunks[i]] = true;
  7548. }
  7549. }
  7550. if (isEmptyObj(chunksNeeded)) {
  7551. if (callback) {
  7552. callback();
  7553. }
  7554. return;
  7555. }
  7556. this.callbacksByRequest[requestId] = callback;
  7557. var chunksToRequest = [];
  7558. for (var chunk in chunksNeeded) {
  7559. chunk = chunk | 0;
  7560. if (!(chunk in this.requestsByChunk)) {
  7561. this.requestsByChunk[chunk] = [];
  7562. chunksToRequest.push(chunk);
  7563. }
  7564. this.requestsByChunk[chunk].push(requestId);
  7565. }
  7566. if (!chunksToRequest.length) {
  7567. return;
  7568. }
  7569. var groupedChunksToRequest = this.groupChunks(chunksToRequest);
  7570. for (i = 0; i < groupedChunksToRequest.length; ++i) {
  7571. var groupedChunk = groupedChunksToRequest[i];
  7572. var begin = groupedChunk.beginChunk * this.chunkSize;
  7573. var end = Math.min(groupedChunk.endChunk * this.chunkSize, this.length);
  7574. this.sendRequest(begin, end);
  7575. }
  7576. },
  7577. getStream: function ChunkedStreamManager_getStream() {
  7578. return this.stream;
  7579. },
  7580. // Loads any chunks in the requested range that are not yet loaded
  7581. requestRange: function ChunkedStreamManager_requestRange(
  7582. begin, end, callback) {
  7583. end = Math.min(end, this.length);
  7584. var beginChunk = this.getBeginChunk(begin);
  7585. var endChunk = this.getEndChunk(end);
  7586. var chunks = [];
  7587. for (var chunk = beginChunk; chunk < endChunk; ++chunk) {
  7588. chunks.push(chunk);
  7589. }
  7590. this.requestChunks(chunks, callback);
  7591. },
  7592. requestRanges: function ChunkedStreamManager_requestRanges(ranges,
  7593. callback) {
  7594. ranges = ranges || [];
  7595. var chunksToRequest = [];
  7596. for (var i = 0; i < ranges.length; i++) {
  7597. var beginChunk = this.getBeginChunk(ranges[i].begin);
  7598. var endChunk = this.getEndChunk(ranges[i].end);
  7599. for (var chunk = beginChunk; chunk < endChunk; ++chunk) {
  7600. if (chunksToRequest.indexOf(chunk) < 0) {
  7601. chunksToRequest.push(chunk);
  7602. }
  7603. }
  7604. }
  7605. chunksToRequest.sort(function(a, b) { return a - b; });
  7606. this.requestChunks(chunksToRequest, callback);
  7607. },
  7608. // Groups a sorted array of chunks into as few continguous larger
  7609. // chunks as possible
  7610. groupChunks: function ChunkedStreamManager_groupChunks(chunks) {
  7611. var groupedChunks = [];
  7612. var beginChunk = -1;
  7613. var prevChunk = -1;
  7614. for (var i = 0; i < chunks.length; ++i) {
  7615. var chunk = chunks[i];
  7616. if (beginChunk < 0) {
  7617. beginChunk = chunk;
  7618. }
  7619. if (prevChunk >= 0 && prevChunk + 1 !== chunk) {
  7620. groupedChunks.push({ beginChunk: beginChunk,
  7621. endChunk: prevChunk + 1 });
  7622. beginChunk = chunk;
  7623. }
  7624. if (i + 1 === chunks.length) {
  7625. groupedChunks.push({ beginChunk: beginChunk,
  7626. endChunk: chunk + 1 });
  7627. }
  7628. prevChunk = chunk;
  7629. }
  7630. return groupedChunks;
  7631. },
  7632. onProgress: function ChunkedStreamManager_onProgress(args) {
  7633. var bytesLoaded = (this.stream.numChunksLoaded * this.chunkSize +
  7634. args.loaded);
  7635. this.msgHandler.send('DocProgress', {
  7636. loaded: bytesLoaded,
  7637. total: this.length
  7638. });
  7639. },
  7640. onReceiveData: function ChunkedStreamManager_onReceiveData(args) {
  7641. var chunk = args.chunk;
  7642. var isProgressive = args.begin === undefined;
  7643. var begin = isProgressive ? this.progressiveDataLength : args.begin;
  7644. var end = begin + chunk.byteLength;
  7645. var beginChunk = Math.floor(begin / this.chunkSize);
  7646. var endChunk = end < this.length ? Math.floor(end / this.chunkSize) :
  7647. Math.ceil(end / this.chunkSize);
  7648. if (isProgressive) {
  7649. this.stream.onReceiveProgressiveData(chunk);
  7650. this.progressiveDataLength = end;
  7651. } else {
  7652. this.stream.onReceiveData(begin, chunk);
  7653. }
  7654. if (this.stream.allChunksLoaded()) {
  7655. this._loadedStreamCapability.resolve(this.stream);
  7656. }
  7657. var loadedRequests = [];
  7658. var i, requestId;
  7659. for (chunk = beginChunk; chunk < endChunk; ++chunk) {
  7660. // The server might return more chunks than requested
  7661. var requestIds = this.requestsByChunk[chunk] || [];
  7662. delete this.requestsByChunk[chunk];
  7663. for (i = 0; i < requestIds.length; ++i) {
  7664. requestId = requestIds[i];
  7665. var chunksNeeded = this.chunksNeededByRequest[requestId];
  7666. if (chunk in chunksNeeded) {
  7667. delete chunksNeeded[chunk];
  7668. }
  7669. if (!isEmptyObj(chunksNeeded)) {
  7670. continue;
  7671. }
  7672. loadedRequests.push(requestId);
  7673. }
  7674. }
  7675. // If there are no pending requests, automatically fetch the next
  7676. // unfetched chunk of the PDF
  7677. if (!this.disableAutoFetch && isEmptyObj(this.requestsByChunk)) {
  7678. var nextEmptyChunk;
  7679. if (this.stream.numChunksLoaded === 1) {
  7680. // This is a special optimization so that after fetching the first
  7681. // chunk, rather than fetching the second chunk, we fetch the last
  7682. // chunk.
  7683. var lastChunk = this.stream.numChunks - 1;
  7684. if (!this.stream.hasChunk(lastChunk)) {
  7685. nextEmptyChunk = lastChunk;
  7686. }
  7687. } else {
  7688. nextEmptyChunk = this.stream.nextEmptyChunk(endChunk);
  7689. }
  7690. if (isInt(nextEmptyChunk)) {
  7691. this.requestChunks([nextEmptyChunk]);
  7692. }
  7693. }
  7694. for (i = 0; i < loadedRequests.length; ++i) {
  7695. requestId = loadedRequests[i];
  7696. var callback = this.callbacksByRequest[requestId];
  7697. delete this.callbacksByRequest[requestId];
  7698. if (callback) {
  7699. callback();
  7700. }
  7701. }
  7702. this.msgHandler.send('DocProgress', {
  7703. loaded: this.stream.numChunksLoaded * this.chunkSize,
  7704. total: this.length
  7705. });
  7706. },
  7707. onError: function ChunkedStreamManager_onError(err) {
  7708. this._loadedStreamCapability.reject(err);
  7709. },
  7710. getBeginChunk: function ChunkedStreamManager_getBeginChunk(begin) {
  7711. var chunk = Math.floor(begin / this.chunkSize);
  7712. return chunk;
  7713. },
  7714. getEndChunk: function ChunkedStreamManager_getEndChunk(end) {
  7715. if (end % this.chunkSize === 0) {
  7716. return end / this.chunkSize;
  7717. }
  7718. // 0 -> 0
  7719. // 1 -> 1
  7720. // 99 -> 1
  7721. // 100 -> 1
  7722. // 101 -> 2
  7723. var chunk = Math.floor((end - 1) / this.chunkSize) + 1;
  7724. return chunk;
  7725. }
  7726. };
  7727. return ChunkedStreamManager;
  7728. })();
  7729. // The maximum number of bytes fetched per range request
  7730. var RANGE_CHUNK_SIZE = 65536;
  7731. // TODO(mack): Make use of PDFJS.Util.inherit() when it becomes available
  7732. var BasePdfManager = (function BasePdfManagerClosure() {
  7733. function BasePdfManager() {
  7734. throw new Error('Cannot initialize BaseManagerManager');
  7735. }
  7736. BasePdfManager.prototype = {
  7737. onLoadedStream: function BasePdfManager_onLoadedStream() {
  7738. throw new NotImplementedException();
  7739. },
  7740. ensureDoc: function BasePdfManager_ensureDoc(prop, args) {
  7741. return this.ensure(this.pdfDocument, prop, args);
  7742. },
  7743. ensureXRef: function BasePdfManager_ensureXRef(prop, args) {
  7744. return this.ensure(this.pdfDocument.xref, prop, args);
  7745. },
  7746. ensureCatalog: function BasePdfManager_ensureCatalog(prop, args) {
  7747. return this.ensure(this.pdfDocument.catalog, prop, args);
  7748. },
  7749. getPage: function BasePdfManager_pagePage(pageIndex) {
  7750. return this.pdfDocument.getPage(pageIndex);
  7751. },
  7752. cleanup: function BasePdfManager_cleanup() {
  7753. return this.pdfDocument.cleanup();
  7754. },
  7755. ensure: function BasePdfManager_ensure(obj, prop, args) {
  7756. return new NotImplementedException();
  7757. },
  7758. requestRange: function BasePdfManager_ensure(begin, end) {
  7759. return new NotImplementedException();
  7760. },
  7761. requestLoadedStream: function BasePdfManager_requestLoadedStream() {
  7762. return new NotImplementedException();
  7763. },
  7764. sendProgressiveData: function BasePdfManager_sendProgressiveData(chunk) {
  7765. return new NotImplementedException();
  7766. },
  7767. updatePassword: function BasePdfManager_updatePassword(password) {
  7768. this.pdfDocument.xref.password = this.password = password;
  7769. if (this._passwordChangedCapability) {
  7770. this._passwordChangedCapability.resolve();
  7771. }
  7772. },
  7773. passwordChanged: function BasePdfManager_passwordChanged() {
  7774. this._passwordChangedCapability = createPromiseCapability();
  7775. return this._passwordChangedCapability.promise;
  7776. },
  7777. terminate: function BasePdfManager_terminate() {
  7778. return new NotImplementedException();
  7779. }
  7780. };
  7781. return BasePdfManager;
  7782. })();
  7783. var LocalPdfManager = (function LocalPdfManagerClosure() {
  7784. function LocalPdfManager(data, password) {
  7785. var stream = new Stream(data);
  7786. this.pdfDocument = new PDFDocument(this, stream, password);
  7787. this._loadedStreamCapability = createPromiseCapability();
  7788. this._loadedStreamCapability.resolve(stream);
  7789. }
  7790. LocalPdfManager.prototype = Object.create(BasePdfManager.prototype);
  7791. LocalPdfManager.prototype.constructor = LocalPdfManager;
  7792. LocalPdfManager.prototype.ensure =
  7793. function LocalPdfManager_ensure(obj, prop, args) {
  7794. return new Promise(function (resolve, reject) {
  7795. try {
  7796. var value = obj[prop];
  7797. var result;
  7798. if (typeof value === 'function') {
  7799. result = value.apply(obj, args);
  7800. } else {
  7801. result = value;
  7802. }
  7803. resolve(result);
  7804. } catch (e) {
  7805. reject(e);
  7806. }
  7807. });
  7808. };
  7809. LocalPdfManager.prototype.requestRange =
  7810. function LocalPdfManager_requestRange(begin, end) {
  7811. return Promise.resolve();
  7812. };
  7813. LocalPdfManager.prototype.requestLoadedStream =
  7814. function LocalPdfManager_requestLoadedStream() {
  7815. };
  7816. LocalPdfManager.prototype.onLoadedStream =
  7817. function LocalPdfManager_getLoadedStream() {
  7818. return this._loadedStreamCapability.promise;
  7819. };
  7820. LocalPdfManager.prototype.terminate =
  7821. function LocalPdfManager_terminate() {
  7822. return;
  7823. };
  7824. return LocalPdfManager;
  7825. })();
  7826. var NetworkPdfManager = (function NetworkPdfManagerClosure() {
  7827. function NetworkPdfManager(args, msgHandler) {
  7828. this.msgHandler = msgHandler;
  7829. var params = {
  7830. msgHandler: msgHandler,
  7831. httpHeaders: args.httpHeaders,
  7832. withCredentials: args.withCredentials,
  7833. chunkedViewerLoading: args.chunkedViewerLoading,
  7834. disableAutoFetch: args.disableAutoFetch,
  7835. initialData: args.initialData
  7836. };
  7837. this.streamManager = new ChunkedStreamManager(args.length, RANGE_CHUNK_SIZE,
  7838. args.url, params);
  7839. this.pdfDocument = new PDFDocument(this, this.streamManager.getStream(),
  7840. args.password);
  7841. }
  7842. NetworkPdfManager.prototype = Object.create(BasePdfManager.prototype);
  7843. NetworkPdfManager.prototype.constructor = NetworkPdfManager;
  7844. NetworkPdfManager.prototype.ensure =
  7845. function NetworkPdfManager_ensure(obj, prop, args) {
  7846. var pdfManager = this;
  7847. return new Promise(function (resolve, reject) {
  7848. function ensureHelper() {
  7849. try {
  7850. var result;
  7851. var value = obj[prop];
  7852. if (typeof value === 'function') {
  7853. result = value.apply(obj, args);
  7854. } else {
  7855. result = value;
  7856. }
  7857. resolve(result);
  7858. } catch(e) {
  7859. if (!(e instanceof MissingDataException)) {
  7860. reject(e);
  7861. return;
  7862. }
  7863. pdfManager.streamManager.requestRange(e.begin, e.end, ensureHelper);
  7864. }
  7865. }
  7866. ensureHelper();
  7867. });
  7868. };
  7869. NetworkPdfManager.prototype.requestRange =
  7870. function NetworkPdfManager_requestRange(begin, end) {
  7871. return new Promise(function (resolve) {
  7872. this.streamManager.requestRange(begin, end, function() {
  7873. resolve();
  7874. });
  7875. }.bind(this));
  7876. };
  7877. NetworkPdfManager.prototype.requestLoadedStream =
  7878. function NetworkPdfManager_requestLoadedStream() {
  7879. this.streamManager.requestAllChunks();
  7880. };
  7881. NetworkPdfManager.prototype.sendProgressiveData =
  7882. function NetworkPdfManager_sendProgressiveData(chunk) {
  7883. this.streamManager.onReceiveData({ chunk: chunk });
  7884. };
  7885. NetworkPdfManager.prototype.onLoadedStream =
  7886. function NetworkPdfManager_getLoadedStream() {
  7887. return this.streamManager.onLoadedStream();
  7888. };
  7889. NetworkPdfManager.prototype.terminate =
  7890. function NetworkPdfManager_terminate() {
  7891. this.streamManager.networkManager.abortAllRequests();
  7892. };
  7893. return NetworkPdfManager;
  7894. })();
  7895. var Page = (function PageClosure() {
  7896. var LETTER_SIZE_MEDIABOX = [0, 0, 612, 792];
  7897. function Page(pdfManager, xref, pageIndex, pageDict, ref, fontCache) {
  7898. this.pdfManager = pdfManager;
  7899. this.pageIndex = pageIndex;
  7900. this.pageDict = pageDict;
  7901. this.xref = xref;
  7902. this.ref = ref;
  7903. this.fontCache = fontCache;
  7904. this.idCounters = {
  7905. obj: 0
  7906. };
  7907. this.resourcesPromise = null;
  7908. }
  7909. Page.prototype = {
  7910. getPageProp: function Page_getPageProp(key) {
  7911. return this.pageDict.get(key);
  7912. },
  7913. getInheritedPageProp: function Page_getInheritedPageProp(key) {
  7914. var dict = this.pageDict, valueArray = null, loopCount = 0;
  7915. var MAX_LOOP_COUNT = 100;
  7916. // Always walk up the entire parent chain, to be able to find
  7917. // e.g. \Resources placed on multiple levels of the tree.
  7918. while (dict) {
  7919. var value = dict.get(key);
  7920. if (value) {
  7921. if (!valueArray) {
  7922. valueArray = [];
  7923. }
  7924. valueArray.push(value);
  7925. }
  7926. if (++loopCount > MAX_LOOP_COUNT) {
  7927. warn('Page_getInheritedPageProp: maximum loop count exceeded.');
  7928. break;
  7929. }
  7930. dict = dict.get('Parent');
  7931. }
  7932. if (!valueArray) {
  7933. return Dict.empty;
  7934. }
  7935. if (valueArray.length === 1 || !isDict(valueArray[0]) ||
  7936. loopCount > MAX_LOOP_COUNT) {
  7937. return valueArray[0];
  7938. }
  7939. return Dict.merge(this.xref, valueArray);
  7940. },
  7941. get content() {
  7942. return this.getPageProp('Contents');
  7943. },
  7944. get resources() {
  7945. // For robustness: The spec states that a \Resources entry has to be
  7946. // present, but can be empty. Some document omit it still, in this case
  7947. // we return an empty dictionary.
  7948. return shadow(this, 'resources', this.getInheritedPageProp('Resources'));
  7949. },
  7950. get mediaBox() {
  7951. var obj = this.getInheritedPageProp('MediaBox');
  7952. // Reset invalid media box to letter size.
  7953. if (!isArray(obj) || obj.length !== 4) {
  7954. obj = LETTER_SIZE_MEDIABOX;
  7955. }
  7956. return shadow(this, 'mediaBox', obj);
  7957. },
  7958. get view() {
  7959. var mediaBox = this.mediaBox;
  7960. var cropBox = this.getInheritedPageProp('CropBox');
  7961. if (!isArray(cropBox) || cropBox.length !== 4) {
  7962. return shadow(this, 'view', mediaBox);
  7963. }
  7964. // From the spec, 6th ed., p.963:
  7965. // "The crop, bleed, trim, and art boxes should not ordinarily
  7966. // extend beyond the boundaries of the media box. If they do, they are
  7967. // effectively reduced to their intersection with the media box."
  7968. cropBox = Util.intersect(cropBox, mediaBox);
  7969. if (!cropBox) {
  7970. return shadow(this, 'view', mediaBox);
  7971. }
  7972. return shadow(this, 'view', cropBox);
  7973. },
  7974. get annotationRefs() {
  7975. return shadow(this, 'annotationRefs',
  7976. this.getInheritedPageProp('Annots'));
  7977. },
  7978. get rotate() {
  7979. var rotate = this.getInheritedPageProp('Rotate') || 0;
  7980. // Normalize rotation so it's a multiple of 90 and between 0 and 270
  7981. if (rotate % 90 !== 0) {
  7982. rotate = 0;
  7983. } else if (rotate >= 360) {
  7984. rotate = rotate % 360;
  7985. } else if (rotate < 0) {
  7986. // The spec doesn't cover negatives, assume its counterclockwise
  7987. // rotation. The following is the other implementation of modulo.
  7988. rotate = ((rotate % 360) + 360) % 360;
  7989. }
  7990. return shadow(this, 'rotate', rotate);
  7991. },
  7992. getContentStream: function Page_getContentStream() {
  7993. var content = this.content;
  7994. var stream;
  7995. if (isArray(content)) {
  7996. // fetching items
  7997. var xref = this.xref;
  7998. var i, n = content.length;
  7999. var streams = [];
  8000. for (i = 0; i < n; ++i) {
  8001. streams.push(xref.fetchIfRef(content[i]));
  8002. }
  8003. stream = new StreamsSequenceStream(streams);
  8004. } else if (isStream(content)) {
  8005. stream = content;
  8006. } else {
  8007. // replacing non-existent page content with empty one
  8008. stream = new NullStream();
  8009. }
  8010. return stream;
  8011. },
  8012. loadResources: function Page_loadResources(keys) {
  8013. if (!this.resourcesPromise) {
  8014. // TODO: add async getInheritedPageProp and remove this.
  8015. this.resourcesPromise = this.pdfManager.ensure(this, 'resources');
  8016. }
  8017. return this.resourcesPromise.then(function resourceSuccess() {
  8018. var objectLoader = new ObjectLoader(this.resources.map,
  8019. keys,
  8020. this.xref);
  8021. return objectLoader.load();
  8022. }.bind(this));
  8023. },
  8024. getOperatorList: function Page_getOperatorList(handler, intent) {
  8025. var self = this;
  8026. var pdfManager = this.pdfManager;
  8027. var contentStreamPromise = pdfManager.ensure(this, 'getContentStream',
  8028. []);
  8029. var resourcesPromise = this.loadResources([
  8030. 'ExtGState',
  8031. 'ColorSpace',
  8032. 'Pattern',
  8033. 'Shading',
  8034. 'XObject',
  8035. 'Font'
  8036. // ProcSet
  8037. // Properties
  8038. ]);
  8039. var partialEvaluator = new PartialEvaluator(pdfManager, this.xref,
  8040. handler, this.pageIndex,
  8041. 'p' + this.pageIndex + '_',
  8042. this.idCounters,
  8043. this.fontCache);
  8044. var dataPromises = Promise.all([contentStreamPromise, resourcesPromise]);
  8045. var pageListPromise = dataPromises.then(function(data) {
  8046. var contentStream = data[0];
  8047. var opList = new OperatorList(intent, handler, self.pageIndex);
  8048. handler.send('StartRenderPage', {
  8049. transparency: partialEvaluator.hasBlendModes(self.resources),
  8050. pageIndex: self.pageIndex,
  8051. intent: intent
  8052. });
  8053. return partialEvaluator.getOperatorList(contentStream, self.resources,
  8054. opList).then(function () {
  8055. return opList;
  8056. });
  8057. });
  8058. var annotationsPromise = pdfManager.ensure(this, 'annotations');
  8059. return Promise.all([pageListPromise, annotationsPromise]).then(
  8060. function(datas) {
  8061. var pageOpList = datas[0];
  8062. var annotations = datas[1];
  8063. if (annotations.length === 0) {
  8064. pageOpList.flush(true);
  8065. return pageOpList;
  8066. }
  8067. var annotationsReadyPromise = Annotation.appendToOperatorList(
  8068. annotations, pageOpList, pdfManager, partialEvaluator, intent);
  8069. return annotationsReadyPromise.then(function () {
  8070. pageOpList.flush(true);
  8071. return pageOpList;
  8072. });
  8073. });
  8074. },
  8075. extractTextContent: function Page_extractTextContent() {
  8076. var handler = {
  8077. on: function nullHandlerOn() {},
  8078. send: function nullHandlerSend() {}
  8079. };
  8080. var self = this;
  8081. var pdfManager = this.pdfManager;
  8082. var contentStreamPromise = pdfManager.ensure(this, 'getContentStream',
  8083. []);
  8084. var resourcesPromise = this.loadResources([
  8085. 'ExtGState',
  8086. 'XObject',
  8087. 'Font'
  8088. ]);
  8089. var dataPromises = Promise.all([contentStreamPromise,
  8090. resourcesPromise]);
  8091. return dataPromises.then(function(data) {
  8092. var contentStream = data[0];
  8093. var partialEvaluator = new PartialEvaluator(pdfManager, self.xref,
  8094. handler, self.pageIndex,
  8095. 'p' + self.pageIndex + '_',
  8096. self.idCounters,
  8097. self.fontCache);
  8098. return partialEvaluator.getTextContent(contentStream,
  8099. self.resources);
  8100. });
  8101. },
  8102. getAnnotationsData: function Page_getAnnotationsData() {
  8103. var annotations = this.annotations;
  8104. var annotationsData = [];
  8105. for (var i = 0, n = annotations.length; i < n; ++i) {
  8106. annotationsData.push(annotations[i].getData());
  8107. }
  8108. return annotationsData;
  8109. },
  8110. get annotations() {
  8111. var annotations = [];
  8112. var annotationRefs = (this.annotationRefs || []);
  8113. for (var i = 0, n = annotationRefs.length; i < n; ++i) {
  8114. var annotationRef = annotationRefs[i];
  8115. var annotation = Annotation.fromRef(this.xref, annotationRef);
  8116. if (annotation) {
  8117. annotations.push(annotation);
  8118. }
  8119. }
  8120. return shadow(this, 'annotations', annotations);
  8121. }
  8122. };
  8123. return Page;
  8124. })();
  8125. /**
  8126. * The `PDFDocument` holds all the data of the PDF file. Compared to the
  8127. * `PDFDoc`, this one doesn't have any job management code.
  8128. * Right now there exists one PDFDocument on the main thread + one object
  8129. * for each worker. If there is no worker support enabled, there are two
  8130. * `PDFDocument` objects on the main thread created.
  8131. */
  8132. var PDFDocument = (function PDFDocumentClosure() {
  8133. var FINGERPRINT_FIRST_BYTES = 1024;
  8134. var EMPTY_FINGERPRINT = '\x00\x00\x00\x00\x00\x00\x00' +
  8135. '\x00\x00\x00\x00\x00\x00\x00\x00\x00';
  8136. function PDFDocument(pdfManager, arg, password) {
  8137. if (isStream(arg)) {
  8138. init.call(this, pdfManager, arg, password);
  8139. } else if (isArrayBuffer(arg)) {
  8140. init.call(this, pdfManager, new Stream(arg), password);
  8141. } else {
  8142. error('PDFDocument: Unknown argument type');
  8143. }
  8144. }
  8145. function init(pdfManager, stream, password) {
  8146. assert(stream.length > 0, 'stream must have data');
  8147. this.pdfManager = pdfManager;
  8148. this.stream = stream;
  8149. var xref = new XRef(this.stream, password, pdfManager);
  8150. this.xref = xref;
  8151. }
  8152. function find(stream, needle, limit, backwards) {
  8153. var pos = stream.pos;
  8154. var end = stream.end;
  8155. var strBuf = [];
  8156. if (pos + limit > end) {
  8157. limit = end - pos;
  8158. }
  8159. for (var n = 0; n < limit; ++n) {
  8160. strBuf.push(String.fromCharCode(stream.getByte()));
  8161. }
  8162. var str = strBuf.join('');
  8163. stream.pos = pos;
  8164. var index = backwards ? str.lastIndexOf(needle) : str.indexOf(needle);
  8165. if (index === -1) {
  8166. return false; /* not found */
  8167. }
  8168. stream.pos += index;
  8169. return true; /* found */
  8170. }
  8171. var DocumentInfoValidators = {
  8172. get entries() {
  8173. // Lazily build this since all the validation functions below are not
  8174. // defined until after this file loads.
  8175. return shadow(this, 'entries', {
  8176. Title: isString,
  8177. Author: isString,
  8178. Subject: isString,
  8179. Keywords: isString,
  8180. Creator: isString,
  8181. Producer: isString,
  8182. CreationDate: isString,
  8183. ModDate: isString,
  8184. Trapped: isName
  8185. });
  8186. }
  8187. };
  8188. PDFDocument.prototype = {
  8189. parse: function PDFDocument_parse(recoveryMode) {
  8190. this.setup(recoveryMode);
  8191. var version = this.catalog.catDict.get('Version');
  8192. if (isName(version)) {
  8193. this.pdfFormatVersion = version.name;
  8194. }
  8195. try {
  8196. // checking if AcroForm is present
  8197. this.acroForm = this.catalog.catDict.get('AcroForm');
  8198. if (this.acroForm) {
  8199. this.xfa = this.acroForm.get('XFA');
  8200. var fields = this.acroForm.get('Fields');
  8201. if ((!fields || !isArray(fields) || fields.length === 0) &&
  8202. !this.xfa) {
  8203. // no fields and no XFA -- not a form (?)
  8204. this.acroForm = null;
  8205. }
  8206. }
  8207. } catch (ex) {
  8208. info('Something wrong with AcroForm entry');
  8209. this.acroForm = null;
  8210. }
  8211. },
  8212. get linearization() {
  8213. var linearization = null;
  8214. if (this.stream.length) {
  8215. try {
  8216. linearization = Linearization.create(this.stream);
  8217. } catch (err) {
  8218. if (err instanceof MissingDataException) {
  8219. throw err;
  8220. }
  8221. info(err);
  8222. }
  8223. }
  8224. // shadow the prototype getter with a data property
  8225. return shadow(this, 'linearization', linearization);
  8226. },
  8227. get startXRef() {
  8228. var stream = this.stream;
  8229. var startXRef = 0;
  8230. var linearization = this.linearization;
  8231. if (linearization) {
  8232. // Find end of first obj.
  8233. stream.reset();
  8234. if (find(stream, 'endobj', 1024)) {
  8235. startXRef = stream.pos + 6;
  8236. }
  8237. } else {
  8238. // Find startxref by jumping backward from the end of the file.
  8239. var step = 1024;
  8240. var found = false, pos = stream.end;
  8241. while (!found && pos > 0) {
  8242. pos -= step - 'startxref'.length;
  8243. if (pos < 0) {
  8244. pos = 0;
  8245. }
  8246. stream.pos = pos;
  8247. found = find(stream, 'startxref', step, true);
  8248. }
  8249. if (found) {
  8250. stream.skip(9);
  8251. var ch;
  8252. do {
  8253. ch = stream.getByte();
  8254. } while (Lexer.isSpace(ch));
  8255. var str = '';
  8256. while (ch >= 0x20 && ch <= 0x39) { // < '9'
  8257. str += String.fromCharCode(ch);
  8258. ch = stream.getByte();
  8259. }
  8260. startXRef = parseInt(str, 10);
  8261. if (isNaN(startXRef)) {
  8262. startXRef = 0;
  8263. }
  8264. }
  8265. }
  8266. // shadow the prototype getter with a data property
  8267. return shadow(this, 'startXRef', startXRef);
  8268. },
  8269. get mainXRefEntriesOffset() {
  8270. var mainXRefEntriesOffset = 0;
  8271. var linearization = this.linearization;
  8272. if (linearization) {
  8273. mainXRefEntriesOffset = linearization.mainXRefEntriesOffset;
  8274. }
  8275. // shadow the prototype getter with a data property
  8276. return shadow(this, 'mainXRefEntriesOffset', mainXRefEntriesOffset);
  8277. },
  8278. // Find the header, remove leading garbage and setup the stream
  8279. // starting from the header.
  8280. checkHeader: function PDFDocument_checkHeader() {
  8281. var stream = this.stream;
  8282. stream.reset();
  8283. if (find(stream, '%PDF-', 1024)) {
  8284. // Found the header, trim off any garbage before it.
  8285. stream.moveStart();
  8286. // Reading file format version
  8287. var MAX_VERSION_LENGTH = 12;
  8288. var version = '', ch;
  8289. while ((ch = stream.getByte()) > 0x20) { // SPACE
  8290. if (version.length >= MAX_VERSION_LENGTH) {
  8291. break;
  8292. }
  8293. version += String.fromCharCode(ch);
  8294. }
  8295. if (!this.pdfFormatVersion) {
  8296. // removing "%PDF-"-prefix
  8297. this.pdfFormatVersion = version.substring(5);
  8298. }
  8299. return;
  8300. }
  8301. // May not be a PDF file, continue anyway.
  8302. },
  8303. parseStartXRef: function PDFDocument_parseStartXRef() {
  8304. var startXRef = this.startXRef;
  8305. this.xref.setStartXRef(startXRef);
  8306. },
  8307. setup: function PDFDocument_setup(recoveryMode) {
  8308. this.xref.parse(recoveryMode);
  8309. this.catalog = new Catalog(this.pdfManager, this.xref);
  8310. },
  8311. get numPages() {
  8312. var linearization = this.linearization;
  8313. var num = linearization ? linearization.numPages : this.catalog.numPages;
  8314. // shadow the prototype getter
  8315. return shadow(this, 'numPages', num);
  8316. },
  8317. get documentInfo() {
  8318. var docInfo = {
  8319. PDFFormatVersion: this.pdfFormatVersion,
  8320. IsAcroFormPresent: !!this.acroForm,
  8321. IsXFAPresent: !!this.xfa
  8322. };
  8323. var infoDict;
  8324. try {
  8325. infoDict = this.xref.trailer.get('Info');
  8326. } catch (err) {
  8327. info('The document information dictionary is invalid.');
  8328. }
  8329. if (infoDict) {
  8330. var validEntries = DocumentInfoValidators.entries;
  8331. // Only fill the document info with valid entries from the spec.
  8332. for (var key in validEntries) {
  8333. if (infoDict.has(key)) {
  8334. var value = infoDict.get(key);
  8335. // Make sure the value conforms to the spec.
  8336. if (validEntries[key](value)) {
  8337. docInfo[key] = (typeof value !== 'string' ?
  8338. value : stringToPDFString(value));
  8339. } else {
  8340. info('Bad value in document info for "' + key + '"');
  8341. }
  8342. }
  8343. }
  8344. }
  8345. return shadow(this, 'documentInfo', docInfo);
  8346. },
  8347. get fingerprint() {
  8348. var xref = this.xref, idArray, hash, fileID = '';
  8349. if (xref.trailer.has('ID')) {
  8350. idArray = xref.trailer.get('ID');
  8351. }
  8352. if (idArray && isArray(idArray) && idArray[0] !== EMPTY_FINGERPRINT) {
  8353. hash = stringToBytes(idArray[0]);
  8354. } else {
  8355. if (this.stream.ensureRange) {
  8356. this.stream.ensureRange(0,
  8357. Math.min(FINGERPRINT_FIRST_BYTES, this.stream.end));
  8358. }
  8359. hash = calculateMD5(this.stream.bytes.subarray(0,
  8360. FINGERPRINT_FIRST_BYTES), 0, FINGERPRINT_FIRST_BYTES);
  8361. }
  8362. for (var i = 0, n = hash.length; i < n; i++) {
  8363. var hex = hash[i].toString(16);
  8364. fileID += hex.length === 1 ? '0' + hex : hex;
  8365. }
  8366. return shadow(this, 'fingerprint', fileID);
  8367. },
  8368. getPage: function PDFDocument_getPage(pageIndex) {
  8369. return this.catalog.getPage(pageIndex);
  8370. },
  8371. cleanup: function PDFDocument_cleanup() {
  8372. return this.catalog.cleanup();
  8373. }
  8374. };
  8375. return PDFDocument;
  8376. })();
  8377. var Name = (function NameClosure() {
  8378. function Name(name) {
  8379. this.name = name;
  8380. }
  8381. Name.prototype = {};
  8382. var nameCache = {};
  8383. Name.get = function Name_get(name) {
  8384. var nameValue = nameCache[name];
  8385. return (nameValue ? nameValue : (nameCache[name] = new Name(name)));
  8386. };
  8387. return Name;
  8388. })();
  8389. var Cmd = (function CmdClosure() {
  8390. function Cmd(cmd) {
  8391. this.cmd = cmd;
  8392. }
  8393. Cmd.prototype = {};
  8394. var cmdCache = {};
  8395. Cmd.get = function Cmd_get(cmd) {
  8396. var cmdValue = cmdCache[cmd];
  8397. return (cmdValue ? cmdValue : (cmdCache[cmd] = new Cmd(cmd)));
  8398. };
  8399. return Cmd;
  8400. })();
  8401. var Dict = (function DictClosure() {
  8402. var nonSerializable = function nonSerializableClosure() {
  8403. return nonSerializable; // creating closure on some variable
  8404. };
  8405. var GETALL_DICTIONARY_TYPES_WHITELIST = {
  8406. 'Background': true,
  8407. 'ExtGState': true,
  8408. 'Halftone': true,
  8409. 'Layout': true,
  8410. 'Mask': true,
  8411. 'Pagination': true,
  8412. 'Printing': true
  8413. };
  8414. function isRecursionAllowedFor(dict) {
  8415. if (!isName(dict.Type)) {
  8416. return true;
  8417. }
  8418. var dictType = dict.Type.name;
  8419. return GETALL_DICTIONARY_TYPES_WHITELIST[dictType] === true;
  8420. }
  8421. // xref is optional
  8422. function Dict(xref) {
  8423. // Map should only be used internally, use functions below to access.
  8424. this.map = Object.create(null);
  8425. this.xref = xref;
  8426. this.objId = null;
  8427. this.__nonSerializable__ = nonSerializable; // disable cloning of the Dict
  8428. }
  8429. Dict.prototype = {
  8430. assignXref: function Dict_assignXref(newXref) {
  8431. this.xref = newXref;
  8432. },
  8433. // automatically dereferences Ref objects
  8434. get: function Dict_get(key1, key2, key3) {
  8435. var value;
  8436. var xref = this.xref;
  8437. if (typeof (value = this.map[key1]) !== 'undefined' || key1 in this.map ||
  8438. typeof key2 === 'undefined') {
  8439. return xref ? xref.fetchIfRef(value) : value;
  8440. }
  8441. if (typeof (value = this.map[key2]) !== 'undefined' || key2 in this.map ||
  8442. typeof key3 === 'undefined') {
  8443. return xref ? xref.fetchIfRef(value) : value;
  8444. }
  8445. value = this.map[key3] || null;
  8446. return xref ? xref.fetchIfRef(value) : value;
  8447. },
  8448. // Same as get(), but returns a promise and uses fetchIfRefAsync().
  8449. getAsync: function Dict_getAsync(key1, key2, key3) {
  8450. var value;
  8451. var xref = this.xref;
  8452. if (typeof (value = this.map[key1]) !== 'undefined' || key1 in this.map ||
  8453. typeof key2 === 'undefined') {
  8454. if (xref) {
  8455. return xref.fetchIfRefAsync(value);
  8456. }
  8457. return Promise.resolve(value);
  8458. }
  8459. if (typeof (value = this.map[key2]) !== 'undefined' || key2 in this.map ||
  8460. typeof key3 === 'undefined') {
  8461. if (xref) {
  8462. return xref.fetchIfRefAsync(value);
  8463. }
  8464. return Promise.resolve(value);
  8465. }
  8466. value = this.map[key3] || null;
  8467. if (xref) {
  8468. return xref.fetchIfRefAsync(value);
  8469. }
  8470. return Promise.resolve(value);
  8471. },
  8472. // no dereferencing
  8473. getRaw: function Dict_getRaw(key) {
  8474. return this.map[key];
  8475. },
  8476. // creates new map and dereferences all Refs
  8477. getAll: function Dict_getAll() {
  8478. var all = Object.create(null);
  8479. var queue = null;
  8480. var key, obj;
  8481. for (key in this.map) {
  8482. obj = this.get(key);
  8483. if (obj instanceof Dict) {
  8484. if (isRecursionAllowedFor(obj)) {
  8485. (queue || (queue = [])).push({target: all, key: key, obj: obj});
  8486. } else {
  8487. all[key] = this.getRaw(key);
  8488. }
  8489. } else {
  8490. all[key] = obj;
  8491. }
  8492. }
  8493. if (!queue) {
  8494. return all;
  8495. }
  8496. // trying to take cyclic references into the account
  8497. var processed = Object.create(null);
  8498. while (queue.length > 0) {
  8499. var item = queue.shift();
  8500. var itemObj = item.obj;
  8501. var objId = itemObj.objId;
  8502. if (objId && objId in processed) {
  8503. item.target[item.key] = processed[objId];
  8504. continue;
  8505. }
  8506. var dereferenced = Object.create(null);
  8507. for (key in itemObj.map) {
  8508. obj = itemObj.get(key);
  8509. if (obj instanceof Dict) {
  8510. if (isRecursionAllowedFor(obj)) {
  8511. queue.push({target: dereferenced, key: key, obj: obj});
  8512. } else {
  8513. dereferenced[key] = itemObj.getRaw(key);
  8514. }
  8515. } else {
  8516. dereferenced[key] = obj;
  8517. }
  8518. }
  8519. if (objId) {
  8520. processed[objId] = dereferenced;
  8521. }
  8522. item.target[item.key] = dereferenced;
  8523. }
  8524. return all;
  8525. },
  8526. getKeys: function Dict_getKeys() {
  8527. return Object.keys(this.map);
  8528. },
  8529. set: function Dict_set(key, value) {
  8530. this.map[key] = value;
  8531. },
  8532. has: function Dict_has(key) {
  8533. return key in this.map;
  8534. },
  8535. forEach: function Dict_forEach(callback) {
  8536. for (var key in this.map) {
  8537. callback(key, this.get(key));
  8538. }
  8539. }
  8540. };
  8541. Dict.empty = new Dict(null);
  8542. Dict.merge = function Dict_merge(xref, dictArray) {
  8543. var mergedDict = new Dict(xref);
  8544. for (var i = 0, ii = dictArray.length; i < ii; i++) {
  8545. var dict = dictArray[i];
  8546. if (!isDict(dict)) {
  8547. continue;
  8548. }
  8549. for (var keyName in dict.map) {
  8550. if (mergedDict.map[keyName]) {
  8551. continue;
  8552. }
  8553. mergedDict.map[keyName] = dict.map[keyName];
  8554. }
  8555. }
  8556. return mergedDict;
  8557. };
  8558. return Dict;
  8559. })();
  8560. var Ref = (function RefClosure() {
  8561. function Ref(num, gen) {
  8562. this.num = num;
  8563. this.gen = gen;
  8564. }
  8565. Ref.prototype = {
  8566. toString: function Ref_toString() {
  8567. // This function is hot, so we make the string as compact as possible.
  8568. // |this.gen| is almost always zero, so we treat that case specially.
  8569. var str = this.num + 'R';
  8570. if (this.gen !== 0) {
  8571. str += this.gen;
  8572. }
  8573. return str;
  8574. }
  8575. };
  8576. return Ref;
  8577. })();
  8578. // The reference is identified by number and generation.
  8579. // This structure stores only one instance of the reference.
  8580. var RefSet = (function RefSetClosure() {
  8581. function RefSet() {
  8582. this.dict = {};
  8583. }
  8584. RefSet.prototype = {
  8585. has: function RefSet_has(ref) {
  8586. return ref.toString() in this.dict;
  8587. },
  8588. put: function RefSet_put(ref) {
  8589. this.dict[ref.toString()] = true;
  8590. },
  8591. remove: function RefSet_remove(ref) {
  8592. delete this.dict[ref.toString()];
  8593. }
  8594. };
  8595. return RefSet;
  8596. })();
  8597. var RefSetCache = (function RefSetCacheClosure() {
  8598. function RefSetCache() {
  8599. this.dict = Object.create(null);
  8600. }
  8601. RefSetCache.prototype = {
  8602. get: function RefSetCache_get(ref) {
  8603. return this.dict[ref.toString()];
  8604. },
  8605. has: function RefSetCache_has(ref) {
  8606. return ref.toString() in this.dict;
  8607. },
  8608. put: function RefSetCache_put(ref, obj) {
  8609. this.dict[ref.toString()] = obj;
  8610. },
  8611. putAlias: function RefSetCache_putAlias(ref, aliasRef) {
  8612. this.dict[ref.toString()] = this.get(aliasRef);
  8613. },
  8614. forEach: function RefSetCache_forEach(fn, thisArg) {
  8615. for (var i in this.dict) {
  8616. fn.call(thisArg, this.dict[i]);
  8617. }
  8618. },
  8619. clear: function RefSetCache_clear() {
  8620. this.dict = Object.create(null);
  8621. }
  8622. };
  8623. return RefSetCache;
  8624. })();
  8625. var Catalog = (function CatalogClosure() {
  8626. function Catalog(pdfManager, xref) {
  8627. this.pdfManager = pdfManager;
  8628. this.xref = xref;
  8629. this.catDict = xref.getCatalogObj();
  8630. this.fontCache = new RefSetCache();
  8631. assert(isDict(this.catDict),
  8632. 'catalog object is not a dictionary');
  8633. this.pagePromises = [];
  8634. }
  8635. Catalog.prototype = {
  8636. get metadata() {
  8637. var streamRef = this.catDict.getRaw('Metadata');
  8638. if (!isRef(streamRef)) {
  8639. return shadow(this, 'metadata', null);
  8640. }
  8641. var encryptMetadata = (!this.xref.encrypt ? false :
  8642. this.xref.encrypt.encryptMetadata);
  8643. var stream = this.xref.fetch(streamRef, !encryptMetadata);
  8644. var metadata;
  8645. if (stream && isDict(stream.dict)) {
  8646. var type = stream.dict.get('Type');
  8647. var subtype = stream.dict.get('Subtype');
  8648. if (isName(type) && isName(subtype) &&
  8649. type.name === 'Metadata' && subtype.name === 'XML') {
  8650. // XXX: This should examine the charset the XML document defines,
  8651. // however since there are currently no real means to decode
  8652. // arbitrary charsets, let's just hope that the author of the PDF
  8653. // was reasonable enough to stick with the XML default charset,
  8654. // which is UTF-8.
  8655. try {
  8656. metadata = stringToUTF8String(bytesToString(stream.getBytes()));
  8657. } catch (e) {
  8658. info('Skipping invalid metadata.');
  8659. }
  8660. }
  8661. }
  8662. return shadow(this, 'metadata', metadata);
  8663. },
  8664. get toplevelPagesDict() {
  8665. var pagesObj = this.catDict.get('Pages');
  8666. assert(isDict(pagesObj), 'invalid top-level pages dictionary');
  8667. // shadow the prototype getter
  8668. return shadow(this, 'toplevelPagesDict', pagesObj);
  8669. },
  8670. get documentOutline() {
  8671. var obj = null;
  8672. try {
  8673. obj = this.readDocumentOutline();
  8674. } catch (ex) {
  8675. if (ex instanceof MissingDataException) {
  8676. throw ex;
  8677. }
  8678. warn('Unable to read document outline');
  8679. }
  8680. return shadow(this, 'documentOutline', obj);
  8681. },
  8682. readDocumentOutline: function Catalog_readDocumentOutline() {
  8683. var xref = this.xref;
  8684. var obj = this.catDict.get('Outlines');
  8685. var root = { items: [] };
  8686. if (isDict(obj)) {
  8687. obj = obj.getRaw('First');
  8688. var processed = new RefSet();
  8689. if (isRef(obj)) {
  8690. var queue = [{obj: obj, parent: root}];
  8691. // to avoid recursion keeping track of the items
  8692. // in the processed dictionary
  8693. processed.put(obj);
  8694. while (queue.length > 0) {
  8695. var i = queue.shift();
  8696. var outlineDict = xref.fetchIfRef(i.obj);
  8697. if (outlineDict === null) {
  8698. continue;
  8699. }
  8700. if (!outlineDict.has('Title')) {
  8701. error('Invalid outline item');
  8702. }
  8703. var dest = outlineDict.get('A');
  8704. if (dest) {
  8705. dest = dest.get('D');
  8706. } else if (outlineDict.has('Dest')) {
  8707. dest = outlineDict.getRaw('Dest');
  8708. if (isName(dest)) {
  8709. dest = dest.name;
  8710. }
  8711. }
  8712. var title = outlineDict.get('Title');
  8713. var outlineItem = {
  8714. dest: dest,
  8715. title: stringToPDFString(title),
  8716. color: outlineDict.get('C') || [0, 0, 0],
  8717. count: outlineDict.get('Count'),
  8718. bold: !!(outlineDict.get('F') & 2),
  8719. italic: !!(outlineDict.get('F') & 1),
  8720. items: []
  8721. };
  8722. i.parent.items.push(outlineItem);
  8723. obj = outlineDict.getRaw('First');
  8724. if (isRef(obj) && !processed.has(obj)) {
  8725. queue.push({obj: obj, parent: outlineItem});
  8726. processed.put(obj);
  8727. }
  8728. obj = outlineDict.getRaw('Next');
  8729. if (isRef(obj) && !processed.has(obj)) {
  8730. queue.push({obj: obj, parent: i.parent});
  8731. processed.put(obj);
  8732. }
  8733. }
  8734. }
  8735. }
  8736. return (root.items.length > 0 ? root.items : null);
  8737. },
  8738. get numPages() {
  8739. var obj = this.toplevelPagesDict.get('Count');
  8740. assert(
  8741. isInt(obj),
  8742. 'page count in top level pages object is not an integer'
  8743. );
  8744. // shadow the prototype getter
  8745. return shadow(this, 'num', obj);
  8746. },
  8747. get destinations() {
  8748. function fetchDestination(dest) {
  8749. return isDict(dest) ? dest.get('D') : dest;
  8750. }
  8751. var xref = this.xref;
  8752. var dests = {}, nameTreeRef, nameDictionaryRef;
  8753. var obj = this.catDict.get('Names');
  8754. if (obj && obj.has('Dests')) {
  8755. nameTreeRef = obj.getRaw('Dests');
  8756. } else if (this.catDict.has('Dests')) {
  8757. nameDictionaryRef = this.catDict.get('Dests');
  8758. }
  8759. if (nameDictionaryRef) {
  8760. // reading simple destination dictionary
  8761. obj = nameDictionaryRef;
  8762. obj.forEach(function catalogForEach(key, value) {
  8763. if (!value) {
  8764. return;
  8765. }
  8766. dests[key] = fetchDestination(value);
  8767. });
  8768. }
  8769. if (nameTreeRef) {
  8770. var nameTree = new NameTree(nameTreeRef, xref);
  8771. var names = nameTree.getAll();
  8772. for (var name in names) {
  8773. if (!names.hasOwnProperty(name)) {
  8774. continue;
  8775. }
  8776. dests[name] = fetchDestination(names[name]);
  8777. }
  8778. }
  8779. return shadow(this, 'destinations', dests);
  8780. },
  8781. getDestination: function Catalog_getDestination(destinationId) {
  8782. function fetchDestination(dest) {
  8783. return isDict(dest) ? dest.get('D') : dest;
  8784. }
  8785. var xref = this.xref;
  8786. var dest, nameTreeRef, nameDictionaryRef;
  8787. var obj = this.catDict.get('Names');
  8788. if (obj && obj.has('Dests')) {
  8789. nameTreeRef = obj.getRaw('Dests');
  8790. } else if (this.catDict.has('Dests')) {
  8791. nameDictionaryRef = this.catDict.get('Dests');
  8792. }
  8793. if (nameDictionaryRef) {
  8794. // reading simple destination dictionary
  8795. obj = nameDictionaryRef;
  8796. obj.forEach(function catalogForEach(key, value) {
  8797. if (!value) {
  8798. return;
  8799. }
  8800. if (key === destinationId) {
  8801. dest = fetchDestination(value);
  8802. }
  8803. });
  8804. }
  8805. if (nameTreeRef) {
  8806. var nameTree = new NameTree(nameTreeRef, xref);
  8807. dest = fetchDestination(nameTree.get(destinationId));
  8808. }
  8809. return dest;
  8810. },
  8811. get attachments() {
  8812. var xref = this.xref;
  8813. var attachments = null, nameTreeRef;
  8814. var obj = this.catDict.get('Names');
  8815. if (obj) {
  8816. nameTreeRef = obj.getRaw('EmbeddedFiles');
  8817. }
  8818. if (nameTreeRef) {
  8819. var nameTree = new NameTree(nameTreeRef, xref);
  8820. var names = nameTree.getAll();
  8821. for (var name in names) {
  8822. if (!names.hasOwnProperty(name)) {
  8823. continue;
  8824. }
  8825. var fs = new FileSpec(names[name], xref);
  8826. if (!attachments) {
  8827. attachments = {};
  8828. }
  8829. attachments[stringToPDFString(name)] = fs.serializable;
  8830. }
  8831. }
  8832. return shadow(this, 'attachments', attachments);
  8833. },
  8834. get javaScript() {
  8835. var xref = this.xref;
  8836. var obj = this.catDict.get('Names');
  8837. var javaScript = [];
  8838. if (obj && obj.has('JavaScript')) {
  8839. var nameTree = new NameTree(obj.getRaw('JavaScript'), xref);
  8840. var names = nameTree.getAll();
  8841. for (var name in names) {
  8842. if (!names.hasOwnProperty(name)) {
  8843. continue;
  8844. }
  8845. // We don't really use the JavaScript right now. This code is
  8846. // defensive so we don't cause errors on document load.
  8847. var jsDict = names[name];
  8848. if (!isDict(jsDict)) {
  8849. continue;
  8850. }
  8851. var type = jsDict.get('S');
  8852. if (!isName(type) || type.name !== 'JavaScript') {
  8853. continue;
  8854. }
  8855. var js = jsDict.get('JS');
  8856. if (!isString(js) && !isStream(js)) {
  8857. continue;
  8858. }
  8859. if (isStream(js)) {
  8860. js = bytesToString(js.getBytes());
  8861. }
  8862. javaScript.push(stringToPDFString(js));
  8863. }
  8864. }
  8865. // Append OpenAction actions to javaScript array
  8866. var openactionDict = this.catDict.get('OpenAction');
  8867. if (isDict(openactionDict)) {
  8868. var objType = openactionDict.get('Type');
  8869. var actionType = openactionDict.get('S');
  8870. var action = openactionDict.get('N');
  8871. var isPrintAction = (isName(objType) && objType.name === 'Action' &&
  8872. isName(actionType) && actionType.name === 'Named' &&
  8873. isName(action) && action.name === 'Print');
  8874. if (isPrintAction) {
  8875. javaScript.push('print(true);');
  8876. }
  8877. }
  8878. return shadow(this, 'javaScript', javaScript);
  8879. },
  8880. cleanup: function Catalog_cleanup() {
  8881. var promises = [];
  8882. this.fontCache.forEach(function (promise) {
  8883. promises.push(promise);
  8884. });
  8885. return Promise.all(promises).then(function (translatedFonts) {
  8886. for (var i = 0, ii = translatedFonts.length; i < ii; i++) {
  8887. var font = translatedFonts[i].dict;
  8888. delete font.translated;
  8889. }
  8890. this.fontCache.clear();
  8891. }.bind(this));
  8892. },
  8893. getPage: function Catalog_getPage(pageIndex) {
  8894. if (!(pageIndex in this.pagePromises)) {
  8895. this.pagePromises[pageIndex] = this.getPageDict(pageIndex).then(
  8896. function (a) {
  8897. var dict = a[0];
  8898. var ref = a[1];
  8899. return new Page(this.pdfManager, this.xref, pageIndex, dict, ref,
  8900. this.fontCache);
  8901. }.bind(this)
  8902. );
  8903. }
  8904. return this.pagePromises[pageIndex];
  8905. },
  8906. getPageDict: function Catalog_getPageDict(pageIndex) {
  8907. var capability = createPromiseCapability();
  8908. var nodesToVisit = [this.catDict.getRaw('Pages')];
  8909. var currentPageIndex = 0;
  8910. var xref = this.xref;
  8911. var checkAllKids = false;
  8912. function next() {
  8913. while (nodesToVisit.length) {
  8914. var currentNode = nodesToVisit.pop();
  8915. if (isRef(currentNode)) {
  8916. xref.fetchAsync(currentNode).then(function (obj) {
  8917. if (isDict(obj, 'Page') || (isDict(obj) && !obj.has('Kids'))) {
  8918. if (pageIndex === currentPageIndex) {
  8919. capability.resolve([obj, currentNode]);
  8920. } else {
  8921. currentPageIndex++;
  8922. next();
  8923. }
  8924. return;
  8925. }
  8926. nodesToVisit.push(obj);
  8927. next();
  8928. }, capability.reject);
  8929. return;
  8930. }
  8931. // Must be a child page dictionary.
  8932. assert(
  8933. isDict(currentNode),
  8934. 'page dictionary kid reference points to wrong type of object'
  8935. );
  8936. var count = currentNode.get('Count');
  8937. // If the current node doesn't have any children, avoid getting stuck
  8938. // in an empty node further down in the tree (see issue5644.pdf).
  8939. if (count === 0) {
  8940. checkAllKids = true;
  8941. }
  8942. // Skip nodes where the page can't be.
  8943. if (currentPageIndex + count <= pageIndex) {
  8944. currentPageIndex += count;
  8945. continue;
  8946. }
  8947. var kids = currentNode.get('Kids');
  8948. assert(isArray(kids), 'page dictionary kids object is not an array');
  8949. if (!checkAllKids && count === kids.length) {
  8950. // Nodes that don't have the page have been skipped and this is the
  8951. // bottom of the tree which means the page requested must be a
  8952. // descendant of this pages node. Ideally we would just resolve the
  8953. // promise with the page ref here, but there is the case where more
  8954. // pages nodes could link to single a page (see issue 3666 pdf). To
  8955. // handle this push it back on the queue so if it is a pages node it
  8956. // will be descended into.
  8957. nodesToVisit = [kids[pageIndex - currentPageIndex]];
  8958. currentPageIndex = pageIndex;
  8959. continue;
  8960. } else {
  8961. for (var last = kids.length - 1; last >= 0; last--) {
  8962. nodesToVisit.push(kids[last]);
  8963. }
  8964. }
  8965. }
  8966. capability.reject('Page index ' + pageIndex + ' not found.');
  8967. }
  8968. next();
  8969. return capability.promise;
  8970. },
  8971. getPageIndex: function Catalog_getPageIndex(ref) {
  8972. // The page tree nodes have the count of all the leaves below them. To get
  8973. // how many pages are before we just have to walk up the tree and keep
  8974. // adding the count of siblings to the left of the node.
  8975. var xref = this.xref;
  8976. function pagesBeforeRef(kidRef) {
  8977. var total = 0;
  8978. var parentRef;
  8979. return xref.fetchAsync(kidRef).then(function (node) {
  8980. if (!node) {
  8981. return null;
  8982. }
  8983. parentRef = node.getRaw('Parent');
  8984. return node.getAsync('Parent');
  8985. }).then(function (parent) {
  8986. if (!parent) {
  8987. return null;
  8988. }
  8989. return parent.getAsync('Kids');
  8990. }).then(function (kids) {
  8991. if (!kids) {
  8992. return null;
  8993. }
  8994. var kidPromises = [];
  8995. var found = false;
  8996. for (var i = 0; i < kids.length; i++) {
  8997. var kid = kids[i];
  8998. assert(isRef(kid), 'kids must be a ref');
  8999. if (kid.num === kidRef.num) {
  9000. found = true;
  9001. break;
  9002. }
  9003. kidPromises.push(xref.fetchAsync(kid).then(function (kid) {
  9004. if (kid.has('Count')) {
  9005. var count = kid.get('Count');
  9006. total += count;
  9007. } else { // page leaf node
  9008. total++;
  9009. }
  9010. }));
  9011. }
  9012. if (!found) {
  9013. error('kid ref not found in parents kids');
  9014. }
  9015. return Promise.all(kidPromises).then(function () {
  9016. return [total, parentRef];
  9017. });
  9018. });
  9019. }
  9020. var total = 0;
  9021. function next(ref) {
  9022. return pagesBeforeRef(ref).then(function (args) {
  9023. if (!args) {
  9024. return total;
  9025. }
  9026. var count = args[0];
  9027. var parentRef = args[1];
  9028. total += count;
  9029. return next(parentRef);
  9030. });
  9031. }
  9032. return next(ref);
  9033. }
  9034. };
  9035. return Catalog;
  9036. })();
  9037. var XRef = (function XRefClosure() {
  9038. function XRef(stream, password) {
  9039. this.stream = stream;
  9040. this.entries = [];
  9041. this.xrefstms = {};
  9042. // prepare the XRef cache
  9043. this.cache = [];
  9044. this.password = password;
  9045. this.stats = {
  9046. streamTypes: [],
  9047. fontTypes: []
  9048. };
  9049. }
  9050. XRef.prototype = {
  9051. setStartXRef: function XRef_setStartXRef(startXRef) {
  9052. // Store the starting positions of xref tables as we process them
  9053. // so we can recover from missing data errors
  9054. this.startXRefQueue = [startXRef];
  9055. },
  9056. parse: function XRef_parse(recoveryMode) {
  9057. var trailerDict;
  9058. if (!recoveryMode) {
  9059. trailerDict = this.readXRef();
  9060. } else {
  9061. warn('Indexing all PDF objects');
  9062. trailerDict = this.indexObjects();
  9063. }
  9064. trailerDict.assignXref(this);
  9065. this.trailer = trailerDict;
  9066. var encrypt = trailerDict.get('Encrypt');
  9067. if (encrypt) {
  9068. var ids = trailerDict.get('ID');
  9069. var fileId = (ids && ids.length) ? ids[0] : '';
  9070. this.encrypt = new CipherTransformFactory(encrypt, fileId,
  9071. this.password);
  9072. }
  9073. // get the root dictionary (catalog) object
  9074. if (!(this.root = trailerDict.get('Root'))) {
  9075. error('Invalid root reference');
  9076. }
  9077. },
  9078. processXRefTable: function XRef_processXRefTable(parser) {
  9079. if (!('tableState' in this)) {
  9080. // Stores state of the table as we process it so we can resume
  9081. // from middle of table in case of missing data error
  9082. this.tableState = {
  9083. entryNum: 0,
  9084. streamPos: parser.lexer.stream.pos,
  9085. parserBuf1: parser.buf1,
  9086. parserBuf2: parser.buf2
  9087. };
  9088. }
  9089. var obj = this.readXRefTable(parser);
  9090. // Sanity check
  9091. if (!isCmd(obj, 'trailer')) {
  9092. error('Invalid XRef table: could not find trailer dictionary');
  9093. }
  9094. // Read trailer dictionary, e.g.
  9095. // trailer
  9096. // << /Size 22
  9097. // /Root 20R
  9098. // /Info 10R
  9099. // /ID [ <81b14aafa313db63dbd6f981e49f94f4> ]
  9100. // >>
  9101. // The parser goes through the entire stream << ... >> and provides
  9102. // a getter interface for the key-value table
  9103. var dict = parser.getObj();
  9104. // The pdflib PDF generator can generate a nested trailer dictionary
  9105. if (!isDict(dict) && dict.dict) {
  9106. dict = dict.dict;
  9107. }
  9108. if (!isDict(dict)) {
  9109. error('Invalid XRef table: could not parse trailer dictionary');
  9110. }
  9111. delete this.tableState;
  9112. return dict;
  9113. },
  9114. readXRefTable: function XRef_readXRefTable(parser) {
  9115. // Example of cross-reference table:
  9116. // xref
  9117. // 0 1 <-- subsection header (first obj #, obj count)
  9118. // 0000000000 65535 f <-- actual object (offset, generation #, f/n)
  9119. // 23 2 <-- subsection header ... and so on ...
  9120. // 0000025518 00002 n
  9121. // 0000025635 00000 n
  9122. // trailer
  9123. // ...
  9124. var stream = parser.lexer.stream;
  9125. var tableState = this.tableState;
  9126. stream.pos = tableState.streamPos;
  9127. parser.buf1 = tableState.parserBuf1;
  9128. parser.buf2 = tableState.parserBuf2;
  9129. // Outer loop is over subsection headers
  9130. var obj;
  9131. while (true) {
  9132. if (!('firstEntryNum' in tableState) || !('entryCount' in tableState)) {
  9133. if (isCmd(obj = parser.getObj(), 'trailer')) {
  9134. break;
  9135. }
  9136. tableState.firstEntryNum = obj;
  9137. tableState.entryCount = parser.getObj();
  9138. }
  9139. var first = tableState.firstEntryNum;
  9140. var count = tableState.entryCount;
  9141. if (!isInt(first) || !isInt(count)) {
  9142. error('Invalid XRef table: wrong types in subsection header');
  9143. }
  9144. // Inner loop is over objects themselves
  9145. for (var i = tableState.entryNum; i < count; i++) {
  9146. tableState.streamPos = stream.pos;
  9147. tableState.entryNum = i;
  9148. tableState.parserBuf1 = parser.buf1;
  9149. tableState.parserBuf2 = parser.buf2;
  9150. var entry = {};
  9151. entry.offset = parser.getObj();
  9152. entry.gen = parser.getObj();
  9153. var type = parser.getObj();
  9154. if (isCmd(type, 'f')) {
  9155. entry.free = true;
  9156. } else if (isCmd(type, 'n')) {
  9157. entry.uncompressed = true;
  9158. }
  9159. // Validate entry obj
  9160. if (!isInt(entry.offset) || !isInt(entry.gen) ||
  9161. !(entry.free || entry.uncompressed)) {
  9162. error('Invalid entry in XRef subsection: ' + first + ', ' + count);
  9163. }
  9164. if (!this.entries[i + first]) {
  9165. this.entries[i + first] = entry;
  9166. }
  9167. }
  9168. tableState.entryNum = 0;
  9169. tableState.streamPos = stream.pos;
  9170. tableState.parserBuf1 = parser.buf1;
  9171. tableState.parserBuf2 = parser.buf2;
  9172. delete tableState.firstEntryNum;
  9173. delete tableState.entryCount;
  9174. }
  9175. // Per issue 3248: hp scanners generate bad XRef
  9176. if (first === 1 && this.entries[1] && this.entries[1].free) {
  9177. // shifting the entries
  9178. this.entries.shift();
  9179. }
  9180. // Sanity check: as per spec, first object must be free
  9181. if (this.entries[0] && !this.entries[0].free) {
  9182. error('Invalid XRef table: unexpected first object');
  9183. }
  9184. return obj;
  9185. },
  9186. processXRefStream: function XRef_processXRefStream(stream) {
  9187. if (!('streamState' in this)) {
  9188. // Stores state of the stream as we process it so we can resume
  9189. // from middle of stream in case of missing data error
  9190. var streamParameters = stream.dict;
  9191. var byteWidths = streamParameters.get('W');
  9192. var range = streamParameters.get('Index');
  9193. if (!range) {
  9194. range = [0, streamParameters.get('Size')];
  9195. }
  9196. this.streamState = {
  9197. entryRanges: range,
  9198. byteWidths: byteWidths,
  9199. entryNum: 0,
  9200. streamPos: stream.pos
  9201. };
  9202. }
  9203. this.readXRefStream(stream);
  9204. delete this.streamState;
  9205. return stream.dict;
  9206. },
  9207. readXRefStream: function XRef_readXRefStream(stream) {
  9208. var i, j;
  9209. var streamState = this.streamState;
  9210. stream.pos = streamState.streamPos;
  9211. var byteWidths = streamState.byteWidths;
  9212. var typeFieldWidth = byteWidths[0];
  9213. var offsetFieldWidth = byteWidths[1];
  9214. var generationFieldWidth = byteWidths[2];
  9215. var entryRanges = streamState.entryRanges;
  9216. while (entryRanges.length > 0) {
  9217. var first = entryRanges[0];
  9218. var n = entryRanges[1];
  9219. if (!isInt(first) || !isInt(n)) {
  9220. error('Invalid XRef range fields: ' + first + ', ' + n);
  9221. }
  9222. if (!isInt(typeFieldWidth) || !isInt(offsetFieldWidth) ||
  9223. !isInt(generationFieldWidth)) {
  9224. error('Invalid XRef entry fields length: ' + first + ', ' + n);
  9225. }
  9226. for (i = streamState.entryNum; i < n; ++i) {
  9227. streamState.entryNum = i;
  9228. streamState.streamPos = stream.pos;
  9229. var type = 0, offset = 0, generation = 0;
  9230. for (j = 0; j < typeFieldWidth; ++j) {
  9231. type = (type << 8) | stream.getByte();
  9232. }
  9233. // if type field is absent, its default value is 1
  9234. if (typeFieldWidth === 0) {
  9235. type = 1;
  9236. }
  9237. for (j = 0; j < offsetFieldWidth; ++j) {
  9238. offset = (offset << 8) | stream.getByte();
  9239. }
  9240. for (j = 0; j < generationFieldWidth; ++j) {
  9241. generation = (generation << 8) | stream.getByte();
  9242. }
  9243. var entry = {};
  9244. entry.offset = offset;
  9245. entry.gen = generation;
  9246. switch (type) {
  9247. case 0:
  9248. entry.free = true;
  9249. break;
  9250. case 1:
  9251. entry.uncompressed = true;
  9252. break;
  9253. case 2:
  9254. break;
  9255. default:
  9256. error('Invalid XRef entry type: ' + type);
  9257. }
  9258. if (!this.entries[first + i]) {
  9259. this.entries[first + i] = entry;
  9260. }
  9261. }
  9262. streamState.entryNum = 0;
  9263. streamState.streamPos = stream.pos;
  9264. entryRanges.splice(0, 2);
  9265. }
  9266. },
  9267. indexObjects: function XRef_indexObjects() {
  9268. // Simple scan through the PDF content to find objects,
  9269. // trailers and XRef streams.
  9270. function readToken(data, offset) {
  9271. var token = '', ch = data[offset];
  9272. while (ch !== 13 && ch !== 10) {
  9273. if (++offset >= data.length) {
  9274. break;
  9275. }
  9276. token += String.fromCharCode(ch);
  9277. ch = data[offset];
  9278. }
  9279. return token;
  9280. }
  9281. function skipUntil(data, offset, what) {
  9282. var length = what.length, dataLength = data.length;
  9283. var skipped = 0;
  9284. // finding byte sequence
  9285. while (offset < dataLength) {
  9286. var i = 0;
  9287. while (i < length && data[offset + i] === what[i]) {
  9288. ++i;
  9289. }
  9290. if (i >= length) {
  9291. break; // sequence found
  9292. }
  9293. offset++;
  9294. skipped++;
  9295. }
  9296. return skipped;
  9297. }
  9298. var trailerBytes = new Uint8Array([116, 114, 97, 105, 108, 101, 114]);
  9299. var startxrefBytes = new Uint8Array([115, 116, 97, 114, 116, 120, 114,
  9300. 101, 102]);
  9301. var endobjBytes = new Uint8Array([101, 110, 100, 111, 98, 106]);
  9302. var xrefBytes = new Uint8Array([47, 88, 82, 101, 102]);
  9303. var stream = this.stream;
  9304. stream.pos = 0;
  9305. var buffer = stream.getBytes();
  9306. var position = stream.start, length = buffer.length;
  9307. var trailers = [], xrefStms = [];
  9308. while (position < length) {
  9309. var ch = buffer[position];
  9310. if (ch === 32 || ch === 9 || ch === 13 || ch === 10) {
  9311. ++position;
  9312. continue;
  9313. }
  9314. if (ch === 37) { // %-comment
  9315. do {
  9316. ++position;
  9317. if (position >= length) {
  9318. break;
  9319. }
  9320. ch = buffer[position];
  9321. } while (ch !== 13 && ch !== 10);
  9322. continue;
  9323. }
  9324. var token = readToken(buffer, position);
  9325. var m;
  9326. if (token === 'xref') {
  9327. position += skipUntil(buffer, position, trailerBytes);
  9328. trailers.push(position);
  9329. position += skipUntil(buffer, position, startxrefBytes);
  9330. } else if ((m = /^(\d+)\s+(\d+)\s+obj\b/.exec(token))) {
  9331. if (typeof this.entries[m[1]] === 'undefined') {
  9332. this.entries[m[1]] = {
  9333. offset: position,
  9334. gen: m[2] | 0,
  9335. uncompressed: true
  9336. };
  9337. }
  9338. var contentLength = skipUntil(buffer, position, endobjBytes) + 7;
  9339. var content = buffer.subarray(position, position + contentLength);
  9340. // checking XRef stream suspect
  9341. // (it shall have '/XRef' and next char is not a letter)
  9342. var xrefTagOffset = skipUntil(content, 0, xrefBytes);
  9343. if (xrefTagOffset < contentLength &&
  9344. content[xrefTagOffset + 5] < 64) {
  9345. xrefStms.push(position);
  9346. this.xrefstms[position] = 1; // don't read it recursively
  9347. }
  9348. position += contentLength;
  9349. } else {
  9350. position += token.length + 1;
  9351. }
  9352. }
  9353. // reading XRef streams
  9354. var i, ii;
  9355. for (i = 0, ii = xrefStms.length; i < ii; ++i) {
  9356. this.startXRefQueue.push(xrefStms[i]);
  9357. this.readXRef(/* recoveryMode */ true);
  9358. }
  9359. // finding main trailer
  9360. var dict;
  9361. for (i = 0, ii = trailers.length; i < ii; ++i) {
  9362. stream.pos = trailers[i];
  9363. var parser = new Parser(new Lexer(stream), true, this);
  9364. var obj = parser.getObj();
  9365. if (!isCmd(obj, 'trailer')) {
  9366. continue;
  9367. }
  9368. // read the trailer dictionary
  9369. if (!isDict(dict = parser.getObj())) {
  9370. continue;
  9371. }
  9372. // taking the first one with 'ID'
  9373. if (dict.has('ID')) {
  9374. return dict;
  9375. }
  9376. }
  9377. // no tailer with 'ID', taking last one (if exists)
  9378. if (dict) {
  9379. return dict;
  9380. }
  9381. // nothing helps
  9382. // calling error() would reject worker with an UnknownErrorException.
  9383. throw new InvalidPDFException('Invalid PDF structure');
  9384. },
  9385. readXRef: function XRef_readXRef(recoveryMode) {
  9386. var stream = this.stream;
  9387. try {
  9388. while (this.startXRefQueue.length) {
  9389. var startXRef = this.startXRefQueue[0];
  9390. stream.pos = startXRef + stream.start;
  9391. var parser = new Parser(new Lexer(stream), true, this);
  9392. var obj = parser.getObj();
  9393. var dict;
  9394. // Get dictionary
  9395. if (isCmd(obj, 'xref')) {
  9396. // Parse end-of-file XRef
  9397. dict = this.processXRefTable(parser);
  9398. if (!this.topDict) {
  9399. this.topDict = dict;
  9400. }
  9401. // Recursively get other XRefs 'XRefStm', if any
  9402. obj = dict.get('XRefStm');
  9403. if (isInt(obj)) {
  9404. var pos = obj;
  9405. // ignore previously loaded xref streams
  9406. // (possible infinite recursion)
  9407. if (!(pos in this.xrefstms)) {
  9408. this.xrefstms[pos] = 1;
  9409. this.startXRefQueue.push(pos);
  9410. }
  9411. }
  9412. } else if (isInt(obj)) {
  9413. // Parse in-stream XRef
  9414. if (!isInt(parser.getObj()) ||
  9415. !isCmd(parser.getObj(), 'obj') ||
  9416. !isStream(obj = parser.getObj())) {
  9417. error('Invalid XRef stream');
  9418. }
  9419. dict = this.processXRefStream(obj);
  9420. if (!this.topDict) {
  9421. this.topDict = dict;
  9422. }
  9423. if (!dict) {
  9424. error('Failed to read XRef stream');
  9425. }
  9426. } else {
  9427. error('Invalid XRef stream header');
  9428. }
  9429. // Recursively get previous dictionary, if any
  9430. obj = dict.get('Prev');
  9431. if (isInt(obj)) {
  9432. this.startXRefQueue.push(obj);
  9433. } else if (isRef(obj)) {
  9434. // The spec says Prev must not be a reference, i.e. "/Prev NNN"
  9435. // This is a fallback for non-compliant PDFs, i.e. "/Prev NNN 0 R"
  9436. this.startXRefQueue.push(obj.num);
  9437. }
  9438. this.startXRefQueue.shift();
  9439. }
  9440. return this.topDict;
  9441. } catch (e) {
  9442. if (e instanceof MissingDataException) {
  9443. throw e;
  9444. }
  9445. info('(while reading XRef): ' + e);
  9446. }
  9447. if (recoveryMode) {
  9448. return;
  9449. }
  9450. throw new XRefParseException();
  9451. },
  9452. getEntry: function XRef_getEntry(i) {
  9453. var xrefEntry = this.entries[i];
  9454. if (xrefEntry && !xrefEntry.free && xrefEntry.offset) {
  9455. return xrefEntry;
  9456. }
  9457. return null;
  9458. },
  9459. fetchIfRef: function XRef_fetchIfRef(obj) {
  9460. if (!isRef(obj)) {
  9461. return obj;
  9462. }
  9463. return this.fetch(obj);
  9464. },
  9465. fetch: function XRef_fetch(ref, suppressEncryption) {
  9466. assert(isRef(ref), 'ref object is not a reference');
  9467. var num = ref.num;
  9468. if (num in this.cache) {
  9469. var cacheEntry = this.cache[num];
  9470. return cacheEntry;
  9471. }
  9472. var xrefEntry = this.getEntry(num);
  9473. // the referenced entry can be free
  9474. if (xrefEntry === null) {
  9475. return (this.cache[num] = null);
  9476. }
  9477. if (xrefEntry.uncompressed) {
  9478. xrefEntry = this.fetchUncompressed(ref, xrefEntry, suppressEncryption);
  9479. } else {
  9480. xrefEntry = this.fetchCompressed(xrefEntry, suppressEncryption);
  9481. }
  9482. if (isDict(xrefEntry)){
  9483. xrefEntry.objId = ref.toString();
  9484. } else if (isStream(xrefEntry)) {
  9485. xrefEntry.dict.objId = ref.toString();
  9486. }
  9487. return xrefEntry;
  9488. },
  9489. fetchUncompressed: function XRef_fetchUncompressed(ref, xrefEntry,
  9490. suppressEncryption) {
  9491. var gen = ref.gen;
  9492. var num = ref.num;
  9493. if (xrefEntry.gen !== gen) {
  9494. error('inconsistent generation in XRef');
  9495. }
  9496. var stream = this.stream.makeSubStream(xrefEntry.offset +
  9497. this.stream.start);
  9498. var parser = new Parser(new Lexer(stream), true, this);
  9499. var obj1 = parser.getObj();
  9500. var obj2 = parser.getObj();
  9501. var obj3 = parser.getObj();
  9502. if (!isInt(obj1) || parseInt(obj1, 10) !== num ||
  9503. !isInt(obj2) || parseInt(obj2, 10) !== gen ||
  9504. !isCmd(obj3)) {
  9505. error('bad XRef entry');
  9506. }
  9507. if (!isCmd(obj3, 'obj')) {
  9508. // some bad PDFs use "obj1234" and really mean 1234
  9509. if (obj3.cmd.indexOf('obj') === 0) {
  9510. num = parseInt(obj3.cmd.substring(3), 10);
  9511. if (!isNaN(num)) {
  9512. return num;
  9513. }
  9514. }
  9515. error('bad XRef entry');
  9516. }
  9517. if (this.encrypt && !suppressEncryption) {
  9518. xrefEntry = parser.getObj(this.encrypt.createCipherTransform(num, gen));
  9519. } else {
  9520. xrefEntry = parser.getObj();
  9521. }
  9522. if (!isStream(xrefEntry)) {
  9523. this.cache[num] = xrefEntry;
  9524. }
  9525. return xrefEntry;
  9526. },
  9527. fetchCompressed: function XRef_fetchCompressed(xrefEntry,
  9528. suppressEncryption) {
  9529. var tableOffset = xrefEntry.offset;
  9530. var stream = this.fetch(new Ref(tableOffset, 0));
  9531. if (!isStream(stream)) {
  9532. error('bad ObjStm stream');
  9533. }
  9534. var first = stream.dict.get('First');
  9535. var n = stream.dict.get('N');
  9536. if (!isInt(first) || !isInt(n)) {
  9537. error('invalid first and n parameters for ObjStm stream');
  9538. }
  9539. var parser = new Parser(new Lexer(stream), false, this);
  9540. parser.allowStreams = true;
  9541. var i, entries = [], num, nums = [];
  9542. // read the object numbers to populate cache
  9543. for (i = 0; i < n; ++i) {
  9544. num = parser.getObj();
  9545. if (!isInt(num)) {
  9546. error('invalid object number in the ObjStm stream: ' + num);
  9547. }
  9548. nums.push(num);
  9549. var offset = parser.getObj();
  9550. if (!isInt(offset)) {
  9551. error('invalid object offset in the ObjStm stream: ' + offset);
  9552. }
  9553. }
  9554. // read stream objects for cache
  9555. for (i = 0; i < n; ++i) {
  9556. entries.push(parser.getObj());
  9557. num = nums[i];
  9558. var entry = this.entries[num];
  9559. if (entry && entry.offset === tableOffset && entry.gen === i) {
  9560. this.cache[num] = entries[i];
  9561. }
  9562. }
  9563. xrefEntry = entries[xrefEntry.gen];
  9564. if (xrefEntry === undefined) {
  9565. error('bad XRef entry for compressed object');
  9566. }
  9567. return xrefEntry;
  9568. },
  9569. fetchIfRefAsync: function XRef_fetchIfRefAsync(obj) {
  9570. if (!isRef(obj)) {
  9571. return Promise.resolve(obj);
  9572. }
  9573. return this.fetchAsync(obj);
  9574. },
  9575. fetchAsync: function XRef_fetchAsync(ref, suppressEncryption) {
  9576. var streamManager = this.stream.manager;
  9577. var xref = this;
  9578. return new Promise(function tryFetch(resolve, reject) {
  9579. try {
  9580. resolve(xref.fetch(ref, suppressEncryption));
  9581. } catch (e) {
  9582. if (e instanceof MissingDataException) {
  9583. streamManager.requestRange(e.begin, e.end, function () {
  9584. tryFetch(resolve, reject);
  9585. });
  9586. return;
  9587. }
  9588. reject(e);
  9589. }
  9590. });
  9591. },
  9592. getCatalogObj: function XRef_getCatalogObj() {
  9593. return this.root;
  9594. }
  9595. };
  9596. return XRef;
  9597. })();
  9598. /**
  9599. * A NameTree is like a Dict but has some advantageous properties, see the
  9600. * spec (7.9.6) for more details.
  9601. * TODO: implement all the Dict functions and make this more efficent.
  9602. */
  9603. var NameTree = (function NameTreeClosure() {
  9604. function NameTree(root, xref) {
  9605. this.root = root;
  9606. this.xref = xref;
  9607. }
  9608. NameTree.prototype = {
  9609. getAll: function NameTree_getAll() {
  9610. var dict = {};
  9611. if (!this.root) {
  9612. return dict;
  9613. }
  9614. var xref = this.xref;
  9615. // reading name tree
  9616. var processed = new RefSet();
  9617. processed.put(this.root);
  9618. var queue = [this.root];
  9619. while (queue.length > 0) {
  9620. var i, n;
  9621. var obj = xref.fetchIfRef(queue.shift());
  9622. if (!isDict(obj)) {
  9623. continue;
  9624. }
  9625. if (obj.has('Kids')) {
  9626. var kids = obj.get('Kids');
  9627. for (i = 0, n = kids.length; i < n; i++) {
  9628. var kid = kids[i];
  9629. if (processed.has(kid)) {
  9630. error('invalid destinations');
  9631. }
  9632. queue.push(kid);
  9633. processed.put(kid);
  9634. }
  9635. continue;
  9636. }
  9637. var names = obj.get('Names');
  9638. if (names) {
  9639. for (i = 0, n = names.length; i < n; i += 2) {
  9640. dict[names[i]] = xref.fetchIfRef(names[i + 1]);
  9641. }
  9642. }
  9643. }
  9644. return dict;
  9645. },
  9646. get: function NameTree_get(destinationId) {
  9647. if (!this.root) {
  9648. return null;
  9649. }
  9650. var xref = this.xref;
  9651. var kidsOrNames = xref.fetchIfRef(this.root);
  9652. var loopCount = 0;
  9653. var MAX_NAMES_LEVELS = 10;
  9654. var l, r, m;
  9655. // Perform a binary search to quickly find the entry that
  9656. // contains the named destination we are looking for.
  9657. while (kidsOrNames.has('Kids')) {
  9658. loopCount++;
  9659. if (loopCount > MAX_NAMES_LEVELS) {
  9660. warn('Search depth limit for named destionations has been reached.');
  9661. return null;
  9662. }
  9663. var kids = kidsOrNames.get('Kids');
  9664. if (!isArray(kids)) {
  9665. return null;
  9666. }
  9667. l = 0;
  9668. r = kids.length - 1;
  9669. while (l <= r) {
  9670. m = (l + r) >> 1;
  9671. var kid = xref.fetchIfRef(kids[m]);
  9672. var limits = kid.get('Limits');
  9673. if (destinationId < limits[0]) {
  9674. r = m - 1;
  9675. } else if (destinationId > limits[1]) {
  9676. l = m + 1;
  9677. } else {
  9678. kidsOrNames = xref.fetchIfRef(kids[m]);
  9679. break;
  9680. }
  9681. }
  9682. if (l > r) {
  9683. return null;
  9684. }
  9685. }
  9686. // If we get here, then we have found the right entry. Now
  9687. // go through the named destinations in the Named dictionary
  9688. // until we find the exact destination we're looking for.
  9689. var names = kidsOrNames.get('Names');
  9690. if (isArray(names)) {
  9691. // Perform a binary search to reduce the lookup time.
  9692. l = 0;
  9693. r = names.length - 2;
  9694. while (l <= r) {
  9695. // Check only even indices (0, 2, 4, ...) because the
  9696. // odd indices contain the actual D array.
  9697. m = (l + r) & ~1;
  9698. if (destinationId < names[m]) {
  9699. r = m - 2;
  9700. } else if (destinationId > names[m]) {
  9701. l = m + 2;
  9702. } else {
  9703. return xref.fetchIfRef(names[m + 1]);
  9704. }
  9705. }
  9706. }
  9707. return null;
  9708. }
  9709. };
  9710. return NameTree;
  9711. })();
  9712. /**
  9713. * "A PDF file can refer to the contents of another file by using a File
  9714. * Specification (PDF 1.1)", see the spec (7.11) for more details.
  9715. * NOTE: Only embedded files are supported (as part of the attachments support)
  9716. * TODO: support the 'URL' file system (with caching if !/V), portable
  9717. * collections attributes and related files (/RF)
  9718. */
  9719. var FileSpec = (function FileSpecClosure() {
  9720. function FileSpec(root, xref) {
  9721. if (!root || !isDict(root)) {
  9722. return;
  9723. }
  9724. this.xref = xref;
  9725. this.root = root;
  9726. if (root.has('FS')) {
  9727. this.fs = root.get('FS');
  9728. }
  9729. this.description = root.has('Desc') ?
  9730. stringToPDFString(root.get('Desc')) :
  9731. '';
  9732. if (root.has('RF')) {
  9733. warn('Related file specifications are not supported');
  9734. }
  9735. this.contentAvailable = true;
  9736. if (!root.has('EF')) {
  9737. this.contentAvailable = false;
  9738. warn('Non-embedded file specifications are not supported');
  9739. }
  9740. }
  9741. function pickPlatformItem(dict) {
  9742. // Look for the filename in this order:
  9743. // UF, F, Unix, Mac, DOS
  9744. if (dict.has('UF')) {
  9745. return dict.get('UF');
  9746. } else if (dict.has('F')) {
  9747. return dict.get('F');
  9748. } else if (dict.has('Unix')) {
  9749. return dict.get('Unix');
  9750. } else if (dict.has('Mac')) {
  9751. return dict.get('Mac');
  9752. } else if (dict.has('DOS')) {
  9753. return dict.get('DOS');
  9754. } else {
  9755. return null;
  9756. }
  9757. }
  9758. FileSpec.prototype = {
  9759. get filename() {
  9760. if (!this._filename && this.root) {
  9761. var filename = pickPlatformItem(this.root) || 'unnamed';
  9762. this._filename = stringToPDFString(filename).
  9763. replace(/\\\\/g, '\\').
  9764. replace(/\\\//g, '/').
  9765. replace(/\\/g, '/');
  9766. }
  9767. return this._filename;
  9768. },
  9769. get content() {
  9770. if (!this.contentAvailable) {
  9771. return null;
  9772. }
  9773. if (!this.contentRef && this.root) {
  9774. this.contentRef = pickPlatformItem(this.root.get('EF'));
  9775. }
  9776. var content = null;
  9777. if (this.contentRef) {
  9778. var xref = this.xref;
  9779. var fileObj = xref.fetchIfRef(this.contentRef);
  9780. if (fileObj && isStream(fileObj)) {
  9781. content = fileObj.getBytes();
  9782. } else {
  9783. warn('Embedded file specification points to non-existing/invalid ' +
  9784. 'content');
  9785. }
  9786. } else {
  9787. warn('Embedded file specification does not have a content');
  9788. }
  9789. return content;
  9790. },
  9791. get serializable() {
  9792. return {
  9793. filename: this.filename,
  9794. content: this.content
  9795. };
  9796. }
  9797. };
  9798. return FileSpec;
  9799. })();
  9800. /**
  9801. * A helper for loading missing data in object graphs. It traverses the graph
  9802. * depth first and queues up any objects that have missing data. Once it has
  9803. * has traversed as many objects that are available it attempts to bundle the
  9804. * missing data requests and then resume from the nodes that weren't ready.
  9805. *
  9806. * NOTE: It provides protection from circular references by keeping track of
  9807. * of loaded references. However, you must be careful not to load any graphs
  9808. * that have references to the catalog or other pages since that will cause the
  9809. * entire PDF document object graph to be traversed.
  9810. */
  9811. var ObjectLoader = (function() {
  9812. function mayHaveChildren(value) {
  9813. return isRef(value) || isDict(value) || isArray(value) || isStream(value);
  9814. }
  9815. function addChildren(node, nodesToVisit) {
  9816. var value;
  9817. if (isDict(node) || isStream(node)) {
  9818. var map;
  9819. if (isDict(node)) {
  9820. map = node.map;
  9821. } else {
  9822. map = node.dict.map;
  9823. }
  9824. for (var key in map) {
  9825. value = map[key];
  9826. if (mayHaveChildren(value)) {
  9827. nodesToVisit.push(value);
  9828. }
  9829. }
  9830. } else if (isArray(node)) {
  9831. for (var i = 0, ii = node.length; i < ii; i++) {
  9832. value = node[i];
  9833. if (mayHaveChildren(value)) {
  9834. nodesToVisit.push(value);
  9835. }
  9836. }
  9837. }
  9838. }
  9839. function ObjectLoader(obj, keys, xref) {
  9840. this.obj = obj;
  9841. this.keys = keys;
  9842. this.xref = xref;
  9843. this.refSet = null;
  9844. }
  9845. ObjectLoader.prototype = {
  9846. load: function ObjectLoader_load() {
  9847. var keys = this.keys;
  9848. this.capability = createPromiseCapability();
  9849. // Don't walk the graph if all the data is already loaded.
  9850. if (!(this.xref.stream instanceof ChunkedStream) ||
  9851. this.xref.stream.getMissingChunks().length === 0) {
  9852. this.capability.resolve();
  9853. return this.capability.promise;
  9854. }
  9855. this.refSet = new RefSet();
  9856. // Setup the initial nodes to visit.
  9857. var nodesToVisit = [];
  9858. for (var i = 0; i < keys.length; i++) {
  9859. nodesToVisit.push(this.obj[keys[i]]);
  9860. }
  9861. this.walk(nodesToVisit);
  9862. return this.capability.promise;
  9863. },
  9864. walk: function ObjectLoader_walk(nodesToVisit) {
  9865. var nodesToRevisit = [];
  9866. var pendingRequests = [];
  9867. // DFS walk of the object graph.
  9868. while (nodesToVisit.length) {
  9869. var currentNode = nodesToVisit.pop();
  9870. // Only references or chunked streams can cause missing data exceptions.
  9871. if (isRef(currentNode)) {
  9872. // Skip nodes that have already been visited.
  9873. if (this.refSet.has(currentNode)) {
  9874. continue;
  9875. }
  9876. try {
  9877. var ref = currentNode;
  9878. this.refSet.put(ref);
  9879. currentNode = this.xref.fetch(currentNode);
  9880. } catch (e) {
  9881. if (!(e instanceof MissingDataException)) {
  9882. throw e;
  9883. }
  9884. nodesToRevisit.push(currentNode);
  9885. pendingRequests.push({ begin: e.begin, end: e.end });
  9886. }
  9887. }
  9888. if (currentNode && currentNode.getBaseStreams) {
  9889. var baseStreams = currentNode.getBaseStreams();
  9890. var foundMissingData = false;
  9891. for (var i = 0; i < baseStreams.length; i++) {
  9892. var stream = baseStreams[i];
  9893. if (stream.getMissingChunks && stream.getMissingChunks().length) {
  9894. foundMissingData = true;
  9895. pendingRequests.push({
  9896. begin: stream.start,
  9897. end: stream.end
  9898. });
  9899. }
  9900. }
  9901. if (foundMissingData) {
  9902. nodesToRevisit.push(currentNode);
  9903. }
  9904. }
  9905. addChildren(currentNode, nodesToVisit);
  9906. }
  9907. if (pendingRequests.length) {
  9908. this.xref.stream.manager.requestRanges(pendingRequests,
  9909. function pendingRequestCallback() {
  9910. nodesToVisit = nodesToRevisit;
  9911. for (var i = 0; i < nodesToRevisit.length; i++) {
  9912. var node = nodesToRevisit[i];
  9913. // Remove any reference nodes from the currrent refset so they
  9914. // aren't skipped when we revist them.
  9915. if (isRef(node)) {
  9916. this.refSet.remove(node);
  9917. }
  9918. }
  9919. this.walk(nodesToVisit);
  9920. }.bind(this));
  9921. return;
  9922. }
  9923. // Everything is loaded.
  9924. this.refSet = null;
  9925. this.capability.resolve();
  9926. }
  9927. };
  9928. return ObjectLoader;
  9929. })();
  9930. var ISOAdobeCharset = [
  9931. '.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar',
  9932. 'percent', 'ampersand', 'quoteright', 'parenleft', 'parenright',
  9933. 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero',
  9934. 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
  9935. 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question',
  9936. 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
  9937. 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  9938. 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore',
  9939. 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
  9940. 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
  9941. 'braceleft', 'bar', 'braceright', 'asciitilde', 'exclamdown', 'cent',
  9942. 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency',
  9943. 'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft',
  9944. 'guilsinglright', 'fi', 'fl', 'endash', 'dagger', 'daggerdbl',
  9945. 'periodcentered', 'paragraph', 'bullet', 'quotesinglbase',
  9946. 'quotedblbase', 'quotedblright', 'guillemotright', 'ellipsis',
  9947. 'perthousand', 'questiondown', 'grave', 'acute', 'circumflex', 'tilde',
  9948. 'macron', 'breve', 'dotaccent', 'dieresis', 'ring', 'cedilla',
  9949. 'hungarumlaut', 'ogonek', 'caron', 'emdash', 'AE', 'ordfeminine',
  9950. 'Lslash', 'Oslash', 'OE', 'ordmasculine', 'ae', 'dotlessi', 'lslash',
  9951. 'oslash', 'oe', 'germandbls', 'onesuperior', 'logicalnot', 'mu',
  9952. 'trademark', 'Eth', 'onehalf', 'plusminus', 'Thorn', 'onequarter',
  9953. 'divide', 'brokenbar', 'degree', 'thorn', 'threequarters', 'twosuperior',
  9954. 'registered', 'minus', 'eth', 'multiply', 'threesuperior', 'copyright',
  9955. 'Aacute', 'Acircumflex', 'Adieresis', 'Agrave', 'Aring', 'Atilde',
  9956. 'Ccedilla', 'Eacute', 'Ecircumflex', 'Edieresis', 'Egrave', 'Iacute',
  9957. 'Icircumflex', 'Idieresis', 'Igrave', 'Ntilde', 'Oacute', 'Ocircumflex',
  9958. 'Odieresis', 'Ograve', 'Otilde', 'Scaron', 'Uacute', 'Ucircumflex',
  9959. 'Udieresis', 'Ugrave', 'Yacute', 'Ydieresis', 'Zcaron', 'aacute',
  9960. 'acircumflex', 'adieresis', 'agrave', 'aring', 'atilde', 'ccedilla',
  9961. 'eacute', 'ecircumflex', 'edieresis', 'egrave', 'iacute', 'icircumflex',
  9962. 'idieresis', 'igrave', 'ntilde', 'oacute', 'ocircumflex', 'odieresis',
  9963. 'ograve', 'otilde', 'scaron', 'uacute', 'ucircumflex', 'udieresis',
  9964. 'ugrave', 'yacute', 'ydieresis', 'zcaron'
  9965. ];
  9966. var ExpertCharset = [
  9967. '.notdef', 'space', 'exclamsmall', 'Hungarumlautsmall', 'dollaroldstyle',
  9968. 'dollarsuperior', 'ampersandsmall', 'Acutesmall', 'parenleftsuperior',
  9969. 'parenrightsuperior', 'twodotenleader', 'onedotenleader', 'comma',
  9970. 'hyphen', 'period', 'fraction', 'zerooldstyle', 'oneoldstyle',
  9971. 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle',
  9972. 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle',
  9973. 'colon', 'semicolon', 'commasuperior', 'threequartersemdash',
  9974. 'periodsuperior', 'questionsmall', 'asuperior', 'bsuperior',
  9975. 'centsuperior', 'dsuperior', 'esuperior', 'isuperior', 'lsuperior',
  9976. 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior',
  9977. 'tsuperior', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior',
  9978. 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall',
  9979. 'Asmall', 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall',
  9980. 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall',
  9981. 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall',
  9982. 'Vsmall', 'Wsmall', 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary',
  9983. 'onefitted', 'rupiah', 'Tildesmall', 'exclamdownsmall', 'centoldstyle',
  9984. 'Lslashsmall', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall',
  9985. 'Brevesmall', 'Caronsmall', 'Dotaccentsmall', 'Macronsmall',
  9986. 'figuredash', 'hypheninferior', 'Ogoneksmall', 'Ringsmall',
  9987. 'Cedillasmall', 'onequarter', 'onehalf', 'threequarters',
  9988. 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths',
  9989. 'seveneighths', 'onethird', 'twothirds', 'zerosuperior', 'onesuperior',
  9990. 'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior',
  9991. 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior',
  9992. 'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior',
  9993. 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior',
  9994. 'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior',
  9995. 'periodinferior', 'commainferior', 'Agravesmall', 'Aacutesmall',
  9996. 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall', 'Aringsmall',
  9997. 'AEsmall', 'Ccedillasmall', 'Egravesmall', 'Eacutesmall',
  9998. 'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall',
  9999. 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall',
  10000. 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall',
  10001. 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall',
  10002. 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall',
  10003. 'Ydieresissmall'
  10004. ];
  10005. var ExpertSubsetCharset = [
  10006. '.notdef', 'space', 'dollaroldstyle', 'dollarsuperior',
  10007. 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader',
  10008. 'onedotenleader', 'comma', 'hyphen', 'period', 'fraction',
  10009. 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle',
  10010. 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle',
  10011. 'eightoldstyle', 'nineoldstyle', 'colon', 'semicolon', 'commasuperior',
  10012. 'threequartersemdash', 'periodsuperior', 'asuperior', 'bsuperior',
  10013. 'centsuperior', 'dsuperior', 'esuperior', 'isuperior', 'lsuperior',
  10014. 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior',
  10015. 'tsuperior', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior',
  10016. 'parenrightinferior', 'hyphensuperior', 'colonmonetary', 'onefitted',
  10017. 'rupiah', 'centoldstyle', 'figuredash', 'hypheninferior', 'onequarter',
  10018. 'onehalf', 'threequarters', 'oneeighth', 'threeeighths', 'fiveeighths',
  10019. 'seveneighths', 'onethird', 'twothirds', 'zerosuperior', 'onesuperior',
  10020. 'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior',
  10021. 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior',
  10022. 'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior',
  10023. 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior',
  10024. 'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior',
  10025. 'periodinferior', 'commainferior'
  10026. ];
  10027. var DEFAULT_ICON_SIZE = 22; // px
  10028. var SUPPORTED_TYPES = ['Link', 'Text', 'Widget'];
  10029. var Annotation = (function AnnotationClosure() {
  10030. // 12.5.5: Algorithm: Appearance streams
  10031. function getTransformMatrix(rect, bbox, matrix) {
  10032. var bounds = Util.getAxialAlignedBoundingBox(bbox, matrix);
  10033. var minX = bounds[0];
  10034. var minY = bounds[1];
  10035. var maxX = bounds[2];
  10036. var maxY = bounds[3];
  10037. if (minX === maxX || minY === maxY) {
  10038. // From real-life file, bbox was [0, 0, 0, 0]. In this case,
  10039. // just apply the transform for rect
  10040. return [1, 0, 0, 1, rect[0], rect[1]];
  10041. }
  10042. var xRatio = (rect[2] - rect[0]) / (maxX - minX);
  10043. var yRatio = (rect[3] - rect[1]) / (maxY - minY);
  10044. return [
  10045. xRatio,
  10046. 0,
  10047. 0,
  10048. yRatio,
  10049. rect[0] - minX * xRatio,
  10050. rect[1] - minY * yRatio
  10051. ];
  10052. }
  10053. function getDefaultAppearance(dict) {
  10054. var appearanceState = dict.get('AP');
  10055. if (!isDict(appearanceState)) {
  10056. return;
  10057. }
  10058. var appearance;
  10059. var appearances = appearanceState.get('N');
  10060. if (isDict(appearances)) {
  10061. var as = dict.get('AS');
  10062. if (as && appearances.has(as.name)) {
  10063. appearance = appearances.get(as.name);
  10064. }
  10065. } else {
  10066. appearance = appearances;
  10067. }
  10068. return appearance;
  10069. }
  10070. function Annotation(params) {
  10071. var dict = params.dict;
  10072. var data = this.data = {};
  10073. data.subtype = dict.get('Subtype').name;
  10074. var rect = dict.get('Rect') || [0, 0, 0, 0];
  10075. data.rect = Util.normalizeRect(rect);
  10076. data.annotationFlags = dict.get('F');
  10077. var color = dict.get('C');
  10078. if (!color) {
  10079. // The PDF spec does not mention how a missing color array is interpreted.
  10080. // Adobe Reader seems to default to black in this case.
  10081. data.color = [0, 0, 0];
  10082. } else if (isArray(color)) {
  10083. switch (color.length) {
  10084. case 0:
  10085. // Empty array denotes transparent border.
  10086. data.color = null;
  10087. break;
  10088. case 1:
  10089. // TODO: implement DeviceGray
  10090. break;
  10091. case 3:
  10092. data.color = color;
  10093. break;
  10094. case 4:
  10095. // TODO: implement DeviceCMYK
  10096. break;
  10097. }
  10098. }
  10099. // Some types of annotations have border style dict which has more
  10100. // info than the border array
  10101. if (dict.has('BS')) {
  10102. var borderStyle = dict.get('BS');
  10103. data.borderWidth = borderStyle.has('W') ? borderStyle.get('W') : 1;
  10104. } else {
  10105. var borderArray = dict.get('Border') || [0, 0, 1];
  10106. data.borderWidth = borderArray[2] || 0;
  10107. // TODO: implement proper support for annotations with line dash patterns.
  10108. var dashArray = borderArray[3];
  10109. if (data.borderWidth > 0 && dashArray) {
  10110. if (!isArray(dashArray)) {
  10111. // Ignore the border if dashArray is not actually an array,
  10112. // this is consistent with the behaviour in Adobe Reader.
  10113. data.borderWidth = 0;
  10114. } else {
  10115. var dashArrayLength = dashArray.length;
  10116. if (dashArrayLength > 0) {
  10117. // According to the PDF specification: the elements in a dashArray
  10118. // shall be numbers that are nonnegative and not all equal to zero.
  10119. var isInvalid = false;
  10120. var numPositive = 0;
  10121. for (var i = 0; i < dashArrayLength; i++) {
  10122. var validNumber = (+dashArray[i] >= 0);
  10123. if (!validNumber) {
  10124. isInvalid = true;
  10125. break;
  10126. } else if (dashArray[i] > 0) {
  10127. numPositive++;
  10128. }
  10129. }
  10130. if (isInvalid || numPositive === 0) {
  10131. data.borderWidth = 0;
  10132. }
  10133. }
  10134. }
  10135. }
  10136. }
  10137. this.appearance = getDefaultAppearance(dict);
  10138. data.hasAppearance = !!this.appearance;
  10139. data.id = params.ref.num;
  10140. }
  10141. Annotation.prototype = {
  10142. getData: function Annotation_getData() {
  10143. return this.data;
  10144. },
  10145. isInvisible: function Annotation_isInvisible() {
  10146. var data = this.data;
  10147. if (data && SUPPORTED_TYPES.indexOf(data.subtype) !== -1) {
  10148. return false;
  10149. } else {
  10150. return !!(data &&
  10151. data.annotationFlags && // Default: not invisible
  10152. data.annotationFlags & 0x1); // Invisible
  10153. }
  10154. },
  10155. isViewable: function Annotation_isViewable() {
  10156. var data = this.data;
  10157. return !!(!this.isInvisible() &&
  10158. data &&
  10159. (!data.annotationFlags ||
  10160. !(data.annotationFlags & 0x22)) && // Hidden or NoView
  10161. data.rect); // rectangle is necessary
  10162. },
  10163. isPrintable: function Annotation_isPrintable() {
  10164. var data = this.data;
  10165. return !!(!this.isInvisible() &&
  10166. data &&
  10167. data.annotationFlags && // Default: not printable
  10168. data.annotationFlags & 0x4 && // Print
  10169. !(data.annotationFlags & 0x2) && // Hidden
  10170. data.rect); // rectangle is necessary
  10171. },
  10172. loadResources: function Annotation_loadResources(keys) {
  10173. return new Promise(function (resolve, reject) {
  10174. this.appearance.dict.getAsync('Resources').then(function (resources) {
  10175. if (!resources) {
  10176. resolve();
  10177. return;
  10178. }
  10179. var objectLoader = new ObjectLoader(resources.map,
  10180. keys,
  10181. resources.xref);
  10182. objectLoader.load().then(function() {
  10183. resolve(resources);
  10184. }, reject);
  10185. }, reject);
  10186. }.bind(this));
  10187. },
  10188. getOperatorList: function Annotation_getOperatorList(evaluator) {
  10189. if (!this.appearance) {
  10190. return Promise.resolve(new OperatorList());
  10191. }
  10192. var data = this.data;
  10193. var appearanceDict = this.appearance.dict;
  10194. var resourcesPromise = this.loadResources([
  10195. 'ExtGState',
  10196. 'ColorSpace',
  10197. 'Pattern',
  10198. 'Shading',
  10199. 'XObject',
  10200. 'Font'
  10201. // ProcSet
  10202. // Properties
  10203. ]);
  10204. var bbox = appearanceDict.get('BBox') || [0, 0, 1, 1];
  10205. var matrix = appearanceDict.get('Matrix') || [1, 0, 0, 1, 0 ,0];
  10206. var transform = getTransformMatrix(data.rect, bbox, matrix);
  10207. var self = this;
  10208. return resourcesPromise.then(function(resources) {
  10209. var opList = new OperatorList();
  10210. opList.addOp(OPS.beginAnnotation, [data.rect, transform, matrix]);
  10211. return evaluator.getOperatorList(self.appearance, resources, opList).
  10212. then(function () {
  10213. opList.addOp(OPS.endAnnotation, []);
  10214. self.appearance.reset();
  10215. return opList;
  10216. });
  10217. });
  10218. }
  10219. };
  10220. Annotation.getConstructor =
  10221. function Annotation_getConstructor(subtype, fieldType) {
  10222. if (!subtype) {
  10223. return;
  10224. }
  10225. // TODO(mack): Implement FreeText annotations
  10226. if (subtype === 'Link') {
  10227. return LinkAnnotation;
  10228. } else if (subtype === 'Text') {
  10229. return TextAnnotation;
  10230. } else if (subtype === 'Widget') {
  10231. if (!fieldType) {
  10232. return;
  10233. }
  10234. if (fieldType === 'Tx') {
  10235. return TextWidgetAnnotation;
  10236. } else {
  10237. return WidgetAnnotation;
  10238. }
  10239. } else {
  10240. return Annotation;
  10241. }
  10242. };
  10243. Annotation.fromRef = function Annotation_fromRef(xref, ref) {
  10244. var dict = xref.fetchIfRef(ref);
  10245. if (!isDict(dict)) {
  10246. return;
  10247. }
  10248. var subtype = dict.get('Subtype');
  10249. subtype = isName(subtype) ? subtype.name : '';
  10250. if (!subtype) {
  10251. return;
  10252. }
  10253. var fieldType = Util.getInheritableProperty(dict, 'FT');
  10254. fieldType = isName(fieldType) ? fieldType.name : '';
  10255. var Constructor = Annotation.getConstructor(subtype, fieldType);
  10256. if (!Constructor) {
  10257. return;
  10258. }
  10259. var params = {
  10260. dict: dict,
  10261. ref: ref,
  10262. };
  10263. var annotation = new Constructor(params);
  10264. if (annotation.isViewable() || annotation.isPrintable()) {
  10265. return annotation;
  10266. } else {
  10267. if (SUPPORTED_TYPES.indexOf(subtype) === -1) {
  10268. warn('unimplemented annotation type: ' + subtype);
  10269. }
  10270. }
  10271. };
  10272. Annotation.appendToOperatorList = function Annotation_appendToOperatorList(
  10273. annotations, opList, pdfManager, partialEvaluator, intent) {
  10274. function reject(e) {
  10275. annotationsReadyCapability.reject(e);
  10276. }
  10277. var annotationsReadyCapability = createPromiseCapability();
  10278. var annotationPromises = [];
  10279. for (var i = 0, n = annotations.length; i < n; ++i) {
  10280. if (intent === 'display' && annotations[i].isViewable() ||
  10281. intent === 'print' && annotations[i].isPrintable()) {
  10282. annotationPromises.push(
  10283. annotations[i].getOperatorList(partialEvaluator));
  10284. }
  10285. }
  10286. Promise.all(annotationPromises).then(function(datas) {
  10287. opList.addOp(OPS.beginAnnotations, []);
  10288. for (var i = 0, n = datas.length; i < n; ++i) {
  10289. var annotOpList = datas[i];
  10290. opList.addOpList(annotOpList);
  10291. }
  10292. opList.addOp(OPS.endAnnotations, []);
  10293. annotationsReadyCapability.resolve();
  10294. }, reject);
  10295. return annotationsReadyCapability.promise;
  10296. };
  10297. return Annotation;
  10298. })();
  10299. var WidgetAnnotation = (function WidgetAnnotationClosure() {
  10300. function WidgetAnnotation(params) {
  10301. Annotation.call(this, params);
  10302. var dict = params.dict;
  10303. var data = this.data;
  10304. data.fieldValue = stringToPDFString(
  10305. Util.getInheritableProperty(dict, 'V') || '');
  10306. data.alternativeText = stringToPDFString(dict.get('TU') || '');
  10307. data.defaultAppearance = Util.getInheritableProperty(dict, 'DA') || '';
  10308. var fieldType = Util.getInheritableProperty(dict, 'FT');
  10309. data.fieldType = isName(fieldType) ? fieldType.name : '';
  10310. data.fieldFlags = Util.getInheritableProperty(dict, 'Ff') || 0;
  10311. this.fieldResources = Util.getInheritableProperty(dict, 'DR') || Dict.empty;
  10312. // Building the full field name by collecting the field and
  10313. // its ancestors 'T' data and joining them using '.'.
  10314. var fieldName = [];
  10315. var namedItem = dict;
  10316. var ref = params.ref;
  10317. while (namedItem) {
  10318. var parent = namedItem.get('Parent');
  10319. var parentRef = namedItem.getRaw('Parent');
  10320. var name = namedItem.get('T');
  10321. if (name) {
  10322. fieldName.unshift(stringToPDFString(name));
  10323. } else if (parent && ref) {
  10324. // The field name is absent, that means more than one field
  10325. // with the same name may exist. Replacing the empty name
  10326. // with the '`' plus index in the parent's 'Kids' array.
  10327. // This is not in the PDF spec but necessary to id the
  10328. // the input controls.
  10329. var kids = parent.get('Kids');
  10330. var j, jj;
  10331. for (j = 0, jj = kids.length; j < jj; j++) {
  10332. var kidRef = kids[j];
  10333. if (kidRef.num === ref.num && kidRef.gen === ref.gen) {
  10334. break;
  10335. }
  10336. }
  10337. fieldName.unshift('`' + j);
  10338. }
  10339. namedItem = parent;
  10340. ref = parentRef;
  10341. }
  10342. data.fullName = fieldName.join('.');
  10343. }
  10344. var parent = Annotation.prototype;
  10345. Util.inherit(WidgetAnnotation, Annotation, {
  10346. isViewable: function WidgetAnnotation_isViewable() {
  10347. if (this.data.fieldType === 'Sig') {
  10348. warn('unimplemented annotation type: Widget signature');
  10349. return false;
  10350. }
  10351. return parent.isViewable.call(this);
  10352. }
  10353. });
  10354. return WidgetAnnotation;
  10355. })();
  10356. var TextWidgetAnnotation = (function TextWidgetAnnotationClosure() {
  10357. function TextWidgetAnnotation(params) {
  10358. WidgetAnnotation.call(this, params);
  10359. this.data.textAlignment = Util.getInheritableProperty(params.dict, 'Q');
  10360. this.data.annotationType = AnnotationType.WIDGET;
  10361. this.data.hasHtml = !this.data.hasAppearance && !!this.data.fieldValue;
  10362. }
  10363. Util.inherit(TextWidgetAnnotation, WidgetAnnotation, {
  10364. getOperatorList: function TextWidgetAnnotation_getOperatorList(evaluator) {
  10365. if (this.appearance) {
  10366. return Annotation.prototype.getOperatorList.call(this, evaluator);
  10367. }
  10368. var opList = new OperatorList();
  10369. var data = this.data;
  10370. // Even if there is an appearance stream, ignore it. This is the
  10371. // behaviour used by Adobe Reader.
  10372. if (!data.defaultAppearance) {
  10373. return Promise.resolve(opList);
  10374. }
  10375. var stream = new Stream(stringToBytes(data.defaultAppearance));
  10376. return evaluator.getOperatorList(stream, this.fieldResources, opList).
  10377. then(function () {
  10378. return opList;
  10379. });
  10380. }
  10381. });
  10382. return TextWidgetAnnotation;
  10383. })();
  10384. var InteractiveAnnotation = (function InteractiveAnnotationClosure() {
  10385. function InteractiveAnnotation(params) {
  10386. Annotation.call(this, params);
  10387. this.data.hasHtml = true;
  10388. }
  10389. Util.inherit(InteractiveAnnotation, Annotation, { });
  10390. return InteractiveAnnotation;
  10391. })();
  10392. var TextAnnotation = (function TextAnnotationClosure() {
  10393. function TextAnnotation(params) {
  10394. InteractiveAnnotation.call(this, params);
  10395. var dict = params.dict;
  10396. var data = this.data;
  10397. var content = dict.get('Contents');
  10398. var title = dict.get('T');
  10399. data.annotationType = AnnotationType.TEXT;
  10400. data.content = stringToPDFString(content || '');
  10401. data.title = stringToPDFString(title || '');
  10402. if (data.hasAppearance) {
  10403. data.name = 'NoIcon';
  10404. } else {
  10405. data.rect[1] = data.rect[3] - DEFAULT_ICON_SIZE;
  10406. data.rect[2] = data.rect[0] + DEFAULT_ICON_SIZE;
  10407. data.name = dict.has('Name') ? dict.get('Name').name : 'Note';
  10408. }
  10409. if (dict.has('C')) {
  10410. data.hasBgColor = true;
  10411. }
  10412. }
  10413. Util.inherit(TextAnnotation, InteractiveAnnotation, { });
  10414. return TextAnnotation;
  10415. })();
  10416. var LinkAnnotation = (function LinkAnnotationClosure() {
  10417. function LinkAnnotation(params) {
  10418. InteractiveAnnotation.call(this, params);
  10419. var dict = params.dict;
  10420. var data = this.data;
  10421. data.annotationType = AnnotationType.LINK;
  10422. var action = dict.get('A');
  10423. if (action && isDict(action)) {
  10424. var linkType = action.get('S').name;
  10425. if (linkType === 'URI') {
  10426. var url = action.get('URI');
  10427. if (isName(url)) {
  10428. // Some bad PDFs do not put parentheses around relative URLs.
  10429. url = '/' + url.name;
  10430. } else if (url) {
  10431. url = addDefaultProtocolToUrl(url);
  10432. }
  10433. // TODO: pdf spec mentions urls can be relative to a Base
  10434. // entry in the dictionary.
  10435. if (!isValidUrl(url, false)) {
  10436. url = '';
  10437. }
  10438. // According to ISO 32000-1:2008, section 12.6.4.7,
  10439. // URI should to be encoded in 7-bit ASCII.
  10440. // Some bad PDFs may have URIs in UTF-8 encoding, see Bugzilla 1122280.
  10441. try {
  10442. data.url = stringToUTF8String(url);
  10443. } catch (e) {
  10444. // Fall back to a simple copy.
  10445. data.url = url;
  10446. }
  10447. } else if (linkType === 'GoTo') {
  10448. data.dest = action.get('D');
  10449. } else if (linkType === 'GoToR') {
  10450. var urlDict = action.get('F');
  10451. if (isDict(urlDict)) {
  10452. // We assume that the 'url' is a Filspec dictionary
  10453. // and fetch the url without checking any further
  10454. url = urlDict.get('F') || '';
  10455. }
  10456. // TODO: pdf reference says that GoToR
  10457. // can also have 'NewWindow' attribute
  10458. if (!isValidUrl(url, false)) {
  10459. url = '';
  10460. }
  10461. data.url = url;
  10462. data.dest = action.get('D');
  10463. } else if (linkType === 'Named') {
  10464. data.action = action.get('N').name;
  10465. } else {
  10466. warn('unrecognized link type: ' + linkType);
  10467. }
  10468. } else if (dict.has('Dest')) {
  10469. // simple destination link
  10470. var dest = dict.get('Dest');
  10471. data.dest = isName(dest) ? dest.name : dest;
  10472. }
  10473. }
  10474. // Lets URLs beginning with 'www.' default to using the 'http://' protocol.
  10475. function addDefaultProtocolToUrl(url) {
  10476. if (url && url.indexOf('www.') === 0) {
  10477. return ('http://' + url);
  10478. }
  10479. return url;
  10480. }
  10481. Util.inherit(LinkAnnotation, InteractiveAnnotation, { });
  10482. return LinkAnnotation;
  10483. })();
  10484. var PDFFunction = (function PDFFunctionClosure() {
  10485. var CONSTRUCT_SAMPLED = 0;
  10486. var CONSTRUCT_INTERPOLATED = 2;
  10487. var CONSTRUCT_STICHED = 3;
  10488. var CONSTRUCT_POSTSCRIPT = 4;
  10489. return {
  10490. getSampleArray: function PDFFunction_getSampleArray(size, outputSize, bps,
  10491. str) {
  10492. var i, ii;
  10493. var length = 1;
  10494. for (i = 0, ii = size.length; i < ii; i++) {
  10495. length *= size[i];
  10496. }
  10497. length *= outputSize;
  10498. var array = new Array(length);
  10499. var codeSize = 0;
  10500. var codeBuf = 0;
  10501. // 32 is a valid bps so shifting won't work
  10502. var sampleMul = 1.0 / (Math.pow(2.0, bps) - 1);
  10503. var strBytes = str.getBytes((length * bps + 7) / 8);
  10504. var strIdx = 0;
  10505. for (i = 0; i < length; i++) {
  10506. while (codeSize < bps) {
  10507. codeBuf <<= 8;
  10508. codeBuf |= strBytes[strIdx++];
  10509. codeSize += 8;
  10510. }
  10511. codeSize -= bps;
  10512. array[i] = (codeBuf >> codeSize) * sampleMul;
  10513. codeBuf &= (1 << codeSize) - 1;
  10514. }
  10515. return array;
  10516. },
  10517. getIR: function PDFFunction_getIR(xref, fn) {
  10518. var dict = fn.dict;
  10519. if (!dict) {
  10520. dict = fn;
  10521. }
  10522. var types = [this.constructSampled,
  10523. null,
  10524. this.constructInterpolated,
  10525. this.constructStiched,
  10526. this.constructPostScript];
  10527. var typeNum = dict.get('FunctionType');
  10528. var typeFn = types[typeNum];
  10529. if (!typeFn) {
  10530. error('Unknown type of function');
  10531. }
  10532. return typeFn.call(this, fn, dict, xref);
  10533. },
  10534. fromIR: function PDFFunction_fromIR(IR) {
  10535. var type = IR[0];
  10536. switch (type) {
  10537. case CONSTRUCT_SAMPLED:
  10538. return this.constructSampledFromIR(IR);
  10539. case CONSTRUCT_INTERPOLATED:
  10540. return this.constructInterpolatedFromIR(IR);
  10541. case CONSTRUCT_STICHED:
  10542. return this.constructStichedFromIR(IR);
  10543. //case CONSTRUCT_POSTSCRIPT:
  10544. default:
  10545. return this.constructPostScriptFromIR(IR);
  10546. }
  10547. },
  10548. parse: function PDFFunction_parse(xref, fn) {
  10549. var IR = this.getIR(xref, fn);
  10550. return this.fromIR(IR);
  10551. },
  10552. parseArray: function PDFFunction_parseArray(xref, fnObj) {
  10553. if (!isArray(fnObj)) {
  10554. // not an array -- parsing as regular function
  10555. return this.parse(xref, fnObj);
  10556. }
  10557. var fnArray = [];
  10558. for (var j = 0, jj = fnObj.length; j < jj; j++) {
  10559. var obj = xref.fetchIfRef(fnObj[j]);
  10560. fnArray.push(PDFFunction.parse(xref, obj));
  10561. }
  10562. return function (src, srcOffset, dest, destOffset) {
  10563. for (var i = 0, ii = fnArray.length; i < ii; i++) {
  10564. fnArray[i](src, srcOffset, dest, destOffset + i);
  10565. }
  10566. };
  10567. },
  10568. constructSampled: function PDFFunction_constructSampled(str, dict) {
  10569. function toMultiArray(arr) {
  10570. var inputLength = arr.length;
  10571. var out = [];
  10572. var index = 0;
  10573. for (var i = 0; i < inputLength; i += 2) {
  10574. out[index] = [arr[i], arr[i + 1]];
  10575. ++index;
  10576. }
  10577. return out;
  10578. }
  10579. var domain = dict.get('Domain');
  10580. var range = dict.get('Range');
  10581. if (!domain || !range) {
  10582. error('No domain or range');
  10583. }
  10584. var inputSize = domain.length / 2;
  10585. var outputSize = range.length / 2;
  10586. domain = toMultiArray(domain);
  10587. range = toMultiArray(range);
  10588. var size = dict.get('Size');
  10589. var bps = dict.get('BitsPerSample');
  10590. var order = dict.get('Order') || 1;
  10591. if (order !== 1) {
  10592. // No description how cubic spline interpolation works in PDF32000:2008
  10593. // As in poppler, ignoring order, linear interpolation may work as good
  10594. info('No support for cubic spline interpolation: ' + order);
  10595. }
  10596. var encode = dict.get('Encode');
  10597. if (!encode) {
  10598. encode = [];
  10599. for (var i = 0; i < inputSize; ++i) {
  10600. encode.push(0);
  10601. encode.push(size[i] - 1);
  10602. }
  10603. }
  10604. encode = toMultiArray(encode);
  10605. var decode = dict.get('Decode');
  10606. if (!decode) {
  10607. decode = range;
  10608. } else {
  10609. decode = toMultiArray(decode);
  10610. }
  10611. var samples = this.getSampleArray(size, outputSize, bps, str);
  10612. return [
  10613. CONSTRUCT_SAMPLED, inputSize, domain, encode, decode, samples, size,
  10614. outputSize, Math.pow(2, bps) - 1, range
  10615. ];
  10616. },
  10617. constructSampledFromIR: function PDFFunction_constructSampledFromIR(IR) {
  10618. // See chapter 3, page 109 of the PDF reference
  10619. function interpolate(x, xmin, xmax, ymin, ymax) {
  10620. return ymin + ((x - xmin) * ((ymax - ymin) / (xmax - xmin)));
  10621. }
  10622. return function constructSampledFromIRResult(src, srcOffset,
  10623. dest, destOffset) {
  10624. // See chapter 3, page 110 of the PDF reference.
  10625. var m = IR[1];
  10626. var domain = IR[2];
  10627. var encode = IR[3];
  10628. var decode = IR[4];
  10629. var samples = IR[5];
  10630. var size = IR[6];
  10631. var n = IR[7];
  10632. //var mask = IR[8];
  10633. var range = IR[9];
  10634. // Building the cube vertices: its part and sample index
  10635. // http://rjwagner49.com/Mathematics/Interpolation.pdf
  10636. var cubeVertices = 1 << m;
  10637. var cubeN = new Float64Array(cubeVertices);
  10638. var cubeVertex = new Uint32Array(cubeVertices);
  10639. var i, j;
  10640. for (j = 0; j < cubeVertices; j++) {
  10641. cubeN[j] = 1;
  10642. }
  10643. var k = n, pos = 1;
  10644. // Map x_i to y_j for 0 <= i < m using the sampled function.
  10645. for (i = 0; i < m; ++i) {
  10646. // x_i' = min(max(x_i, Domain_2i), Domain_2i+1)
  10647. var domain_2i = domain[i][0];
  10648. var domain_2i_1 = domain[i][1];
  10649. var xi = Math.min(Math.max(src[srcOffset +i], domain_2i),
  10650. domain_2i_1);
  10651. // e_i = Interpolate(x_i', Domain_2i, Domain_2i+1,
  10652. // Encode_2i, Encode_2i+1)
  10653. var e = interpolate(xi, domain_2i, domain_2i_1,
  10654. encode[i][0], encode[i][1]);
  10655. // e_i' = min(max(e_i, 0), Size_i - 1)
  10656. var size_i = size[i];
  10657. e = Math.min(Math.max(e, 0), size_i - 1);
  10658. // Adjusting the cube: N and vertex sample index
  10659. var e0 = e < size_i - 1 ? Math.floor(e) : e - 1; // e1 = e0 + 1;
  10660. var n0 = e0 + 1 - e; // (e1 - e) / (e1 - e0);
  10661. var n1 = e - e0; // (e - e0) / (e1 - e0);
  10662. var offset0 = e0 * k;
  10663. var offset1 = offset0 + k; // e1 * k
  10664. for (j = 0; j < cubeVertices; j++) {
  10665. if (j & pos) {
  10666. cubeN[j] *= n1;
  10667. cubeVertex[j] += offset1;
  10668. } else {
  10669. cubeN[j] *= n0;
  10670. cubeVertex[j] += offset0;
  10671. }
  10672. }
  10673. k *= size_i;
  10674. pos <<= 1;
  10675. }
  10676. for (j = 0; j < n; ++j) {
  10677. // Sum all cube vertices' samples portions
  10678. var rj = 0;
  10679. for (i = 0; i < cubeVertices; i++) {
  10680. rj += samples[cubeVertex[i] + j] * cubeN[i];
  10681. }
  10682. // r_j' = Interpolate(r_j, 0, 2^BitsPerSample - 1,
  10683. // Decode_2j, Decode_2j+1)
  10684. rj = interpolate(rj, 0, 1, decode[j][0], decode[j][1]);
  10685. // y_j = min(max(r_j, range_2j), range_2j+1)
  10686. dest[destOffset + j] = Math.min(Math.max(rj, range[j][0]),
  10687. range[j][1]);
  10688. }
  10689. };
  10690. },
  10691. constructInterpolated: function PDFFunction_constructInterpolated(str,
  10692. dict) {
  10693. var c0 = dict.get('C0') || [0];
  10694. var c1 = dict.get('C1') || [1];
  10695. var n = dict.get('N');
  10696. if (!isArray(c0) || !isArray(c1)) {
  10697. error('Illegal dictionary for interpolated function');
  10698. }
  10699. var length = c0.length;
  10700. var diff = [];
  10701. for (var i = 0; i < length; ++i) {
  10702. diff.push(c1[i] - c0[i]);
  10703. }
  10704. return [CONSTRUCT_INTERPOLATED, c0, diff, n];
  10705. },
  10706. constructInterpolatedFromIR:
  10707. function PDFFunction_constructInterpolatedFromIR(IR) {
  10708. var c0 = IR[1];
  10709. var diff = IR[2];
  10710. var n = IR[3];
  10711. var length = diff.length;
  10712. return function constructInterpolatedFromIRResult(src, srcOffset,
  10713. dest, destOffset) {
  10714. var x = n === 1 ? src[srcOffset] : Math.pow(src[srcOffset], n);
  10715. for (var j = 0; j < length; ++j) {
  10716. dest[destOffset + j] = c0[j] + (x * diff[j]);
  10717. }
  10718. };
  10719. },
  10720. constructStiched: function PDFFunction_constructStiched(fn, dict, xref) {
  10721. var domain = dict.get('Domain');
  10722. if (!domain) {
  10723. error('No domain');
  10724. }
  10725. var inputSize = domain.length / 2;
  10726. if (inputSize !== 1) {
  10727. error('Bad domain for stiched function');
  10728. }
  10729. var fnRefs = dict.get('Functions');
  10730. var fns = [];
  10731. for (var i = 0, ii = fnRefs.length; i < ii; ++i) {
  10732. fns.push(PDFFunction.getIR(xref, xref.fetchIfRef(fnRefs[i])));
  10733. }
  10734. var bounds = dict.get('Bounds');
  10735. var encode = dict.get('Encode');
  10736. return [CONSTRUCT_STICHED, domain, bounds, encode, fns];
  10737. },
  10738. constructStichedFromIR: function PDFFunction_constructStichedFromIR(IR) {
  10739. var domain = IR[1];
  10740. var bounds = IR[2];
  10741. var encode = IR[3];
  10742. var fnsIR = IR[4];
  10743. var fns = [];
  10744. var tmpBuf = new Float32Array(1);
  10745. for (var i = 0, ii = fnsIR.length; i < ii; i++) {
  10746. fns.push(PDFFunction.fromIR(fnsIR[i]));
  10747. }
  10748. return function constructStichedFromIRResult(src, srcOffset,
  10749. dest, destOffset) {
  10750. var clip = function constructStichedFromIRClip(v, min, max) {
  10751. if (v > max) {
  10752. v = max;
  10753. } else if (v < min) {
  10754. v = min;
  10755. }
  10756. return v;
  10757. };
  10758. // clip to domain
  10759. var v = clip(src[srcOffset], domain[0], domain[1]);
  10760. // calulate which bound the value is in
  10761. for (var i = 0, ii = bounds.length; i < ii; ++i) {
  10762. if (v < bounds[i]) {
  10763. break;
  10764. }
  10765. }
  10766. // encode value into domain of function
  10767. var dmin = domain[0];
  10768. if (i > 0) {
  10769. dmin = bounds[i - 1];
  10770. }
  10771. var dmax = domain[1];
  10772. if (i < bounds.length) {
  10773. dmax = bounds[i];
  10774. }
  10775. var rmin = encode[2 * i];
  10776. var rmax = encode[2 * i + 1];
  10777. // Prevent the value from becoming NaN as a result
  10778. // of division by zero (fixes issue6113.pdf).
  10779. tmpBuf[0] = dmin === dmax ? rmin :
  10780. rmin + (v - dmin) * (rmax - rmin) / (dmax - dmin);
  10781. // call the appropriate function
  10782. fns[i](tmpBuf, 0, dest, destOffset);
  10783. };
  10784. },
  10785. constructPostScript: function PDFFunction_constructPostScript(fn, dict,
  10786. xref) {
  10787. var domain = dict.get('Domain');
  10788. var range = dict.get('Range');
  10789. if (!domain) {
  10790. error('No domain.');
  10791. }
  10792. if (!range) {
  10793. error('No range.');
  10794. }
  10795. var lexer = new PostScriptLexer(fn);
  10796. var parser = new PostScriptParser(lexer);
  10797. var code = parser.parse();
  10798. return [CONSTRUCT_POSTSCRIPT, domain, range, code];
  10799. },
  10800. constructPostScriptFromIR: function PDFFunction_constructPostScriptFromIR(
  10801. IR) {
  10802. var domain = IR[1];
  10803. var range = IR[2];
  10804. var code = IR[3];
  10805. var compiled = (new PostScriptCompiler()).compile(code, domain, range);
  10806. if (compiled) {
  10807. // Compiled function consists of simple expressions such as addition,
  10808. // subtraction, Math.max, and also contains 'var' and 'return'
  10809. // statements. See the generation in the PostScriptCompiler below.
  10810. /*jshint -W054 */
  10811. return new Function('src', 'srcOffset', 'dest', 'destOffset', compiled);
  10812. }
  10813. info('Unable to compile PS function');
  10814. var numOutputs = range.length >> 1;
  10815. var numInputs = domain.length >> 1;
  10816. var evaluator = new PostScriptEvaluator(code);
  10817. // Cache the values for a big speed up, the cache size is limited though
  10818. // since the number of possible values can be huge from a PS function.
  10819. var cache = {};
  10820. // The MAX_CACHE_SIZE is set to ~4x the maximum number of distinct values
  10821. // seen in our tests.
  10822. var MAX_CACHE_SIZE = 2048 * 4;
  10823. var cache_available = MAX_CACHE_SIZE;
  10824. var tmpBuf = new Float32Array(numInputs);
  10825. return function constructPostScriptFromIRResult(src, srcOffset,
  10826. dest, destOffset) {
  10827. var i, value;
  10828. var key = '';
  10829. var input = tmpBuf;
  10830. for (i = 0; i < numInputs; i++) {
  10831. value = src[srcOffset + i];
  10832. input[i] = value;
  10833. key += value + '_';
  10834. }
  10835. var cachedValue = cache[key];
  10836. if (cachedValue !== undefined) {
  10837. dest.set(cachedValue, destOffset);
  10838. return;
  10839. }
  10840. var output = new Float32Array(numOutputs);
  10841. var stack = evaluator.execute(input);
  10842. var stackIndex = stack.length - numOutputs;
  10843. for (i = 0; i < numOutputs; i++) {
  10844. value = stack[stackIndex + i];
  10845. var bound = range[i * 2];
  10846. if (value < bound) {
  10847. value = bound;
  10848. } else {
  10849. bound = range[i * 2 +1];
  10850. if (value > bound) {
  10851. value = bound;
  10852. }
  10853. }
  10854. output[i] = value;
  10855. }
  10856. if (cache_available > 0) {
  10857. cache_available--;
  10858. cache[key] = output;
  10859. }
  10860. dest.set(output, destOffset);
  10861. };
  10862. }
  10863. };
  10864. })();
  10865. function isPDFFunction(v) {
  10866. var fnDict;
  10867. if (typeof v !== 'object') {
  10868. return false;
  10869. } else if (isDict(v)) {
  10870. fnDict = v;
  10871. } else if (isStream(v)) {
  10872. fnDict = v.dict;
  10873. } else {
  10874. return false;
  10875. }
  10876. return fnDict.has('FunctionType');
  10877. }
  10878. var PostScriptStack = (function PostScriptStackClosure() {
  10879. var MAX_STACK_SIZE = 100;
  10880. function PostScriptStack(initialStack) {
  10881. this.stack = !initialStack ? [] :
  10882. Array.prototype.slice.call(initialStack, 0);
  10883. }
  10884. PostScriptStack.prototype = {
  10885. push: function PostScriptStack_push(value) {
  10886. if (this.stack.length >= MAX_STACK_SIZE) {
  10887. error('PostScript function stack overflow.');
  10888. }
  10889. this.stack.push(value);
  10890. },
  10891. pop: function PostScriptStack_pop() {
  10892. if (this.stack.length <= 0) {
  10893. error('PostScript function stack underflow.');
  10894. }
  10895. return this.stack.pop();
  10896. },
  10897. copy: function PostScriptStack_copy(n) {
  10898. if (this.stack.length + n >= MAX_STACK_SIZE) {
  10899. error('PostScript function stack overflow.');
  10900. }
  10901. var stack = this.stack;
  10902. for (var i = stack.length - n, j = n - 1; j >= 0; j--, i++) {
  10903. stack.push(stack[i]);
  10904. }
  10905. },
  10906. index: function PostScriptStack_index(n) {
  10907. this.push(this.stack[this.stack.length - n - 1]);
  10908. },
  10909. // rotate the last n stack elements p times
  10910. roll: function PostScriptStack_roll(n, p) {
  10911. var stack = this.stack;
  10912. var l = stack.length - n;
  10913. var r = stack.length - 1, c = l + (p - Math.floor(p / n) * n), i, j, t;
  10914. for (i = l, j = r; i < j; i++, j--) {
  10915. t = stack[i]; stack[i] = stack[j]; stack[j] = t;
  10916. }
  10917. for (i = l, j = c - 1; i < j; i++, j--) {
  10918. t = stack[i]; stack[i] = stack[j]; stack[j] = t;
  10919. }
  10920. for (i = c, j = r; i < j; i++, j--) {
  10921. t = stack[i]; stack[i] = stack[j]; stack[j] = t;
  10922. }
  10923. }
  10924. };
  10925. return PostScriptStack;
  10926. })();
  10927. var PostScriptEvaluator = (function PostScriptEvaluatorClosure() {
  10928. function PostScriptEvaluator(operators) {
  10929. this.operators = operators;
  10930. }
  10931. PostScriptEvaluator.prototype = {
  10932. execute: function PostScriptEvaluator_execute(initialStack) {
  10933. var stack = new PostScriptStack(initialStack);
  10934. var counter = 0;
  10935. var operators = this.operators;
  10936. var length = operators.length;
  10937. var operator, a, b;
  10938. while (counter < length) {
  10939. operator = operators[counter++];
  10940. if (typeof operator === 'number') {
  10941. // Operator is really an operand and should be pushed to the stack.
  10942. stack.push(operator);
  10943. continue;
  10944. }
  10945. switch (operator) {
  10946. // non standard ps operators
  10947. case 'jz': // jump if false
  10948. b = stack.pop();
  10949. a = stack.pop();
  10950. if (!a) {
  10951. counter = b;
  10952. }
  10953. break;
  10954. case 'j': // jump
  10955. a = stack.pop();
  10956. counter = a;
  10957. break;
  10958. // all ps operators in alphabetical order (excluding if/ifelse)
  10959. case 'abs':
  10960. a = stack.pop();
  10961. stack.push(Math.abs(a));
  10962. break;
  10963. case 'add':
  10964. b = stack.pop();
  10965. a = stack.pop();
  10966. stack.push(a + b);
  10967. break;
  10968. case 'and':
  10969. b = stack.pop();
  10970. a = stack.pop();
  10971. if (isBool(a) && isBool(b)) {
  10972. stack.push(a && b);
  10973. } else {
  10974. stack.push(a & b);
  10975. }
  10976. break;
  10977. case 'atan':
  10978. a = stack.pop();
  10979. stack.push(Math.atan(a));
  10980. break;
  10981. case 'bitshift':
  10982. b = stack.pop();
  10983. a = stack.pop();
  10984. if (a > 0) {
  10985. stack.push(a << b);
  10986. } else {
  10987. stack.push(a >> b);
  10988. }
  10989. break;
  10990. case 'ceiling':
  10991. a = stack.pop();
  10992. stack.push(Math.ceil(a));
  10993. break;
  10994. case 'copy':
  10995. a = stack.pop();
  10996. stack.copy(a);
  10997. break;
  10998. case 'cos':
  10999. a = stack.pop();
  11000. stack.push(Math.cos(a));
  11001. break;
  11002. case 'cvi':
  11003. a = stack.pop() | 0;
  11004. stack.push(a);
  11005. break;
  11006. case 'cvr':
  11007. // noop
  11008. break;
  11009. case 'div':
  11010. b = stack.pop();
  11011. a = stack.pop();
  11012. stack.push(a / b);
  11013. break;
  11014. case 'dup':
  11015. stack.copy(1);
  11016. break;
  11017. case 'eq':
  11018. b = stack.pop();
  11019. a = stack.pop();
  11020. stack.push(a === b);
  11021. break;
  11022. case 'exch':
  11023. stack.roll(2, 1);
  11024. break;
  11025. case 'exp':
  11026. b = stack.pop();
  11027. a = stack.pop();
  11028. stack.push(Math.pow(a, b));
  11029. break;
  11030. case 'false':
  11031. stack.push(false);
  11032. break;
  11033. case 'floor':
  11034. a = stack.pop();
  11035. stack.push(Math.floor(a));
  11036. break;
  11037. case 'ge':
  11038. b = stack.pop();
  11039. a = stack.pop();
  11040. stack.push(a >= b);
  11041. break;
  11042. case 'gt':
  11043. b = stack.pop();
  11044. a = stack.pop();
  11045. stack.push(a > b);
  11046. break;
  11047. case 'idiv':
  11048. b = stack.pop();
  11049. a = stack.pop();
  11050. stack.push((a / b) | 0);
  11051. break;
  11052. case 'index':
  11053. a = stack.pop();
  11054. stack.index(a);
  11055. break;
  11056. case 'le':
  11057. b = stack.pop();
  11058. a = stack.pop();
  11059. stack.push(a <= b);
  11060. break;
  11061. case 'ln':
  11062. a = stack.pop();
  11063. stack.push(Math.log(a));
  11064. break;
  11065. case 'log':
  11066. a = stack.pop();
  11067. stack.push(Math.log(a) / Math.LN10);
  11068. break;
  11069. case 'lt':
  11070. b = stack.pop();
  11071. a = stack.pop();
  11072. stack.push(a < b);
  11073. break;
  11074. case 'mod':
  11075. b = stack.pop();
  11076. a = stack.pop();
  11077. stack.push(a % b);
  11078. break;
  11079. case 'mul':
  11080. b = stack.pop();
  11081. a = stack.pop();
  11082. stack.push(a * b);
  11083. break;
  11084. case 'ne':
  11085. b = stack.pop();
  11086. a = stack.pop();
  11087. stack.push(a !== b);
  11088. break;
  11089. case 'neg':
  11090. a = stack.pop();
  11091. stack.push(-a);
  11092. break;
  11093. case 'not':
  11094. a = stack.pop();
  11095. if (isBool(a)) {
  11096. stack.push(!a);
  11097. } else {
  11098. stack.push(~a);
  11099. }
  11100. break;
  11101. case 'or':
  11102. b = stack.pop();
  11103. a = stack.pop();
  11104. if (isBool(a) && isBool(b)) {
  11105. stack.push(a || b);
  11106. } else {
  11107. stack.push(a | b);
  11108. }
  11109. break;
  11110. case 'pop':
  11111. stack.pop();
  11112. break;
  11113. case 'roll':
  11114. b = stack.pop();
  11115. a = stack.pop();
  11116. stack.roll(a, b);
  11117. break;
  11118. case 'round':
  11119. a = stack.pop();
  11120. stack.push(Math.round(a));
  11121. break;
  11122. case 'sin':
  11123. a = stack.pop();
  11124. stack.push(Math.sin(a));
  11125. break;
  11126. case 'sqrt':
  11127. a = stack.pop();
  11128. stack.push(Math.sqrt(a));
  11129. break;
  11130. case 'sub':
  11131. b = stack.pop();
  11132. a = stack.pop();
  11133. stack.push(a - b);
  11134. break;
  11135. case 'true':
  11136. stack.push(true);
  11137. break;
  11138. case 'truncate':
  11139. a = stack.pop();
  11140. a = a < 0 ? Math.ceil(a) : Math.floor(a);
  11141. stack.push(a);
  11142. break;
  11143. case 'xor':
  11144. b = stack.pop();
  11145. a = stack.pop();
  11146. if (isBool(a) && isBool(b)) {
  11147. stack.push(a !== b);
  11148. } else {
  11149. stack.push(a ^ b);
  11150. }
  11151. break;
  11152. default:
  11153. error('Unknown operator ' + operator);
  11154. break;
  11155. }
  11156. }
  11157. return stack.stack;
  11158. }
  11159. };
  11160. return PostScriptEvaluator;
  11161. })();
  11162. // Most of the PDFs functions consist of simple operations such as:
  11163. // roll, exch, sub, cvr, pop, index, dup, mul, if, gt, add.
  11164. //
  11165. // We can compile most of such programs, and at the same moment, we can
  11166. // optimize some expressions using basic math properties. Keeping track of
  11167. // min/max values will allow us to avoid extra Math.min/Math.max calls.
  11168. var PostScriptCompiler = (function PostScriptCompilerClosure() {
  11169. function AstNode(type) {
  11170. this.type = type;
  11171. }
  11172. AstNode.prototype.visit = function (visitor) {
  11173. throw new Error('abstract method');
  11174. };
  11175. function AstArgument(index, min, max) {
  11176. AstNode.call(this, 'args');
  11177. this.index = index;
  11178. this.min = min;
  11179. this.max = max;
  11180. }
  11181. AstArgument.prototype = Object.create(AstNode.prototype);
  11182. AstArgument.prototype.visit = function (visitor) {
  11183. visitor.visitArgument(this);
  11184. };
  11185. function AstLiteral(number) {
  11186. AstNode.call(this, 'literal');
  11187. this.number = number;
  11188. this.min = number;
  11189. this.max = number;
  11190. }
  11191. AstLiteral.prototype = Object.create(AstNode.prototype);
  11192. AstLiteral.prototype.visit = function (visitor) {
  11193. visitor.visitLiteral(this);
  11194. };
  11195. function AstBinaryOperation(op, arg1, arg2, min, max) {
  11196. AstNode.call(this, 'binary');
  11197. this.op = op;
  11198. this.arg1 = arg1;
  11199. this.arg2 = arg2;
  11200. this.min = min;
  11201. this.max = max;
  11202. }
  11203. AstBinaryOperation.prototype = Object.create(AstNode.prototype);
  11204. AstBinaryOperation.prototype.visit = function (visitor) {
  11205. visitor.visitBinaryOperation(this);
  11206. };
  11207. function AstMin(arg, max) {
  11208. AstNode.call(this, 'max');
  11209. this.arg = arg;
  11210. this.min = arg.min;
  11211. this.max = max;
  11212. }
  11213. AstMin.prototype = Object.create(AstNode.prototype);
  11214. AstMin.prototype.visit = function (visitor) {
  11215. visitor.visitMin(this);
  11216. };
  11217. function AstVariable(index, min, max) {
  11218. AstNode.call(this, 'var');
  11219. this.index = index;
  11220. this.min = min;
  11221. this.max = max;
  11222. }
  11223. AstVariable.prototype = Object.create(AstNode.prototype);
  11224. AstVariable.prototype.visit = function (visitor) {
  11225. visitor.visitVariable(this);
  11226. };
  11227. function AstVariableDefinition(variable, arg) {
  11228. AstNode.call(this, 'definition');
  11229. this.variable = variable;
  11230. this.arg = arg;
  11231. }
  11232. AstVariableDefinition.prototype = Object.create(AstNode.prototype);
  11233. AstVariableDefinition.prototype.visit = function (visitor) {
  11234. visitor.visitVariableDefinition(this);
  11235. };
  11236. function ExpressionBuilderVisitor() {
  11237. this.parts = [];
  11238. }
  11239. ExpressionBuilderVisitor.prototype = {
  11240. visitArgument: function (arg) {
  11241. this.parts.push('Math.max(', arg.min, ', Math.min(',
  11242. arg.max, ', src[srcOffset + ', arg.index, ']))');
  11243. },
  11244. visitVariable: function (variable) {
  11245. this.parts.push('v', variable.index);
  11246. },
  11247. visitLiteral: function (literal) {
  11248. this.parts.push(literal.number);
  11249. },
  11250. visitBinaryOperation: function (operation) {
  11251. this.parts.push('(');
  11252. operation.arg1.visit(this);
  11253. this.parts.push(' ', operation.op, ' ');
  11254. operation.arg2.visit(this);
  11255. this.parts.push(')');
  11256. },
  11257. visitVariableDefinition: function (definition) {
  11258. this.parts.push('var ');
  11259. definition.variable.visit(this);
  11260. this.parts.push(' = ');
  11261. definition.arg.visit(this);
  11262. this.parts.push(';');
  11263. },
  11264. visitMin: function (max) {
  11265. this.parts.push('Math.min(');
  11266. max.arg.visit(this);
  11267. this.parts.push(', ', max.max, ')');
  11268. },
  11269. toString: function () {
  11270. return this.parts.join('');
  11271. }
  11272. };
  11273. function buildAddOperation(num1, num2) {
  11274. if (num2.type === 'literal' && num2.number === 0) {
  11275. // optimization: second operand is 0
  11276. return num1;
  11277. }
  11278. if (num1.type === 'literal' && num1.number === 0) {
  11279. // optimization: first operand is 0
  11280. return num2;
  11281. }
  11282. if (num2.type === 'literal' && num1.type === 'literal') {
  11283. // optimization: operands operand are literals
  11284. return new AstLiteral(num1.number + num2.number);
  11285. }
  11286. return new AstBinaryOperation('+', num1, num2,
  11287. num1.min + num2.min, num1.max + num2.max);
  11288. }
  11289. function buildMulOperation(num1, num2) {
  11290. if (num2.type === 'literal') {
  11291. // optimization: second operands is a literal...
  11292. if (num2.number === 0) {
  11293. return new AstLiteral(0); // and it's 0
  11294. } else if (num2.number === 1) {
  11295. return num1; // and it's 1
  11296. } else if (num1.type === 'literal') {
  11297. // ... and first operands is a literal too
  11298. return new AstLiteral(num1.number * num2.number);
  11299. }
  11300. }
  11301. if (num1.type === 'literal') {
  11302. // optimization: first operands is a literal...
  11303. if (num1.number === 0) {
  11304. return new AstLiteral(0); // and it's 0
  11305. } else if (num1.number === 1) {
  11306. return num2; // and it's 1
  11307. }
  11308. }
  11309. var min = Math.min(num1.min * num2.min, num1.min * num2.max,
  11310. num1.max * num2.min, num1.max * num2.max);
  11311. var max = Math.max(num1.min * num2.min, num1.min * num2.max,
  11312. num1.max * num2.min, num1.max * num2.max);
  11313. return new AstBinaryOperation('*', num1, num2, min, max);
  11314. }
  11315. function buildSubOperation(num1, num2) {
  11316. if (num2.type === 'literal') {
  11317. // optimization: second operands is a literal...
  11318. if (num2.number === 0) {
  11319. return num1; // ... and it's 0
  11320. } else if (num1.type === 'literal') {
  11321. // ... and first operands is a literal too
  11322. return new AstLiteral(num1.number - num2.number);
  11323. }
  11324. }
  11325. if (num2.type === 'binary' && num2.op === '-' &&
  11326. num1.type === 'literal' && num1.number === 1 &&
  11327. num2.arg1.type === 'literal' && num2.arg1.number === 1) {
  11328. // optimization for case: 1 - (1 - x)
  11329. return num2.arg2;
  11330. }
  11331. return new AstBinaryOperation('-', num1, num2,
  11332. num1.min - num2.max, num1.max - num2.min);
  11333. }
  11334. function buildMinOperation(num1, max) {
  11335. if (num1.min >= max) {
  11336. // optimization: num1 min value is not less than required max
  11337. return new AstLiteral(max); // just returning max
  11338. } else if (num1.max <= max) {
  11339. // optimization: num1 max value is not greater than required max
  11340. return num1; // just returning an argument
  11341. }
  11342. return new AstMin(num1, max);
  11343. }
  11344. function PostScriptCompiler() {}
  11345. PostScriptCompiler.prototype = {
  11346. compile: function PostScriptCompiler_compile(code, domain, range) {
  11347. var stack = [];
  11348. var i, ii;
  11349. var instructions = [];
  11350. var inputSize = domain.length >> 1, outputSize = range.length >> 1;
  11351. var lastRegister = 0;
  11352. var n, j, min, max;
  11353. var num1, num2, ast1, ast2, tmpVar, item;
  11354. for (i = 0; i < inputSize; i++) {
  11355. stack.push(new AstArgument(i, domain[i * 2], domain[i * 2 + 1]));
  11356. }
  11357. for (i = 0, ii = code.length; i < ii; i++) {
  11358. item = code[i];
  11359. if (typeof item === 'number') {
  11360. stack.push(new AstLiteral(item));
  11361. continue;
  11362. }
  11363. switch (item) {
  11364. case 'add':
  11365. if (stack.length < 2) {
  11366. return null;
  11367. }
  11368. num2 = stack.pop();
  11369. num1 = stack.pop();
  11370. stack.push(buildAddOperation(num1, num2));
  11371. break;
  11372. case 'cvr':
  11373. if (stack.length < 1) {
  11374. return null;
  11375. }
  11376. break;
  11377. case 'mul':
  11378. if (stack.length < 2) {
  11379. return null;
  11380. }
  11381. num2 = stack.pop();
  11382. num1 = stack.pop();
  11383. stack.push(buildMulOperation(num1, num2));
  11384. break;
  11385. case 'sub':
  11386. if (stack.length < 2) {
  11387. return null;
  11388. }
  11389. num2 = stack.pop();
  11390. num1 = stack.pop();
  11391. stack.push(buildSubOperation(num1, num2));
  11392. break;
  11393. case 'exch':
  11394. if (stack.length < 2) {
  11395. return null;
  11396. }
  11397. ast1 = stack.pop(); ast2 = stack.pop();
  11398. stack.push(ast1, ast2);
  11399. break;
  11400. case 'pop':
  11401. if (stack.length < 1) {
  11402. return null;
  11403. }
  11404. stack.pop();
  11405. break;
  11406. case 'index':
  11407. if (stack.length < 1) {
  11408. return null;
  11409. }
  11410. num1 = stack.pop();
  11411. if (num1.type !== 'literal') {
  11412. return null;
  11413. }
  11414. n = num1.number;
  11415. if (n < 0 || (n|0) !== n || stack.length < n) {
  11416. return null;
  11417. }
  11418. ast1 = stack[stack.length - n - 1];
  11419. if (ast1.type === 'literal' || ast1.type === 'var') {
  11420. stack.push(ast1);
  11421. break;
  11422. }
  11423. tmpVar = new AstVariable(lastRegister++, ast1.min, ast1.max);
  11424. stack[stack.length - n - 1] = tmpVar;
  11425. stack.push(tmpVar);
  11426. instructions.push(new AstVariableDefinition(tmpVar, ast1));
  11427. break;
  11428. case 'dup':
  11429. if (stack.length < 1) {
  11430. return null;
  11431. }
  11432. if (typeof code[i + 1] === 'number' && code[i + 2] === 'gt' &&
  11433. code[i + 3] === i + 7 && code[i + 4] === 'jz' &&
  11434. code[i + 5] === 'pop' && code[i + 6] === code[i + 1]) {
  11435. // special case of the commands sequence for the min operation
  11436. num1 = stack.pop();
  11437. stack.push(buildMinOperation(num1, code[i + 1]));
  11438. i += 6;
  11439. break;
  11440. }
  11441. ast1 = stack[stack.length - 1];
  11442. if (ast1.type === 'literal' || ast1.type === 'var') {
  11443. // we don't have to save into intermediate variable a literal or
  11444. // variable.
  11445. stack.push(ast1);
  11446. break;
  11447. }
  11448. tmpVar = new AstVariable(lastRegister++, ast1.min, ast1.max);
  11449. stack[stack.length - 1] = tmpVar;
  11450. stack.push(tmpVar);
  11451. instructions.push(new AstVariableDefinition(tmpVar, ast1));
  11452. break;
  11453. case 'roll':
  11454. if (stack.length < 2) {
  11455. return null;
  11456. }
  11457. num2 = stack.pop();
  11458. num1 = stack.pop();
  11459. if (num2.type !== 'literal' || num1.type !== 'literal') {
  11460. // both roll operands must be numbers
  11461. return null;
  11462. }
  11463. j = num2.number;
  11464. n = num1.number;
  11465. if (n <= 0 || (n|0) !== n || (j|0) !== j || stack.length < n) {
  11466. // ... and integers
  11467. return null;
  11468. }
  11469. j = ((j % n) + n) % n;
  11470. if (j === 0) {
  11471. break; // just skipping -- there are nothing to rotate
  11472. }
  11473. Array.prototype.push.apply(stack,
  11474. stack.splice(stack.length - n, n - j));
  11475. break;
  11476. default:
  11477. return null; // unsupported operator
  11478. }
  11479. }
  11480. if (stack.length !== outputSize) {
  11481. return null;
  11482. }
  11483. var result = [];
  11484. instructions.forEach(function (instruction) {
  11485. var statementBuilder = new ExpressionBuilderVisitor();
  11486. instruction.visit(statementBuilder);
  11487. result.push(statementBuilder.toString());
  11488. });
  11489. stack.forEach(function (expr, i) {
  11490. var statementBuilder = new ExpressionBuilderVisitor();
  11491. expr.visit(statementBuilder);
  11492. var min = range[i * 2], max = range[i * 2 + 1];
  11493. var out = [statementBuilder.toString()];
  11494. if (min > expr.min) {
  11495. out.unshift('Math.max(', min, ', ');
  11496. out.push(')');
  11497. }
  11498. if (max < expr.max) {
  11499. out.unshift('Math.min(', max, ', ');
  11500. out.push(')');
  11501. }
  11502. out.unshift('dest[destOffset + ', i, '] = ');
  11503. out.push(';');
  11504. result.push(out.join(''));
  11505. });
  11506. return result.join('\n');
  11507. }
  11508. };
  11509. return PostScriptCompiler;
  11510. })();
  11511. var ColorSpace = (function ColorSpaceClosure() {
  11512. // Constructor should define this.numComps, this.defaultColor, this.name
  11513. function ColorSpace() {
  11514. error('should not call ColorSpace constructor');
  11515. }
  11516. ColorSpace.prototype = {
  11517. /**
  11518. * Converts the color value to the RGB color. The color components are
  11519. * located in the src array starting from the srcOffset. Returns the array
  11520. * of the rgb components, each value ranging from [0,255].
  11521. */
  11522. getRgb: function ColorSpace_getRgb(src, srcOffset) {
  11523. var rgb = new Uint8Array(3);
  11524. this.getRgbItem(src, srcOffset, rgb, 0);
  11525. return rgb;
  11526. },
  11527. /**
  11528. * Converts the color value to the RGB color, similar to the getRgb method.
  11529. * The result placed into the dest array starting from the destOffset.
  11530. */
  11531. getRgbItem: function ColorSpace_getRgbItem(src, srcOffset,
  11532. dest, destOffset) {
  11533. error('Should not call ColorSpace.getRgbItem');
  11534. },
  11535. /**
  11536. * Converts the specified number of the color values to the RGB colors.
  11537. * The colors are located in the src array starting from the srcOffset.
  11538. * The result is placed into the dest array starting from the destOffset.
  11539. * The src array items shall be in [0,2^bits) range, the dest array items
  11540. * will be in [0,255] range. alpha01 indicates how many alpha components
  11541. * there are in the dest array; it will be either 0 (RGB array) or 1 (RGBA
  11542. * array).
  11543. */
  11544. getRgbBuffer: function ColorSpace_getRgbBuffer(src, srcOffset, count,
  11545. dest, destOffset, bits,
  11546. alpha01) {
  11547. error('Should not call ColorSpace.getRgbBuffer');
  11548. },
  11549. /**
  11550. * Determines the number of bytes required to store the result of the
  11551. * conversion done by the getRgbBuffer method. As in getRgbBuffer,
  11552. * |alpha01| is either 0 (RGB output) or 1 (RGBA output).
  11553. */
  11554. getOutputLength: function ColorSpace_getOutputLength(inputLength,
  11555. alpha01) {
  11556. error('Should not call ColorSpace.getOutputLength');
  11557. },
  11558. /**
  11559. * Returns true if source data will be equal the result/output data.
  11560. */
  11561. isPassthrough: function ColorSpace_isPassthrough(bits) {
  11562. return false;
  11563. },
  11564. /**
  11565. * Fills in the RGB colors in the destination buffer. alpha01 indicates
  11566. * how many alpha components there are in the dest array; it will be either
  11567. * 0 (RGB array) or 1 (RGBA array).
  11568. */
  11569. fillRgb: function ColorSpace_fillRgb(dest, originalWidth,
  11570. originalHeight, width, height,
  11571. actualHeight, bpc, comps, alpha01) {
  11572. var count = originalWidth * originalHeight;
  11573. var rgbBuf = null;
  11574. var numComponentColors = 1 << bpc;
  11575. var needsResizing = originalHeight !== height || originalWidth !== width;
  11576. var i, ii;
  11577. if (this.isPassthrough(bpc)) {
  11578. rgbBuf = comps;
  11579. } else if (this.numComps === 1 && count > numComponentColors &&
  11580. this.name !== 'DeviceGray' && this.name !== 'DeviceRGB') {
  11581. // Optimization: create a color map when there is just one component and
  11582. // we are converting more colors than the size of the color map. We
  11583. // don't build the map if the colorspace is gray or rgb since those
  11584. // methods are faster than building a map. This mainly offers big speed
  11585. // ups for indexed and alternate colorspaces.
  11586. //
  11587. // TODO it may be worth while to cache the color map. While running
  11588. // testing I never hit a cache so I will leave that out for now (perhaps
  11589. // we are reparsing colorspaces too much?).
  11590. var allColors = bpc <= 8 ? new Uint8Array(numComponentColors) :
  11591. new Uint16Array(numComponentColors);
  11592. var key;
  11593. for (i = 0; i < numComponentColors; i++) {
  11594. allColors[i] = i;
  11595. }
  11596. var colorMap = new Uint8Array(numComponentColors * 3);
  11597. this.getRgbBuffer(allColors, 0, numComponentColors, colorMap, 0, bpc,
  11598. /* alpha01 = */ 0);
  11599. var destPos, rgbPos;
  11600. if (!needsResizing) {
  11601. // Fill in the RGB values directly into |dest|.
  11602. destPos = 0;
  11603. for (i = 0; i < count; ++i) {
  11604. key = comps[i] * 3;
  11605. dest[destPos++] = colorMap[key];
  11606. dest[destPos++] = colorMap[key + 1];
  11607. dest[destPos++] = colorMap[key + 2];
  11608. destPos += alpha01;
  11609. }
  11610. } else {
  11611. rgbBuf = new Uint8Array(count * 3);
  11612. rgbPos = 0;
  11613. for (i = 0; i < count; ++i) {
  11614. key = comps[i] * 3;
  11615. rgbBuf[rgbPos++] = colorMap[key];
  11616. rgbBuf[rgbPos++] = colorMap[key + 1];
  11617. rgbBuf[rgbPos++] = colorMap[key + 2];
  11618. }
  11619. }
  11620. } else {
  11621. if (!needsResizing) {
  11622. // Fill in the RGB values directly into |dest|.
  11623. this.getRgbBuffer(comps, 0, width * actualHeight, dest, 0, bpc,
  11624. alpha01);
  11625. } else {
  11626. rgbBuf = new Uint8Array(count * 3);
  11627. this.getRgbBuffer(comps, 0, count, rgbBuf, 0, bpc,
  11628. /* alpha01 = */ 0);
  11629. }
  11630. }
  11631. if (rgbBuf) {
  11632. if (needsResizing) {
  11633. PDFImage.resize(rgbBuf, bpc, 3, originalWidth, originalHeight, width,
  11634. height, dest, alpha01);
  11635. } else {
  11636. rgbPos = 0;
  11637. destPos = 0;
  11638. for (i = 0, ii = width * actualHeight; i < ii; i++) {
  11639. dest[destPos++] = rgbBuf[rgbPos++];
  11640. dest[destPos++] = rgbBuf[rgbPos++];
  11641. dest[destPos++] = rgbBuf[rgbPos++];
  11642. destPos += alpha01;
  11643. }
  11644. }
  11645. }
  11646. },
  11647. /**
  11648. * True if the colorspace has components in the default range of [0, 1].
  11649. * This should be true for all colorspaces except for lab color spaces
  11650. * which are [0,100], [-128, 127], [-128, 127].
  11651. */
  11652. usesZeroToOneRange: true
  11653. };
  11654. ColorSpace.parse = function ColorSpace_parse(cs, xref, res) {
  11655. var IR = ColorSpace.parseToIR(cs, xref, res);
  11656. if (IR instanceof AlternateCS) {
  11657. return IR;
  11658. }
  11659. return ColorSpace.fromIR(IR);
  11660. };
  11661. ColorSpace.fromIR = function ColorSpace_fromIR(IR) {
  11662. var name = isArray(IR) ? IR[0] : IR;
  11663. var whitePoint, blackPoint, gamma;
  11664. switch (name) {
  11665. case 'DeviceGrayCS':
  11666. return this.singletons.gray;
  11667. case 'DeviceRgbCS':
  11668. return this.singletons.rgb;
  11669. case 'DeviceCmykCS':
  11670. return this.singletons.cmyk;
  11671. case 'CalGrayCS':
  11672. whitePoint = IR[1].WhitePoint;
  11673. blackPoint = IR[1].BlackPoint;
  11674. gamma = IR[1].Gamma;
  11675. return new CalGrayCS(whitePoint, blackPoint, gamma);
  11676. case 'CalRGBCS':
  11677. whitePoint = IR[1].WhitePoint;
  11678. blackPoint = IR[1].BlackPoint;
  11679. gamma = IR[1].Gamma;
  11680. var matrix = IR[1].Matrix;
  11681. return new CalRGBCS(whitePoint, blackPoint, gamma, matrix);
  11682. case 'PatternCS':
  11683. var basePatternCS = IR[1];
  11684. if (basePatternCS) {
  11685. basePatternCS = ColorSpace.fromIR(basePatternCS);
  11686. }
  11687. return new PatternCS(basePatternCS);
  11688. case 'IndexedCS':
  11689. var baseIndexedCS = IR[1];
  11690. var hiVal = IR[2];
  11691. var lookup = IR[3];
  11692. return new IndexedCS(ColorSpace.fromIR(baseIndexedCS), hiVal, lookup);
  11693. case 'AlternateCS':
  11694. var numComps = IR[1];
  11695. var alt = IR[2];
  11696. var tintFnIR = IR[3];
  11697. return new AlternateCS(numComps, ColorSpace.fromIR(alt),
  11698. PDFFunction.fromIR(tintFnIR));
  11699. case 'LabCS':
  11700. whitePoint = IR[1].WhitePoint;
  11701. blackPoint = IR[1].BlackPoint;
  11702. var range = IR[1].Range;
  11703. return new LabCS(whitePoint, blackPoint, range);
  11704. default:
  11705. error('Unknown name ' + name);
  11706. }
  11707. return null;
  11708. };
  11709. ColorSpace.parseToIR = function ColorSpace_parseToIR(cs, xref, res) {
  11710. if (isName(cs)) {
  11711. var colorSpaces = res.get('ColorSpace');
  11712. if (isDict(colorSpaces)) {
  11713. var refcs = colorSpaces.get(cs.name);
  11714. if (refcs) {
  11715. cs = refcs;
  11716. }
  11717. }
  11718. }
  11719. cs = xref.fetchIfRef(cs);
  11720. var mode;
  11721. if (isName(cs)) {
  11722. mode = cs.name;
  11723. this.mode = mode;
  11724. switch (mode) {
  11725. case 'DeviceGray':
  11726. case 'G':
  11727. return 'DeviceGrayCS';
  11728. case 'DeviceRGB':
  11729. case 'RGB':
  11730. return 'DeviceRgbCS';
  11731. case 'DeviceCMYK':
  11732. case 'CMYK':
  11733. return 'DeviceCmykCS';
  11734. case 'Pattern':
  11735. return ['PatternCS', null];
  11736. default:
  11737. error('unrecognized colorspace ' + mode);
  11738. }
  11739. } else if (isArray(cs)) {
  11740. mode = xref.fetchIfRef(cs[0]).name;
  11741. this.mode = mode;
  11742. var numComps, params, alt;
  11743. switch (mode) {
  11744. case 'DeviceGray':
  11745. case 'G':
  11746. return 'DeviceGrayCS';
  11747. case 'DeviceRGB':
  11748. case 'RGB':
  11749. return 'DeviceRgbCS';
  11750. case 'DeviceCMYK':
  11751. case 'CMYK':
  11752. return 'DeviceCmykCS';
  11753. case 'CalGray':
  11754. params = xref.fetchIfRef(cs[1]).getAll();
  11755. return ['CalGrayCS', params];
  11756. case 'CalRGB':
  11757. params = xref.fetchIfRef(cs[1]).getAll();
  11758. return ['CalRGBCS', params];
  11759. case 'ICCBased':
  11760. var stream = xref.fetchIfRef(cs[1]);
  11761. var dict = stream.dict;
  11762. numComps = dict.get('N');
  11763. alt = dict.get('Alternate');
  11764. if (alt) {
  11765. var altIR = ColorSpace.parseToIR(alt, xref, res);
  11766. // Parse the /Alternate CS to ensure that the number of components
  11767. // are correct, and also (indirectly) that it is not a PatternCS.
  11768. var altCS = ColorSpace.fromIR(altIR);
  11769. if (altCS.numComps === numComps) {
  11770. return altIR;
  11771. }
  11772. warn('ICCBased color space: Ignoring incorrect /Alternate entry.');
  11773. }
  11774. if (numComps === 1) {
  11775. return 'DeviceGrayCS';
  11776. } else if (numComps === 3) {
  11777. return 'DeviceRgbCS';
  11778. } else if (numComps === 4) {
  11779. return 'DeviceCmykCS';
  11780. }
  11781. break;
  11782. case 'Pattern':
  11783. var basePatternCS = cs[1] || null;
  11784. if (basePatternCS) {
  11785. basePatternCS = ColorSpace.parseToIR(basePatternCS, xref, res);
  11786. }
  11787. return ['PatternCS', basePatternCS];
  11788. case 'Indexed':
  11789. case 'I':
  11790. var baseIndexedCS = ColorSpace.parseToIR(cs[1], xref, res);
  11791. var hiVal = xref.fetchIfRef(cs[2]) + 1;
  11792. var lookup = xref.fetchIfRef(cs[3]);
  11793. if (isStream(lookup)) {
  11794. lookup = lookup.getBytes();
  11795. }
  11796. return ['IndexedCS', baseIndexedCS, hiVal, lookup];
  11797. case 'Separation':
  11798. case 'DeviceN':
  11799. var name = xref.fetchIfRef(cs[1]);
  11800. numComps = 1;
  11801. if (isName(name)) {
  11802. numComps = 1;
  11803. } else if (isArray(name)) {
  11804. numComps = name.length;
  11805. }
  11806. alt = ColorSpace.parseToIR(cs[2], xref, res);
  11807. var tintFnIR = PDFFunction.getIR(xref, xref.fetchIfRef(cs[3]));
  11808. return ['AlternateCS', numComps, alt, tintFnIR];
  11809. case 'Lab':
  11810. params = xref.fetchIfRef(cs[1]).getAll();
  11811. return ['LabCS', params];
  11812. default:
  11813. error('unimplemented color space object "' + mode + '"');
  11814. }
  11815. } else {
  11816. error('unrecognized color space object: "' + cs + '"');
  11817. }
  11818. return null;
  11819. };
  11820. /**
  11821. * Checks if a decode map matches the default decode map for a color space.
  11822. * This handles the general decode maps where there are two values per
  11823. * component. e.g. [0, 1, 0, 1, 0, 1] for a RGB color.
  11824. * This does not handle Lab, Indexed, or Pattern decode maps since they are
  11825. * slightly different.
  11826. * @param {Array} decode Decode map (usually from an image).
  11827. * @param {Number} n Number of components the color space has.
  11828. */
  11829. ColorSpace.isDefaultDecode = function ColorSpace_isDefaultDecode(decode, n) {
  11830. if (!decode) {
  11831. return true;
  11832. }
  11833. if (n * 2 !== decode.length) {
  11834. warn('The decode map is not the correct length');
  11835. return true;
  11836. }
  11837. for (var i = 0, ii = decode.length; i < ii; i += 2) {
  11838. if (decode[i] !== 0 || decode[i + 1] !== 1) {
  11839. return false;
  11840. }
  11841. }
  11842. return true;
  11843. };
  11844. ColorSpace.singletons = {
  11845. get gray() {
  11846. return shadow(this, 'gray', new DeviceGrayCS());
  11847. },
  11848. get rgb() {
  11849. return shadow(this, 'rgb', new DeviceRgbCS());
  11850. },
  11851. get cmyk() {
  11852. return shadow(this, 'cmyk', new DeviceCmykCS());
  11853. }
  11854. };
  11855. return ColorSpace;
  11856. })();
  11857. /**
  11858. * Alternate color space handles both Separation and DeviceN color spaces. A
  11859. * Separation color space is actually just a DeviceN with one color component.
  11860. * Both color spaces use a tinting function to convert colors to a base color
  11861. * space.
  11862. */
  11863. var AlternateCS = (function AlternateCSClosure() {
  11864. function AlternateCS(numComps, base, tintFn) {
  11865. this.name = 'Alternate';
  11866. this.numComps = numComps;
  11867. this.defaultColor = new Float32Array(numComps);
  11868. for (var i = 0; i < numComps; ++i) {
  11869. this.defaultColor[i] = 1;
  11870. }
  11871. this.base = base;
  11872. this.tintFn = tintFn;
  11873. this.tmpBuf = new Float32Array(base.numComps);
  11874. }
  11875. AlternateCS.prototype = {
  11876. getRgb: ColorSpace.prototype.getRgb,
  11877. getRgbItem: function AlternateCS_getRgbItem(src, srcOffset,
  11878. dest, destOffset) {
  11879. var tmpBuf = this.tmpBuf;
  11880. this.tintFn(src, srcOffset, tmpBuf, 0);
  11881. this.base.getRgbItem(tmpBuf, 0, dest, destOffset);
  11882. },
  11883. getRgbBuffer: function AlternateCS_getRgbBuffer(src, srcOffset, count,
  11884. dest, destOffset, bits,
  11885. alpha01) {
  11886. var tintFn = this.tintFn;
  11887. var base = this.base;
  11888. var scale = 1 / ((1 << bits) - 1);
  11889. var baseNumComps = base.numComps;
  11890. var usesZeroToOneRange = base.usesZeroToOneRange;
  11891. var isPassthrough = (base.isPassthrough(8) || !usesZeroToOneRange) &&
  11892. alpha01 === 0;
  11893. var pos = isPassthrough ? destOffset : 0;
  11894. var baseBuf = isPassthrough ? dest : new Uint8Array(baseNumComps * count);
  11895. var numComps = this.numComps;
  11896. var scaled = new Float32Array(numComps);
  11897. var tinted = new Float32Array(baseNumComps);
  11898. var i, j;
  11899. if (usesZeroToOneRange) {
  11900. for (i = 0; i < count; i++) {
  11901. for (j = 0; j < numComps; j++) {
  11902. scaled[j] = src[srcOffset++] * scale;
  11903. }
  11904. tintFn(scaled, 0, tinted, 0);
  11905. for (j = 0; j < baseNumComps; j++) {
  11906. baseBuf[pos++] = tinted[j] * 255;
  11907. }
  11908. }
  11909. } else {
  11910. for (i = 0; i < count; i++) {
  11911. for (j = 0; j < numComps; j++) {
  11912. scaled[j] = src[srcOffset++] * scale;
  11913. }
  11914. tintFn(scaled, 0, tinted, 0);
  11915. base.getRgbItem(tinted, 0, baseBuf, pos);
  11916. pos += baseNumComps;
  11917. }
  11918. }
  11919. if (!isPassthrough) {
  11920. base.getRgbBuffer(baseBuf, 0, count, dest, destOffset, 8, alpha01);
  11921. }
  11922. },
  11923. getOutputLength: function AlternateCS_getOutputLength(inputLength,
  11924. alpha01) {
  11925. return this.base.getOutputLength(inputLength *
  11926. this.base.numComps / this.numComps,
  11927. alpha01);
  11928. },
  11929. isPassthrough: ColorSpace.prototype.isPassthrough,
  11930. fillRgb: ColorSpace.prototype.fillRgb,
  11931. isDefaultDecode: function AlternateCS_isDefaultDecode(decodeMap) {
  11932. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  11933. },
  11934. usesZeroToOneRange: true
  11935. };
  11936. return AlternateCS;
  11937. })();
  11938. var PatternCS = (function PatternCSClosure() {
  11939. function PatternCS(baseCS) {
  11940. this.name = 'Pattern';
  11941. this.base = baseCS;
  11942. }
  11943. PatternCS.prototype = {};
  11944. return PatternCS;
  11945. })();
  11946. var IndexedCS = (function IndexedCSClosure() {
  11947. function IndexedCS(base, highVal, lookup) {
  11948. this.name = 'Indexed';
  11949. this.numComps = 1;
  11950. this.defaultColor = new Uint8Array([0]);
  11951. this.base = base;
  11952. this.highVal = highVal;
  11953. var baseNumComps = base.numComps;
  11954. var length = baseNumComps * highVal;
  11955. var lookupArray;
  11956. if (isStream(lookup)) {
  11957. lookupArray = new Uint8Array(length);
  11958. var bytes = lookup.getBytes(length);
  11959. lookupArray.set(bytes);
  11960. } else if (isString(lookup)) {
  11961. lookupArray = new Uint8Array(length);
  11962. for (var i = 0; i < length; ++i) {
  11963. lookupArray[i] = lookup.charCodeAt(i);
  11964. }
  11965. } else if (lookup instanceof Uint8Array || lookup instanceof Array) {
  11966. lookupArray = lookup;
  11967. } else {
  11968. error('Unrecognized lookup table: ' + lookup);
  11969. }
  11970. this.lookup = lookupArray;
  11971. }
  11972. IndexedCS.prototype = {
  11973. getRgb: ColorSpace.prototype.getRgb,
  11974. getRgbItem: function IndexedCS_getRgbItem(src, srcOffset,
  11975. dest, destOffset) {
  11976. var numComps = this.base.numComps;
  11977. var start = src[srcOffset] * numComps;
  11978. this.base.getRgbItem(this.lookup, start, dest, destOffset);
  11979. },
  11980. getRgbBuffer: function IndexedCS_getRgbBuffer(src, srcOffset, count,
  11981. dest, destOffset, bits,
  11982. alpha01) {
  11983. var base = this.base;
  11984. var numComps = base.numComps;
  11985. var outputDelta = base.getOutputLength(numComps, alpha01);
  11986. var lookup = this.lookup;
  11987. for (var i = 0; i < count; ++i) {
  11988. var lookupPos = src[srcOffset++] * numComps;
  11989. base.getRgbBuffer(lookup, lookupPos, 1, dest, destOffset, 8, alpha01);
  11990. destOffset += outputDelta;
  11991. }
  11992. },
  11993. getOutputLength: function IndexedCS_getOutputLength(inputLength, alpha01) {
  11994. return this.base.getOutputLength(inputLength * this.base.numComps,
  11995. alpha01);
  11996. },
  11997. isPassthrough: ColorSpace.prototype.isPassthrough,
  11998. fillRgb: ColorSpace.prototype.fillRgb,
  11999. isDefaultDecode: function IndexedCS_isDefaultDecode(decodeMap) {
  12000. // indexed color maps shouldn't be changed
  12001. return true;
  12002. },
  12003. usesZeroToOneRange: true
  12004. };
  12005. return IndexedCS;
  12006. })();
  12007. var DeviceGrayCS = (function DeviceGrayCSClosure() {
  12008. function DeviceGrayCS() {
  12009. this.name = 'DeviceGray';
  12010. this.numComps = 1;
  12011. this.defaultColor = new Float32Array([0]);
  12012. }
  12013. DeviceGrayCS.prototype = {
  12014. getRgb: ColorSpace.prototype.getRgb,
  12015. getRgbItem: function DeviceGrayCS_getRgbItem(src, srcOffset,
  12016. dest, destOffset) {
  12017. var c = (src[srcOffset] * 255) | 0;
  12018. c = c < 0 ? 0 : c > 255 ? 255 : c;
  12019. dest[destOffset] = dest[destOffset + 1] = dest[destOffset + 2] = c;
  12020. },
  12021. getRgbBuffer: function DeviceGrayCS_getRgbBuffer(src, srcOffset, count,
  12022. dest, destOffset, bits,
  12023. alpha01) {
  12024. var scale = 255 / ((1 << bits) - 1);
  12025. var j = srcOffset, q = destOffset;
  12026. for (var i = 0; i < count; ++i) {
  12027. var c = (scale * src[j++]) | 0;
  12028. dest[q++] = c;
  12029. dest[q++] = c;
  12030. dest[q++] = c;
  12031. q += alpha01;
  12032. }
  12033. },
  12034. getOutputLength: function DeviceGrayCS_getOutputLength(inputLength,
  12035. alpha01) {
  12036. return inputLength * (3 + alpha01);
  12037. },
  12038. isPassthrough: ColorSpace.prototype.isPassthrough,
  12039. fillRgb: ColorSpace.prototype.fillRgb,
  12040. isDefaultDecode: function DeviceGrayCS_isDefaultDecode(decodeMap) {
  12041. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  12042. },
  12043. usesZeroToOneRange: true
  12044. };
  12045. return DeviceGrayCS;
  12046. })();
  12047. var DeviceRgbCS = (function DeviceRgbCSClosure() {
  12048. function DeviceRgbCS() {
  12049. this.name = 'DeviceRGB';
  12050. this.numComps = 3;
  12051. this.defaultColor = new Float32Array([0, 0, 0]);
  12052. }
  12053. DeviceRgbCS.prototype = {
  12054. getRgb: ColorSpace.prototype.getRgb,
  12055. getRgbItem: function DeviceRgbCS_getRgbItem(src, srcOffset,
  12056. dest, destOffset) {
  12057. var r = (src[srcOffset] * 255) | 0;
  12058. var g = (src[srcOffset + 1] * 255) | 0;
  12059. var b = (src[srcOffset + 2] * 255) | 0;
  12060. dest[destOffset] = r < 0 ? 0 : r > 255 ? 255 : r;
  12061. dest[destOffset + 1] = g < 0 ? 0 : g > 255 ? 255 : g;
  12062. dest[destOffset + 2] = b < 0 ? 0 : b > 255 ? 255 : b;
  12063. },
  12064. getRgbBuffer: function DeviceRgbCS_getRgbBuffer(src, srcOffset, count,
  12065. dest, destOffset, bits,
  12066. alpha01) {
  12067. if (bits === 8 && alpha01 === 0) {
  12068. dest.set(src.subarray(srcOffset, srcOffset + count * 3), destOffset);
  12069. return;
  12070. }
  12071. var scale = 255 / ((1 << bits) - 1);
  12072. var j = srcOffset, q = destOffset;
  12073. for (var i = 0; i < count; ++i) {
  12074. dest[q++] = (scale * src[j++]) | 0;
  12075. dest[q++] = (scale * src[j++]) | 0;
  12076. dest[q++] = (scale * src[j++]) | 0;
  12077. q += alpha01;
  12078. }
  12079. },
  12080. getOutputLength: function DeviceRgbCS_getOutputLength(inputLength,
  12081. alpha01) {
  12082. return (inputLength * (3 + alpha01) / 3) | 0;
  12083. },
  12084. isPassthrough: function DeviceRgbCS_isPassthrough(bits) {
  12085. return bits === 8;
  12086. },
  12087. fillRgb: ColorSpace.prototype.fillRgb,
  12088. isDefaultDecode: function DeviceRgbCS_isDefaultDecode(decodeMap) {
  12089. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  12090. },
  12091. usesZeroToOneRange: true
  12092. };
  12093. return DeviceRgbCS;
  12094. })();
  12095. var DeviceCmykCS = (function DeviceCmykCSClosure() {
  12096. // The coefficients below was found using numerical analysis: the method of
  12097. // steepest descent for the sum((f_i - color_value_i)^2) for r/g/b colors,
  12098. // where color_value is the tabular value from the table of sampled RGB colors
  12099. // from CMYK US Web Coated (SWOP) colorspace, and f_i is the corresponding
  12100. // CMYK color conversion using the estimation below:
  12101. // f(A, B,.. N) = Acc+Bcm+Ccy+Dck+c+Fmm+Gmy+Hmk+Im+Jyy+Kyk+Ly+Mkk+Nk+255
  12102. function convertToRgb(src, srcOffset, srcScale, dest, destOffset) {
  12103. var c = src[srcOffset + 0] * srcScale;
  12104. var m = src[srcOffset + 1] * srcScale;
  12105. var y = src[srcOffset + 2] * srcScale;
  12106. var k = src[srcOffset + 3] * srcScale;
  12107. var r =
  12108. (c * (-4.387332384609988 * c + 54.48615194189176 * m +
  12109. 18.82290502165302 * y + 212.25662451639585 * k +
  12110. -285.2331026137004) +
  12111. m * (1.7149763477362134 * m - 5.6096736904047315 * y +
  12112. -17.873870861415444 * k - 5.497006427196366) +
  12113. y * (-2.5217340131683033 * y - 21.248923337353073 * k +
  12114. 17.5119270841813) +
  12115. k * (-21.86122147463605 * k - 189.48180835922747) + 255) | 0;
  12116. var g =
  12117. (c * (8.841041422036149 * c + 60.118027045597366 * m +
  12118. 6.871425592049007 * y + 31.159100130055922 * k +
  12119. -79.2970844816548) +
  12120. m * (-15.310361306967817 * m + 17.575251261109482 * y +
  12121. 131.35250912493976 * k - 190.9453302588951) +
  12122. y * (4.444339102852739 * y + 9.8632861493405 * k - 24.86741582555878) +
  12123. k * (-20.737325471181034 * k - 187.80453709719578) + 255) | 0;
  12124. var b =
  12125. (c * (0.8842522430003296 * c + 8.078677503112928 * m +
  12126. 30.89978309703729 * y - 0.23883238689178934 * k +
  12127. -14.183576799673286) +
  12128. m * (10.49593273432072 * m + 63.02378494754052 * y +
  12129. 50.606957656360734 * k - 112.23884253719248) +
  12130. y * (0.03296041114873217 * y + 115.60384449646641 * k +
  12131. -193.58209356861505) +
  12132. k * (-22.33816807309886 * k - 180.12613974708367) + 255) | 0;
  12133. dest[destOffset] = r > 255 ? 255 : r < 0 ? 0 : r;
  12134. dest[destOffset + 1] = g > 255 ? 255 : g < 0 ? 0 : g;
  12135. dest[destOffset + 2] = b > 255 ? 255 : b < 0 ? 0 : b;
  12136. }
  12137. function DeviceCmykCS() {
  12138. this.name = 'DeviceCMYK';
  12139. this.numComps = 4;
  12140. this.defaultColor = new Float32Array([0, 0, 0, 1]);
  12141. }
  12142. DeviceCmykCS.prototype = {
  12143. getRgb: ColorSpace.prototype.getRgb,
  12144. getRgbItem: function DeviceCmykCS_getRgbItem(src, srcOffset,
  12145. dest, destOffset) {
  12146. convertToRgb(src, srcOffset, 1, dest, destOffset);
  12147. },
  12148. getRgbBuffer: function DeviceCmykCS_getRgbBuffer(src, srcOffset, count,
  12149. dest, destOffset, bits,
  12150. alpha01) {
  12151. var scale = 1 / ((1 << bits) - 1);
  12152. for (var i = 0; i < count; i++) {
  12153. convertToRgb(src, srcOffset, scale, dest, destOffset);
  12154. srcOffset += 4;
  12155. destOffset += 3 + alpha01;
  12156. }
  12157. },
  12158. getOutputLength: function DeviceCmykCS_getOutputLength(inputLength,
  12159. alpha01) {
  12160. return (inputLength / 4 * (3 + alpha01)) | 0;
  12161. },
  12162. isPassthrough: ColorSpace.prototype.isPassthrough,
  12163. fillRgb: ColorSpace.prototype.fillRgb,
  12164. isDefaultDecode: function DeviceCmykCS_isDefaultDecode(decodeMap) {
  12165. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  12166. },
  12167. usesZeroToOneRange: true
  12168. };
  12169. return DeviceCmykCS;
  12170. })();
  12171. //
  12172. // CalGrayCS: Based on "PDF Reference, Sixth Ed", p.245
  12173. //
  12174. var CalGrayCS = (function CalGrayCSClosure() {
  12175. function CalGrayCS(whitePoint, blackPoint, gamma) {
  12176. this.name = 'CalGray';
  12177. this.numComps = 1;
  12178. this.defaultColor = new Float32Array([0]);
  12179. if (!whitePoint) {
  12180. error('WhitePoint missing - required for color space CalGray');
  12181. }
  12182. blackPoint = blackPoint || [0, 0, 0];
  12183. gamma = gamma || 1;
  12184. // Translate arguments to spec variables.
  12185. this.XW = whitePoint[0];
  12186. this.YW = whitePoint[1];
  12187. this.ZW = whitePoint[2];
  12188. this.XB = blackPoint[0];
  12189. this.YB = blackPoint[1];
  12190. this.ZB = blackPoint[2];
  12191. this.G = gamma;
  12192. // Validate variables as per spec.
  12193. if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) {
  12194. error('Invalid WhitePoint components for ' + this.name +
  12195. ', no fallback available');
  12196. }
  12197. if (this.XB < 0 || this.YB < 0 || this.ZB < 0) {
  12198. info('Invalid BlackPoint for ' + this.name + ', falling back to default');
  12199. this.XB = this.YB = this.ZB = 0;
  12200. }
  12201. if (this.XB !== 0 || this.YB !== 0 || this.ZB !== 0) {
  12202. warn(this.name + ', BlackPoint: XB: ' + this.XB + ', YB: ' + this.YB +
  12203. ', ZB: ' + this.ZB + ', only default values are supported.');
  12204. }
  12205. if (this.G < 1) {
  12206. info('Invalid Gamma: ' + this.G + ' for ' + this.name +
  12207. ', falling back to default');
  12208. this.G = 1;
  12209. }
  12210. }
  12211. function convertToRgb(cs, src, srcOffset, dest, destOffset, scale) {
  12212. // A represents a gray component of a calibrated gray space.
  12213. // A <---> AG in the spec
  12214. var A = src[srcOffset] * scale;
  12215. var AG = Math.pow(A, cs.G);
  12216. // Computes L as per spec. ( = cs.YW * AG )
  12217. // Except if other than default BlackPoint values are used.
  12218. var L = cs.YW * AG;
  12219. // http://www.poynton.com/notes/colour_and_gamma/ColorFAQ.html, Ch 4.
  12220. // Convert values to rgb range [0, 255].
  12221. var val = Math.max(295.8 * Math.pow(L, 0.333333333333333333) - 40.8, 0) | 0;
  12222. dest[destOffset] = val;
  12223. dest[destOffset + 1] = val;
  12224. dest[destOffset + 2] = val;
  12225. }
  12226. CalGrayCS.prototype = {
  12227. getRgb: ColorSpace.prototype.getRgb,
  12228. getRgbItem: function CalGrayCS_getRgbItem(src, srcOffset,
  12229. dest, destOffset) {
  12230. convertToRgb(this, src, srcOffset, dest, destOffset, 1);
  12231. },
  12232. getRgbBuffer: function CalGrayCS_getRgbBuffer(src, srcOffset, count,
  12233. dest, destOffset, bits,
  12234. alpha01) {
  12235. var scale = 1 / ((1 << bits) - 1);
  12236. for (var i = 0; i < count; ++i) {
  12237. convertToRgb(this, src, srcOffset, dest, destOffset, scale);
  12238. srcOffset += 1;
  12239. destOffset += 3 + alpha01;
  12240. }
  12241. },
  12242. getOutputLength: function CalGrayCS_getOutputLength(inputLength, alpha01) {
  12243. return inputLength * (3 + alpha01);
  12244. },
  12245. isPassthrough: ColorSpace.prototype.isPassthrough,
  12246. fillRgb: ColorSpace.prototype.fillRgb,
  12247. isDefaultDecode: function CalGrayCS_isDefaultDecode(decodeMap) {
  12248. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  12249. },
  12250. usesZeroToOneRange: true
  12251. };
  12252. return CalGrayCS;
  12253. })();
  12254. //
  12255. // CalRGBCS: Based on "PDF Reference, Sixth Ed", p.247
  12256. //
  12257. var CalRGBCS = (function CalRGBCSClosure() {
  12258. // See http://www.brucelindbloom.com/index.html?Eqn_ChromAdapt.html for these
  12259. // matrices.
  12260. var BRADFORD_SCALE_MATRIX = new Float32Array([
  12261. 0.8951, 0.2664, -0.1614,
  12262. -0.7502, 1.7135, 0.0367,
  12263. 0.0389, -0.0685, 1.0296]);
  12264. var BRADFORD_SCALE_INVERSE_MATRIX = new Float32Array([
  12265. 0.9869929, -0.1470543, 0.1599627,
  12266. 0.4323053, 0.5183603, 0.0492912,
  12267. -0.0085287, 0.0400428, 0.9684867]);
  12268. // See http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html.
  12269. var SRGB_D65_XYZ_TO_RGB_MATRIX = new Float32Array([
  12270. 3.2404542, -1.5371385, -0.4985314,
  12271. -0.9692660, 1.8760108, 0.0415560,
  12272. 0.0556434, -0.2040259, 1.0572252]);
  12273. var FLAT_WHITEPOINT_MATRIX = new Float32Array([1, 1, 1]);
  12274. var tempNormalizeMatrix = new Float32Array(3);
  12275. var tempConvertMatrix1 = new Float32Array(3);
  12276. var tempConvertMatrix2 = new Float32Array(3);
  12277. var DECODE_L_CONSTANT = Math.pow(((8 + 16) / 116), 3) / 8.0;
  12278. function CalRGBCS(whitePoint, blackPoint, gamma, matrix) {
  12279. this.name = 'CalRGB';
  12280. this.numComps = 3;
  12281. this.defaultColor = new Float32Array(3);
  12282. if (!whitePoint) {
  12283. error('WhitePoint missing - required for color space CalRGB');
  12284. }
  12285. blackPoint = blackPoint || new Float32Array(3);
  12286. gamma = gamma || new Float32Array([1, 1, 1]);
  12287. matrix = matrix || new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1]);
  12288. // Translate arguments to spec variables.
  12289. var XW = whitePoint[0];
  12290. var YW = whitePoint[1];
  12291. var ZW = whitePoint[2];
  12292. this.whitePoint = whitePoint;
  12293. var XB = blackPoint[0];
  12294. var YB = blackPoint[1];
  12295. var ZB = blackPoint[2];
  12296. this.blackPoint = blackPoint;
  12297. this.GR = gamma[0];
  12298. this.GG = gamma[1];
  12299. this.GB = gamma[2];
  12300. this.MXA = matrix[0];
  12301. this.MYA = matrix[1];
  12302. this.MZA = matrix[2];
  12303. this.MXB = matrix[3];
  12304. this.MYB = matrix[4];
  12305. this.MZB = matrix[5];
  12306. this.MXC = matrix[6];
  12307. this.MYC = matrix[7];
  12308. this.MZC = matrix[8];
  12309. // Validate variables as per spec.
  12310. if (XW < 0 || ZW < 0 || YW !== 1) {
  12311. error('Invalid WhitePoint components for ' + this.name +
  12312. ', no fallback available');
  12313. }
  12314. if (XB < 0 || YB < 0 || ZB < 0) {
  12315. info('Invalid BlackPoint for ' + this.name + ' [' + XB + ', ' + YB +
  12316. ', ' + ZB + '], falling back to default');
  12317. this.blackPoint = new Float32Array(3);
  12318. }
  12319. if (this.GR < 0 || this.GG < 0 || this.GB < 0) {
  12320. info('Invalid Gamma [' + this.GR + ', ' + this.GG + ', ' + this.GB +
  12321. '] for ' + this.name + ', falling back to default');
  12322. this.GR = this.GG = this.GB = 1;
  12323. }
  12324. if (this.MXA < 0 || this.MYA < 0 || this.MZA < 0 ||
  12325. this.MXB < 0 || this.MYB < 0 || this.MZB < 0 ||
  12326. this.MXC < 0 || this.MYC < 0 || this.MZC < 0) {
  12327. info('Invalid Matrix for ' + this.name + ' [' +
  12328. this.MXA + ', ' + this.MYA + ', ' + this.MZA +
  12329. this.MXB + ', ' + this.MYB + ', ' + this.MZB +
  12330. this.MXC + ', ' + this.MYC + ', ' + this.MZC +
  12331. '], falling back to default');
  12332. this.MXA = this.MYB = this.MZC = 1;
  12333. this.MXB = this.MYA = this.MZA = this.MXC = this.MYC = this.MZB = 0;
  12334. }
  12335. }
  12336. function matrixProduct(a, b, result) {
  12337. result[0] = a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
  12338. result[1] = a[3] * b[0] + a[4] * b[1] + a[5] * b[2];
  12339. result[2] = a[6] * b[0] + a[7] * b[1] + a[8] * b[2];
  12340. }
  12341. function convertToFlat(sourceWhitePoint, LMS, result) {
  12342. result[0] = LMS[0] * 1 / sourceWhitePoint[0];
  12343. result[1] = LMS[1] * 1 / sourceWhitePoint[1];
  12344. result[2] = LMS[2] * 1 / sourceWhitePoint[2];
  12345. }
  12346. function convertToD65(sourceWhitePoint, LMS, result) {
  12347. var D65X = 0.95047;
  12348. var D65Y = 1;
  12349. var D65Z = 1.08883;
  12350. result[0] = LMS[0] * D65X / sourceWhitePoint[0];
  12351. result[1] = LMS[1] * D65Y / sourceWhitePoint[1];
  12352. result[2] = LMS[2] * D65Z / sourceWhitePoint[2];
  12353. }
  12354. function sRGBTransferFunction(color) {
  12355. // See http://en.wikipedia.org/wiki/SRGB.
  12356. if (color <= 0.0031308){
  12357. return adjustToRange(0, 1, 12.92 * color);
  12358. }
  12359. return adjustToRange(0, 1, (1 + 0.055) * Math.pow(color, 1 / 2.4) - 0.055);
  12360. }
  12361. function adjustToRange(min, max, value) {
  12362. return Math.max(min, Math.min(max, value));
  12363. }
  12364. function decodeL(L) {
  12365. if (L < 0) {
  12366. return -decodeL(-L);
  12367. }
  12368. if (L > 8.0) {
  12369. return Math.pow(((L + 16) / 116), 3);
  12370. }
  12371. return L * DECODE_L_CONSTANT;
  12372. }
  12373. function compensateBlackPoint(sourceBlackPoint, XYZ_Flat, result) {
  12374. // In case the blackPoint is already the default blackPoint then there is
  12375. // no need to do compensation.
  12376. if (sourceBlackPoint[0] === 0 &&
  12377. sourceBlackPoint[1] === 0 &&
  12378. sourceBlackPoint[2] === 0) {
  12379. result[0] = XYZ_Flat[0];
  12380. result[1] = XYZ_Flat[1];
  12381. result[2] = XYZ_Flat[2];
  12382. return;
  12383. }
  12384. // For the blackPoint calculation details, please see
  12385. // http://www.adobe.com/content/dam/Adobe/en/devnet/photoshop/sdk/
  12386. // AdobeBPC.pdf.
  12387. // The destination blackPoint is the default blackPoint [0, 0, 0].
  12388. var zeroDecodeL = decodeL(0);
  12389. var X_DST = zeroDecodeL;
  12390. var X_SRC = decodeL(sourceBlackPoint[0]);
  12391. var Y_DST = zeroDecodeL;
  12392. var Y_SRC = decodeL(sourceBlackPoint[1]);
  12393. var Z_DST = zeroDecodeL;
  12394. var Z_SRC = decodeL(sourceBlackPoint[2]);
  12395. var X_Scale = (1 - X_DST) / (1 - X_SRC);
  12396. var X_Offset = 1 - X_Scale;
  12397. var Y_Scale = (1 - Y_DST) / (1 - Y_SRC);
  12398. var Y_Offset = 1 - Y_Scale;
  12399. var Z_Scale = (1 - Z_DST) / (1 - Z_SRC);
  12400. var Z_Offset = 1 - Z_Scale;
  12401. result[0] = XYZ_Flat[0] * X_Scale + X_Offset;
  12402. result[1] = XYZ_Flat[1] * Y_Scale + Y_Offset;
  12403. result[2] = XYZ_Flat[2] * Z_Scale + Z_Offset;
  12404. }
  12405. function normalizeWhitePointToFlat(sourceWhitePoint, XYZ_In, result) {
  12406. // In case the whitePoint is already flat then there is no need to do
  12407. // normalization.
  12408. if (sourceWhitePoint[0] === 1 && sourceWhitePoint[2] === 1) {
  12409. result[0] = XYZ_In[0];
  12410. result[1] = XYZ_In[1];
  12411. result[2] = XYZ_In[2];
  12412. return;
  12413. }
  12414. var LMS = result;
  12415. matrixProduct(BRADFORD_SCALE_MATRIX, XYZ_In, LMS);
  12416. var LMS_Flat = tempNormalizeMatrix;
  12417. convertToFlat(sourceWhitePoint, LMS, LMS_Flat);
  12418. matrixProduct(BRADFORD_SCALE_INVERSE_MATRIX, LMS_Flat, result);
  12419. }
  12420. function normalizeWhitePointToD65(sourceWhitePoint, XYZ_In, result) {
  12421. var LMS = result;
  12422. matrixProduct(BRADFORD_SCALE_MATRIX, XYZ_In, LMS);
  12423. var LMS_D65 = tempNormalizeMatrix;
  12424. convertToD65(sourceWhitePoint, LMS, LMS_D65);
  12425. matrixProduct(BRADFORD_SCALE_INVERSE_MATRIX, LMS_D65, result);
  12426. }
  12427. function convertToRgb(cs, src, srcOffset, dest, destOffset, scale) {
  12428. // A, B and C represent a red, green and blue components of a calibrated
  12429. // rgb space.
  12430. var A = adjustToRange(0, 1, src[srcOffset] * scale);
  12431. var B = adjustToRange(0, 1, src[srcOffset + 1] * scale);
  12432. var C = adjustToRange(0, 1, src[srcOffset + 2] * scale);
  12433. // A <---> AGR in the spec
  12434. // B <---> BGG in the spec
  12435. // C <---> CGB in the spec
  12436. var AGR = Math.pow(A, cs.GR);
  12437. var BGG = Math.pow(B, cs.GG);
  12438. var CGB = Math.pow(C, cs.GB);
  12439. // Computes intermediate variables L, M, N as per spec.
  12440. // To decode X, Y, Z values map L, M, N directly to them.
  12441. var X = cs.MXA * AGR + cs.MXB * BGG + cs.MXC * CGB;
  12442. var Y = cs.MYA * AGR + cs.MYB * BGG + cs.MYC * CGB;
  12443. var Z = cs.MZA * AGR + cs.MZB * BGG + cs.MZC * CGB;
  12444. // The following calculations are based on this document:
  12445. // http://www.adobe.com/content/dam/Adobe/en/devnet/photoshop/sdk/
  12446. // AdobeBPC.pdf.
  12447. var XYZ = tempConvertMatrix1;
  12448. XYZ[0] = X;
  12449. XYZ[1] = Y;
  12450. XYZ[2] = Z;
  12451. var XYZ_Flat = tempConvertMatrix2;
  12452. normalizeWhitePointToFlat(cs.whitePoint, XYZ, XYZ_Flat);
  12453. var XYZ_Black = tempConvertMatrix1;
  12454. compensateBlackPoint(cs.blackPoint, XYZ_Flat, XYZ_Black);
  12455. var XYZ_D65 = tempConvertMatrix2;
  12456. normalizeWhitePointToD65(FLAT_WHITEPOINT_MATRIX, XYZ_Black, XYZ_D65);
  12457. var SRGB = tempConvertMatrix1;
  12458. matrixProduct(SRGB_D65_XYZ_TO_RGB_MATRIX, XYZ_D65, SRGB);
  12459. var sR = sRGBTransferFunction(SRGB[0]);
  12460. var sG = sRGBTransferFunction(SRGB[1]);
  12461. var sB = sRGBTransferFunction(SRGB[2]);
  12462. // Convert the values to rgb range [0, 255].
  12463. dest[destOffset] = Math.round(sR * 255);
  12464. dest[destOffset + 1] = Math.round(sG * 255);
  12465. dest[destOffset + 2] = Math.round(sB * 255);
  12466. }
  12467. CalRGBCS.prototype = {
  12468. getRgb: function CalRGBCS_getRgb(src, srcOffset) {
  12469. var rgb = new Uint8Array(3);
  12470. this.getRgbItem(src, srcOffset, rgb, 0);
  12471. return rgb;
  12472. },
  12473. getRgbItem: function CalRGBCS_getRgbItem(src, srcOffset,
  12474. dest, destOffset) {
  12475. convertToRgb(this, src, srcOffset, dest, destOffset, 1);
  12476. },
  12477. getRgbBuffer: function CalRGBCS_getRgbBuffer(src, srcOffset, count,
  12478. dest, destOffset, bits,
  12479. alpha01) {
  12480. var scale = 1 / ((1 << bits) - 1);
  12481. for (var i = 0; i < count; ++i) {
  12482. convertToRgb(this, src, srcOffset, dest, destOffset, scale);
  12483. srcOffset += 3;
  12484. destOffset += 3 + alpha01;
  12485. }
  12486. },
  12487. getOutputLength: function CalRGBCS_getOutputLength(inputLength, alpha01) {
  12488. return (inputLength * (3 + alpha01) / 3) | 0;
  12489. },
  12490. isPassthrough: ColorSpace.prototype.isPassthrough,
  12491. fillRgb: ColorSpace.prototype.fillRgb,
  12492. isDefaultDecode: function CalRGBCS_isDefaultDecode(decodeMap) {
  12493. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  12494. },
  12495. usesZeroToOneRange: true
  12496. };
  12497. return CalRGBCS;
  12498. })();
  12499. //
  12500. // LabCS: Based on "PDF Reference, Sixth Ed", p.250
  12501. //
  12502. var LabCS = (function LabCSClosure() {
  12503. function LabCS(whitePoint, blackPoint, range) {
  12504. this.name = 'Lab';
  12505. this.numComps = 3;
  12506. this.defaultColor = new Float32Array([0, 0, 0]);
  12507. if (!whitePoint) {
  12508. error('WhitePoint missing - required for color space Lab');
  12509. }
  12510. blackPoint = blackPoint || [0, 0, 0];
  12511. range = range || [-100, 100, -100, 100];
  12512. // Translate args to spec variables
  12513. this.XW = whitePoint[0];
  12514. this.YW = whitePoint[1];
  12515. this.ZW = whitePoint[2];
  12516. this.amin = range[0];
  12517. this.amax = range[1];
  12518. this.bmin = range[2];
  12519. this.bmax = range[3];
  12520. // These are here just for completeness - the spec doesn't offer any
  12521. // formulas that use BlackPoint in Lab
  12522. this.XB = blackPoint[0];
  12523. this.YB = blackPoint[1];
  12524. this.ZB = blackPoint[2];
  12525. // Validate vars as per spec
  12526. if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) {
  12527. error('Invalid WhitePoint components, no fallback available');
  12528. }
  12529. if (this.XB < 0 || this.YB < 0 || this.ZB < 0) {
  12530. info('Invalid BlackPoint, falling back to default');
  12531. this.XB = this.YB = this.ZB = 0;
  12532. }
  12533. if (this.amin > this.amax || this.bmin > this.bmax) {
  12534. info('Invalid Range, falling back to defaults');
  12535. this.amin = -100;
  12536. this.amax = 100;
  12537. this.bmin = -100;
  12538. this.bmax = 100;
  12539. }
  12540. }
  12541. // Function g(x) from spec
  12542. function fn_g(x) {
  12543. if (x >= 6 / 29) {
  12544. return x * x * x;
  12545. } else {
  12546. return (108 / 841) * (x - 4 / 29);
  12547. }
  12548. }
  12549. function decode(value, high1, low2, high2) {
  12550. return low2 + (value) * (high2 - low2) / (high1);
  12551. }
  12552. // If decoding is needed maxVal should be 2^bits per component - 1.
  12553. function convertToRgb(cs, src, srcOffset, maxVal, dest, destOffset) {
  12554. // XXX: Lab input is in the range of [0, 100], [amin, amax], [bmin, bmax]
  12555. // not the usual [0, 1]. If a command like setFillColor is used the src
  12556. // values will already be within the correct range. However, if we are
  12557. // converting an image we have to map the values to the correct range given
  12558. // above.
  12559. // Ls,as,bs <---> L*,a*,b* in the spec
  12560. var Ls = src[srcOffset];
  12561. var as = src[srcOffset + 1];
  12562. var bs = src[srcOffset + 2];
  12563. if (maxVal !== false) {
  12564. Ls = decode(Ls, maxVal, 0, 100);
  12565. as = decode(as, maxVal, cs.amin, cs.amax);
  12566. bs = decode(bs, maxVal, cs.bmin, cs.bmax);
  12567. }
  12568. // Adjust limits of 'as' and 'bs'
  12569. as = as > cs.amax ? cs.amax : as < cs.amin ? cs.amin : as;
  12570. bs = bs > cs.bmax ? cs.bmax : bs < cs.bmin ? cs.bmin : bs;
  12571. // Computes intermediate variables X,Y,Z as per spec
  12572. var M = (Ls + 16) / 116;
  12573. var L = M + (as / 500);
  12574. var N = M - (bs / 200);
  12575. var X = cs.XW * fn_g(L);
  12576. var Y = cs.YW * fn_g(M);
  12577. var Z = cs.ZW * fn_g(N);
  12578. var r, g, b;
  12579. // Using different conversions for D50 and D65 white points,
  12580. // per http://www.color.org/srgb.pdf
  12581. if (cs.ZW < 1) {
  12582. // Assuming D50 (X=0.9642, Y=1.00, Z=0.8249)
  12583. r = X * 3.1339 + Y * -1.6170 + Z * -0.4906;
  12584. g = X * -0.9785 + Y * 1.9160 + Z * 0.0333;
  12585. b = X * 0.0720 + Y * -0.2290 + Z * 1.4057;
  12586. } else {
  12587. // Assuming D65 (X=0.9505, Y=1.00, Z=1.0888)
  12588. r = X * 3.2406 + Y * -1.5372 + Z * -0.4986;
  12589. g = X * -0.9689 + Y * 1.8758 + Z * 0.0415;
  12590. b = X * 0.0557 + Y * -0.2040 + Z * 1.0570;
  12591. }
  12592. // clamp color values to [0,1] range then convert to [0,255] range.
  12593. dest[destOffset] = r <= 0 ? 0 : r >= 1 ? 255 : Math.sqrt(r) * 255 | 0;
  12594. dest[destOffset + 1] = g <= 0 ? 0 : g >= 1 ? 255 : Math.sqrt(g) * 255 | 0;
  12595. dest[destOffset + 2] = b <= 0 ? 0 : b >= 1 ? 255 : Math.sqrt(b) * 255 | 0;
  12596. }
  12597. LabCS.prototype = {
  12598. getRgb: ColorSpace.prototype.getRgb,
  12599. getRgbItem: function LabCS_getRgbItem(src, srcOffset, dest, destOffset) {
  12600. convertToRgb(this, src, srcOffset, false, dest, destOffset);
  12601. },
  12602. getRgbBuffer: function LabCS_getRgbBuffer(src, srcOffset, count,
  12603. dest, destOffset, bits,
  12604. alpha01) {
  12605. var maxVal = (1 << bits) - 1;
  12606. for (var i = 0; i < count; i++) {
  12607. convertToRgb(this, src, srcOffset, maxVal, dest, destOffset);
  12608. srcOffset += 3;
  12609. destOffset += 3 + alpha01;
  12610. }
  12611. },
  12612. getOutputLength: function LabCS_getOutputLength(inputLength, alpha01) {
  12613. return (inputLength * (3 + alpha01) / 3) | 0;
  12614. },
  12615. isPassthrough: ColorSpace.prototype.isPassthrough,
  12616. fillRgb: ColorSpace.prototype.fillRgb,
  12617. isDefaultDecode: function LabCS_isDefaultDecode(decodeMap) {
  12618. // XXX: Decoding is handled with the lab conversion because of the strange
  12619. // ranges that are used.
  12620. return true;
  12621. },
  12622. usesZeroToOneRange: false
  12623. };
  12624. return LabCS;
  12625. })();
  12626. var ARCFourCipher = (function ARCFourCipherClosure() {
  12627. function ARCFourCipher(key) {
  12628. this.a = 0;
  12629. this.b = 0;
  12630. var s = new Uint8Array(256);
  12631. var i, j = 0, tmp, keyLength = key.length;
  12632. for (i = 0; i < 256; ++i) {
  12633. s[i] = i;
  12634. }
  12635. for (i = 0; i < 256; ++i) {
  12636. tmp = s[i];
  12637. j = (j + tmp + key[i % keyLength]) & 0xFF;
  12638. s[i] = s[j];
  12639. s[j] = tmp;
  12640. }
  12641. this.s = s;
  12642. }
  12643. ARCFourCipher.prototype = {
  12644. encryptBlock: function ARCFourCipher_encryptBlock(data) {
  12645. var i, n = data.length, tmp, tmp2;
  12646. var a = this.a, b = this.b, s = this.s;
  12647. var output = new Uint8Array(n);
  12648. for (i = 0; i < n; ++i) {
  12649. a = (a + 1) & 0xFF;
  12650. tmp = s[a];
  12651. b = (b + tmp) & 0xFF;
  12652. tmp2 = s[b];
  12653. s[a] = tmp2;
  12654. s[b] = tmp;
  12655. output[i] = data[i] ^ s[(tmp + tmp2) & 0xFF];
  12656. }
  12657. this.a = a;
  12658. this.b = b;
  12659. return output;
  12660. }
  12661. };
  12662. ARCFourCipher.prototype.decryptBlock = ARCFourCipher.prototype.encryptBlock;
  12663. return ARCFourCipher;
  12664. })();
  12665. var calculateMD5 = (function calculateMD5Closure() {
  12666. var r = new Uint8Array([
  12667. 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
  12668. 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
  12669. 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
  12670. 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]);
  12671. var k = new Int32Array([
  12672. -680876936, -389564586, 606105819, -1044525330, -176418897, 1200080426,
  12673. -1473231341, -45705983, 1770035416, -1958414417, -42063, -1990404162,
  12674. 1804603682, -40341101, -1502002290, 1236535329, -165796510, -1069501632,
  12675. 643717713, -373897302, -701558691, 38016083, -660478335, -405537848,
  12676. 568446438, -1019803690, -187363961, 1163531501, -1444681467, -51403784,
  12677. 1735328473, -1926607734, -378558, -2022574463, 1839030562, -35309556,
  12678. -1530992060, 1272893353, -155497632, -1094730640, 681279174, -358537222,
  12679. -722521979, 76029189, -640364487, -421815835, 530742520, -995338651,
  12680. -198630844, 1126891415, -1416354905, -57434055, 1700485571, -1894986606,
  12681. -1051523, -2054922799, 1873313359, -30611744, -1560198380, 1309151649,
  12682. -145523070, -1120210379, 718787259, -343485551]);
  12683. function hash(data, offset, length) {
  12684. var h0 = 1732584193, h1 = -271733879, h2 = -1732584194, h3 = 271733878;
  12685. // pre-processing
  12686. var paddedLength = (length + 72) & ~63; // data + 9 extra bytes
  12687. var padded = new Uint8Array(paddedLength);
  12688. var i, j, n;
  12689. for (i = 0; i < length; ++i) {
  12690. padded[i] = data[offset++];
  12691. }
  12692. padded[i++] = 0x80;
  12693. n = paddedLength - 8;
  12694. while (i < n) {
  12695. padded[i++] = 0;
  12696. }
  12697. padded[i++] = (length << 3) & 0xFF;
  12698. padded[i++] = (length >> 5) & 0xFF;
  12699. padded[i++] = (length >> 13) & 0xFF;
  12700. padded[i++] = (length >> 21) & 0xFF;
  12701. padded[i++] = (length >>> 29) & 0xFF;
  12702. padded[i++] = 0;
  12703. padded[i++] = 0;
  12704. padded[i++] = 0;
  12705. var w = new Int32Array(16);
  12706. for (i = 0; i < paddedLength;) {
  12707. for (j = 0; j < 16; ++j, i += 4) {
  12708. w[j] = (padded[i] | (padded[i + 1] << 8) |
  12709. (padded[i + 2] << 16) | (padded[i + 3] << 24));
  12710. }
  12711. var a = h0, b = h1, c = h2, d = h3, f, g;
  12712. for (j = 0; j < 64; ++j) {
  12713. if (j < 16) {
  12714. f = (b & c) | ((~b) & d);
  12715. g = j;
  12716. } else if (j < 32) {
  12717. f = (d & b) | ((~d) & c);
  12718. g = (5 * j + 1) & 15;
  12719. } else if (j < 48) {
  12720. f = b ^ c ^ d;
  12721. g = (3 * j + 5) & 15;
  12722. } else {
  12723. f = c ^ (b | (~d));
  12724. g = (7 * j) & 15;
  12725. }
  12726. var tmp = d, rotateArg = (a + f + k[j] + w[g]) | 0, rotate = r[j];
  12727. d = c;
  12728. c = b;
  12729. b = (b + ((rotateArg << rotate) | (rotateArg >>> (32 - rotate)))) | 0;
  12730. a = tmp;
  12731. }
  12732. h0 = (h0 + a) | 0;
  12733. h1 = (h1 + b) | 0;
  12734. h2 = (h2 + c) | 0;
  12735. h3 = (h3 + d) | 0;
  12736. }
  12737. return new Uint8Array([
  12738. h0 & 0xFF, (h0 >> 8) & 0xFF, (h0 >> 16) & 0xFF, (h0 >>> 24) & 0xFF,
  12739. h1 & 0xFF, (h1 >> 8) & 0xFF, (h1 >> 16) & 0xFF, (h1 >>> 24) & 0xFF,
  12740. h2 & 0xFF, (h2 >> 8) & 0xFF, (h2 >> 16) & 0xFF, (h2 >>> 24) & 0xFF,
  12741. h3 & 0xFF, (h3 >> 8) & 0xFF, (h3 >> 16) & 0xFF, (h3 >>> 24) & 0xFF
  12742. ]);
  12743. }
  12744. return hash;
  12745. })();
  12746. var Word64 = (function Word64Closure() {
  12747. function Word64(highInteger, lowInteger) {
  12748. this.high = highInteger | 0;
  12749. this.low = lowInteger | 0;
  12750. }
  12751. Word64.prototype = {
  12752. and: function Word64_and(word) {
  12753. this.high &= word.high;
  12754. this.low &= word.low;
  12755. },
  12756. xor: function Word64_xor(word) {
  12757. this.high ^= word.high;
  12758. this.low ^= word.low;
  12759. },
  12760. or: function Word64_or(word) {
  12761. this.high |= word.high;
  12762. this.low |= word.low;
  12763. },
  12764. shiftRight: function Word64_shiftRight(places) {
  12765. if (places >= 32) {
  12766. this.low = (this.high >>> (places - 32)) | 0;
  12767. this.high = 0;
  12768. } else {
  12769. this.low = (this.low >>> places) | (this.high << (32 - places));
  12770. this.high = (this.high >>> places) | 0;
  12771. }
  12772. },
  12773. shiftLeft: function Word64_shiftLeft(places) {
  12774. if (places >= 32) {
  12775. this.high = this.low << (places - 32);
  12776. this.low = 0;
  12777. } else {
  12778. this.high = (this.high << places) | (this.low >>> (32 - places));
  12779. this.low = this.low << places;
  12780. }
  12781. },
  12782. rotateRight: function Word64_rotateRight(places) {
  12783. var low, high;
  12784. if (places & 32) {
  12785. high = this.low;
  12786. low = this.high;
  12787. } else {
  12788. low = this.low;
  12789. high = this.high;
  12790. }
  12791. places &= 31;
  12792. this.low = (low >>> places) | (high << (32 - places));
  12793. this.high = (high >>> places) | (low << (32 - places));
  12794. },
  12795. not: function Word64_not() {
  12796. this.high = ~this.high;
  12797. this.low = ~this.low;
  12798. },
  12799. add: function Word64_add(word) {
  12800. var lowAdd = (this.low >>> 0) + (word.low >>> 0);
  12801. var highAdd = (this.high >>> 0) + (word.high >>> 0);
  12802. if (lowAdd > 0xFFFFFFFF) {
  12803. highAdd += 1;
  12804. }
  12805. this.low = lowAdd | 0;
  12806. this.high = highAdd | 0;
  12807. },
  12808. copyTo: function Word64_copyTo(bytes, offset) {
  12809. bytes[offset] = (this.high >>> 24) & 0xFF;
  12810. bytes[offset + 1] = (this.high >> 16) & 0xFF;
  12811. bytes[offset + 2] = (this.high >> 8) & 0xFF;
  12812. bytes[offset + 3] = this.high & 0xFF;
  12813. bytes[offset + 4] = (this.low >>> 24) & 0xFF;
  12814. bytes[offset + 5] = (this.low >> 16) & 0xFF;
  12815. bytes[offset + 6] = (this.low >> 8) & 0xFF;
  12816. bytes[offset + 7] = this.low & 0xFF;
  12817. },
  12818. assign: function Word64_assign(word) {
  12819. this.high = word.high;
  12820. this.low = word.low;
  12821. }
  12822. };
  12823. return Word64;
  12824. })();
  12825. var calculateSHA256 = (function calculateSHA256Closure() {
  12826. function rotr(x, n) {
  12827. return (x >>> n) | (x << 32 - n);
  12828. }
  12829. function ch(x, y, z) {
  12830. return (x & y) ^ (~x & z);
  12831. }
  12832. function maj(x, y, z) {
  12833. return (x & y) ^ (x & z) ^ (y & z);
  12834. }
  12835. function sigma(x) {
  12836. return rotr(x, 2) ^ rotr(x, 13) ^ rotr(x, 22);
  12837. }
  12838. function sigmaPrime(x) {
  12839. return rotr(x, 6) ^ rotr(x, 11) ^ rotr(x, 25);
  12840. }
  12841. function littleSigma(x) {
  12842. return rotr(x, 7) ^ rotr(x, 18) ^ x >>> 3;
  12843. }
  12844. function littleSigmaPrime(x) {
  12845. return rotr(x, 17) ^ rotr(x, 19) ^ x >>> 10;
  12846. }
  12847. var k = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
  12848. 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
  12849. 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
  12850. 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
  12851. 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
  12852. 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
  12853. 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
  12854. 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
  12855. 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
  12856. 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
  12857. 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
  12858. 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
  12859. 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
  12860. 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
  12861. 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
  12862. 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];
  12863. function hash(data, offset, length) {
  12864. // initial hash values
  12865. var h0 = 0x6a09e667, h1 = 0xbb67ae85, h2 = 0x3c6ef372,
  12866. h3 = 0xa54ff53a, h4 = 0x510e527f, h5 = 0x9b05688c,
  12867. h6 = 0x1f83d9ab, h7 = 0x5be0cd19;
  12868. // pre-processing
  12869. var paddedLength = Math.ceil((length + 9) / 64) * 64;
  12870. var padded = new Uint8Array(paddedLength);
  12871. var i, j, n;
  12872. for (i = 0; i < length; ++i) {
  12873. padded[i] = data[offset++];
  12874. }
  12875. padded[i++] = 0x80;
  12876. n = paddedLength - 8;
  12877. while (i < n) {
  12878. padded[i++] = 0;
  12879. }
  12880. padded[i++] = 0;
  12881. padded[i++] = 0;
  12882. padded[i++] = 0;
  12883. padded[i++] = (length >>> 29) & 0xFF;
  12884. padded[i++] = (length >> 21) & 0xFF;
  12885. padded[i++] = (length >> 13) & 0xFF;
  12886. padded[i++] = (length >> 5) & 0xFF;
  12887. padded[i++] = (length << 3) & 0xFF;
  12888. var w = new Uint32Array(64);
  12889. // for each 512 bit block
  12890. for (i = 0; i < paddedLength;) {
  12891. for (j = 0; j < 16; ++j) {
  12892. w[j] = (padded[i] << 24 | (padded[i + 1] << 16) |
  12893. (padded[i + 2] << 8) | (padded[i + 3]));
  12894. i += 4;
  12895. }
  12896. for (j = 16; j < 64; ++j) {
  12897. w[j] = littleSigmaPrime(w[j - 2]) + w[j - 7] +
  12898. littleSigma(w[j - 15]) + w[j - 16] | 0;
  12899. }
  12900. var a = h0, b = h1, c = h2, d = h3, e = h4,
  12901. f = h5, g = h6, h = h7, t1, t2;
  12902. for (j = 0; j < 64; ++j) {
  12903. t1 = h + sigmaPrime(e) + ch(e, f, g) + k[j] + w[j];
  12904. t2 = sigma(a) + maj(a, b, c);
  12905. h = g;
  12906. g = f;
  12907. f = e;
  12908. e = (d + t1) | 0;
  12909. d = c;
  12910. c = b;
  12911. b = a;
  12912. a = (t1 + t2) | 0;
  12913. }
  12914. h0 = (h0 + a) | 0;
  12915. h1 = (h1 + b) | 0;
  12916. h2 = (h2 + c) | 0;
  12917. h3 = (h3 + d) | 0;
  12918. h4 = (h4 + e) | 0;
  12919. h5 = (h5 + f) | 0;
  12920. h6 = (h6 + g) | 0;
  12921. h7 = (h7 + h) | 0;
  12922. }
  12923. return new Uint8Array([
  12924. (h0 >> 24) & 0xFF, (h0 >> 16) & 0xFF, (h0 >> 8) & 0xFF, (h0) & 0xFF,
  12925. (h1 >> 24) & 0xFF, (h1 >> 16) & 0xFF, (h1 >> 8) & 0xFF, (h1) & 0xFF,
  12926. (h2 >> 24) & 0xFF, (h2 >> 16) & 0xFF, (h2 >> 8) & 0xFF, (h2) & 0xFF,
  12927. (h3 >> 24) & 0xFF, (h3 >> 16) & 0xFF, (h3 >> 8) & 0xFF, (h3) & 0xFF,
  12928. (h4 >> 24) & 0xFF, (h4 >> 16) & 0xFF, (h4 >> 8) & 0xFF, (h4) & 0xFF,
  12929. (h5 >> 24) & 0xFF, (h5 >> 16) & 0xFF, (h5 >> 8) & 0xFF, (h5) & 0xFF,
  12930. (h6 >> 24) & 0xFF, (h6 >> 16) & 0xFF, (h6 >> 8) & 0xFF, (h6) & 0xFF,
  12931. (h7 >> 24) & 0xFF, (h7 >> 16) & 0xFF, (h7 >> 8) & 0xFF, (h7) & 0xFF
  12932. ]);
  12933. }
  12934. return hash;
  12935. })();
  12936. var calculateSHA512 = (function calculateSHA512Closure() {
  12937. function ch(result, x, y, z, tmp) {
  12938. result.assign(x);
  12939. result.and(y);
  12940. tmp.assign(x);
  12941. tmp.not();
  12942. tmp.and(z);
  12943. result.xor(tmp);
  12944. }
  12945. function maj(result, x, y, z, tmp) {
  12946. result.assign(x);
  12947. result.and(y);
  12948. tmp.assign(x);
  12949. tmp.and(z);
  12950. result.xor(tmp);
  12951. tmp.assign(y);
  12952. tmp.and(z);
  12953. result.xor(tmp);
  12954. }
  12955. function sigma(result, x, tmp) {
  12956. result.assign(x);
  12957. result.rotateRight(28);
  12958. tmp.assign(x);
  12959. tmp.rotateRight(34);
  12960. result.xor(tmp);
  12961. tmp.assign(x);
  12962. tmp.rotateRight(39);
  12963. result.xor(tmp);
  12964. }
  12965. function sigmaPrime(result, x, tmp) {
  12966. result.assign(x);
  12967. result.rotateRight(14);
  12968. tmp.assign(x);
  12969. tmp.rotateRight(18);
  12970. result.xor(tmp);
  12971. tmp.assign(x);
  12972. tmp.rotateRight(41);
  12973. result.xor(tmp);
  12974. }
  12975. function littleSigma(result, x, tmp) {
  12976. result.assign(x);
  12977. result.rotateRight(1);
  12978. tmp.assign(x);
  12979. tmp.rotateRight(8);
  12980. result.xor(tmp);
  12981. tmp.assign(x);
  12982. tmp.shiftRight(7);
  12983. result.xor(tmp);
  12984. }
  12985. function littleSigmaPrime(result, x, tmp) {
  12986. result.assign(x);
  12987. result.rotateRight(19);
  12988. tmp.assign(x);
  12989. tmp.rotateRight(61);
  12990. result.xor(tmp);
  12991. tmp.assign(x);
  12992. tmp.shiftRight(6);
  12993. result.xor(tmp);
  12994. }
  12995. var k = [
  12996. new Word64(0x428a2f98, 0xd728ae22), new Word64(0x71374491, 0x23ef65cd),
  12997. new Word64(0xb5c0fbcf, 0xec4d3b2f), new Word64(0xe9b5dba5, 0x8189dbbc),
  12998. new Word64(0x3956c25b, 0xf348b538), new Word64(0x59f111f1, 0xb605d019),
  12999. new Word64(0x923f82a4, 0xaf194f9b), new Word64(0xab1c5ed5, 0xda6d8118),
  13000. new Word64(0xd807aa98, 0xa3030242), new Word64(0x12835b01, 0x45706fbe),
  13001. new Word64(0x243185be, 0x4ee4b28c), new Word64(0x550c7dc3, 0xd5ffb4e2),
  13002. new Word64(0x72be5d74, 0xf27b896f), new Word64(0x80deb1fe, 0x3b1696b1),
  13003. new Word64(0x9bdc06a7, 0x25c71235), new Word64(0xc19bf174, 0xcf692694),
  13004. new Word64(0xe49b69c1, 0x9ef14ad2), new Word64(0xefbe4786, 0x384f25e3),
  13005. new Word64(0x0fc19dc6, 0x8b8cd5b5), new Word64(0x240ca1cc, 0x77ac9c65),
  13006. new Word64(0x2de92c6f, 0x592b0275), new Word64(0x4a7484aa, 0x6ea6e483),
  13007. new Word64(0x5cb0a9dc, 0xbd41fbd4), new Word64(0x76f988da, 0x831153b5),
  13008. new Word64(0x983e5152, 0xee66dfab), new Word64(0xa831c66d, 0x2db43210),
  13009. new Word64(0xb00327c8, 0x98fb213f), new Word64(0xbf597fc7, 0xbeef0ee4),
  13010. new Word64(0xc6e00bf3, 0x3da88fc2), new Word64(0xd5a79147, 0x930aa725),
  13011. new Word64(0x06ca6351, 0xe003826f), new Word64(0x14292967, 0x0a0e6e70),
  13012. new Word64(0x27b70a85, 0x46d22ffc), new Word64(0x2e1b2138, 0x5c26c926),
  13013. new Word64(0x4d2c6dfc, 0x5ac42aed), new Word64(0x53380d13, 0x9d95b3df),
  13014. new Word64(0x650a7354, 0x8baf63de), new Word64(0x766a0abb, 0x3c77b2a8),
  13015. new Word64(0x81c2c92e, 0x47edaee6), new Word64(0x92722c85, 0x1482353b),
  13016. new Word64(0xa2bfe8a1, 0x4cf10364), new Word64(0xa81a664b, 0xbc423001),
  13017. new Word64(0xc24b8b70, 0xd0f89791), new Word64(0xc76c51a3, 0x0654be30),
  13018. new Word64(0xd192e819, 0xd6ef5218), new Word64(0xd6990624, 0x5565a910),
  13019. new Word64(0xf40e3585, 0x5771202a), new Word64(0x106aa070, 0x32bbd1b8),
  13020. new Word64(0x19a4c116, 0xb8d2d0c8), new Word64(0x1e376c08, 0x5141ab53),
  13021. new Word64(0x2748774c, 0xdf8eeb99), new Word64(0x34b0bcb5, 0xe19b48a8),
  13022. new Word64(0x391c0cb3, 0xc5c95a63), new Word64(0x4ed8aa4a, 0xe3418acb),
  13023. new Word64(0x5b9cca4f, 0x7763e373), new Word64(0x682e6ff3, 0xd6b2b8a3),
  13024. new Word64(0x748f82ee, 0x5defb2fc), new Word64(0x78a5636f, 0x43172f60),
  13025. new Word64(0x84c87814, 0xa1f0ab72), new Word64(0x8cc70208, 0x1a6439ec),
  13026. new Word64(0x90befffa, 0x23631e28), new Word64(0xa4506ceb, 0xde82bde9),
  13027. new Word64(0xbef9a3f7, 0xb2c67915), new Word64(0xc67178f2, 0xe372532b),
  13028. new Word64(0xca273ece, 0xea26619c), new Word64(0xd186b8c7, 0x21c0c207),
  13029. new Word64(0xeada7dd6, 0xcde0eb1e), new Word64(0xf57d4f7f, 0xee6ed178),
  13030. new Word64(0x06f067aa, 0x72176fba), new Word64(0x0a637dc5, 0xa2c898a6),
  13031. new Word64(0x113f9804, 0xbef90dae), new Word64(0x1b710b35, 0x131c471b),
  13032. new Word64(0x28db77f5, 0x23047d84), new Word64(0x32caab7b, 0x40c72493),
  13033. new Word64(0x3c9ebe0a, 0x15c9bebc), new Word64(0x431d67c4, 0x9c100d4c),
  13034. new Word64(0x4cc5d4be, 0xcb3e42b6), new Word64(0x597f299c, 0xfc657e2a),
  13035. new Word64(0x5fcb6fab, 0x3ad6faec), new Word64(0x6c44198c, 0x4a475817)];
  13036. function hash(data, offset, length, mode384) {
  13037. mode384 = !!mode384;
  13038. // initial hash values
  13039. var h0, h1, h2, h3, h4, h5, h6, h7;
  13040. if (!mode384) {
  13041. h0 = new Word64(0x6a09e667, 0xf3bcc908);
  13042. h1 = new Word64(0xbb67ae85, 0x84caa73b);
  13043. h2 = new Word64(0x3c6ef372, 0xfe94f82b);
  13044. h3 = new Word64(0xa54ff53a, 0x5f1d36f1);
  13045. h4 = new Word64(0x510e527f, 0xade682d1);
  13046. h5 = new Word64(0x9b05688c, 0x2b3e6c1f);
  13047. h6 = new Word64(0x1f83d9ab, 0xfb41bd6b);
  13048. h7 = new Word64(0x5be0cd19, 0x137e2179);
  13049. }
  13050. else {
  13051. // SHA384 is exactly the same
  13052. // except with different starting values and a trimmed result
  13053. h0 = new Word64(0xcbbb9d5d, 0xc1059ed8);
  13054. h1 = new Word64(0x629a292a, 0x367cd507);
  13055. h2 = new Word64(0x9159015a, 0x3070dd17);
  13056. h3 = new Word64(0x152fecd8, 0xf70e5939);
  13057. h4 = new Word64(0x67332667, 0xffc00b31);
  13058. h5 = new Word64(0x8eb44a87, 0x68581511);
  13059. h6 = new Word64(0xdb0c2e0d, 0x64f98fa7);
  13060. h7 = new Word64(0x47b5481d, 0xbefa4fa4);
  13061. }
  13062. // pre-processing
  13063. var paddedLength = Math.ceil((length + 17) / 128) * 128;
  13064. var padded = new Uint8Array(paddedLength);
  13065. var i, j, n;
  13066. for (i = 0; i < length; ++i) {
  13067. padded[i] = data[offset++];
  13068. }
  13069. padded[i++] = 0x80;
  13070. n = paddedLength - 16;
  13071. while (i < n) {
  13072. padded[i++] = 0;
  13073. }
  13074. padded[i++] = 0;
  13075. padded[i++] = 0;
  13076. padded[i++] = 0;
  13077. padded[i++] = 0;
  13078. padded[i++] = 0;
  13079. padded[i++] = 0;
  13080. padded[i++] = 0;
  13081. padded[i++] = 0;
  13082. padded[i++] = 0;
  13083. padded[i++] = 0;
  13084. padded[i++] = 0;
  13085. padded[i++] = (length >>> 29) & 0xFF;
  13086. padded[i++] = (length >> 21) & 0xFF;
  13087. padded[i++] = (length >> 13) & 0xFF;
  13088. padded[i++] = (length >> 5) & 0xFF;
  13089. padded[i++] = (length << 3) & 0xFF;
  13090. var w = new Array(80);
  13091. for (i = 0; i < 80; i++) {
  13092. w[i] = new Word64(0, 0);
  13093. }
  13094. var a = new Word64(0, 0), b = new Word64(0, 0), c = new Word64(0, 0);
  13095. var d = new Word64(0, 0), e = new Word64(0, 0), f = new Word64(0, 0);
  13096. var g = new Word64(0, 0), h = new Word64(0, 0);
  13097. var t1 = new Word64(0, 0), t2 = new Word64(0, 0);
  13098. var tmp1 = new Word64(0, 0), tmp2 = new Word64(0, 0), tmp3;
  13099. // for each 1024 bit block
  13100. for (i = 0; i < paddedLength;) {
  13101. for (j = 0; j < 16; ++j) {
  13102. w[j].high = (padded[i] << 24) | (padded[i + 1] << 16) |
  13103. (padded[i + 2] << 8) | (padded[i + 3]);
  13104. w[j].low = (padded[i + 4]) << 24 | (padded[i + 5]) << 16 |
  13105. (padded[i + 6]) << 8 | (padded[i + 7]);
  13106. i += 8;
  13107. }
  13108. for (j = 16; j < 80; ++j) {
  13109. tmp3 = w[j];
  13110. littleSigmaPrime(tmp3, w[j - 2], tmp2);
  13111. tmp3.add(w[j - 7]);
  13112. littleSigma(tmp1, w[j - 15], tmp2);
  13113. tmp3.add(tmp1);
  13114. tmp3.add(w[j - 16]);
  13115. }
  13116. a.assign(h0); b.assign(h1); c.assign(h2); d.assign(h3);
  13117. e.assign(h4); f.assign(h5); g.assign(h6); h.assign(h7);
  13118. for (j = 0; j < 80; ++j) {
  13119. t1.assign(h);
  13120. sigmaPrime(tmp1, e, tmp2);
  13121. t1.add(tmp1);
  13122. ch(tmp1, e, f, g, tmp2);
  13123. t1.add(tmp1);
  13124. t1.add(k[j]);
  13125. t1.add(w[j]);
  13126. sigma(t2, a, tmp2);
  13127. maj(tmp1, a, b, c, tmp2);
  13128. t2.add(tmp1);
  13129. tmp3 = h;
  13130. h = g;
  13131. g = f;
  13132. f = e;
  13133. d.add(t1);
  13134. e = d;
  13135. d = c;
  13136. c = b;
  13137. b = a;
  13138. tmp3.assign(t1);
  13139. tmp3.add(t2);
  13140. a = tmp3;
  13141. }
  13142. h0.add(a);
  13143. h1.add(b);
  13144. h2.add(c);
  13145. h3.add(d);
  13146. h4.add(e);
  13147. h5.add(f);
  13148. h6.add(g);
  13149. h7.add(h);
  13150. }
  13151. var result;
  13152. if (!mode384) {
  13153. result = new Uint8Array(64);
  13154. h0.copyTo(result,0);
  13155. h1.copyTo(result,8);
  13156. h2.copyTo(result,16);
  13157. h3.copyTo(result,24);
  13158. h4.copyTo(result,32);
  13159. h5.copyTo(result,40);
  13160. h6.copyTo(result,48);
  13161. h7.copyTo(result,56);
  13162. }
  13163. else {
  13164. result = new Uint8Array(48);
  13165. h0.copyTo(result,0);
  13166. h1.copyTo(result,8);
  13167. h2.copyTo(result,16);
  13168. h3.copyTo(result,24);
  13169. h4.copyTo(result,32);
  13170. h5.copyTo(result,40);
  13171. }
  13172. return result;
  13173. }
  13174. return hash;
  13175. })();
  13176. var calculateSHA384 = (function calculateSHA384Closure() {
  13177. function hash(data, offset, length) {
  13178. return calculateSHA512(data, offset, length, true);
  13179. }
  13180. return hash;
  13181. })();
  13182. var NullCipher = (function NullCipherClosure() {
  13183. function NullCipher() {
  13184. }
  13185. NullCipher.prototype = {
  13186. decryptBlock: function NullCipher_decryptBlock(data) {
  13187. return data;
  13188. }
  13189. };
  13190. return NullCipher;
  13191. })();
  13192. var AES128Cipher = (function AES128CipherClosure() {
  13193. var rcon = new Uint8Array([
  13194. 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c,
  13195. 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a,
  13196. 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd,
  13197. 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
  13198. 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80,
  13199. 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6,
  13200. 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72,
  13201. 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc,
  13202. 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10,
  13203. 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e,
  13204. 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5,
  13205. 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94,
  13206. 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02,
  13207. 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d,
  13208. 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d,
  13209. 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f,
  13210. 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb,
  13211. 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c,
  13212. 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a,
  13213. 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd,
  13214. 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
  13215. 0x74, 0xe8, 0xcb, 0x8d]);
  13216. var s = new Uint8Array([
  13217. 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b,
  13218. 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0,
  13219. 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26,
  13220. 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
  13221. 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2,
  13222. 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0,
  13223. 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed,
  13224. 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
  13225. 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f,
  13226. 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5,
  13227. 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec,
  13228. 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
  13229. 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14,
  13230. 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c,
  13231. 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d,
  13232. 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
  13233. 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f,
  13234. 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e,
  13235. 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11,
  13236. 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
  13237. 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f,
  13238. 0xb0, 0x54, 0xbb, 0x16]);
  13239. var inv_s = new Uint8Array([
  13240. 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e,
  13241. 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87,
  13242. 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32,
  13243. 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
  13244. 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49,
  13245. 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16,
  13246. 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50,
  13247. 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
  13248. 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05,
  13249. 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02,
  13250. 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41,
  13251. 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
  13252. 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8,
  13253. 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89,
  13254. 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b,
  13255. 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
  13256. 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59,
  13257. 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d,
  13258. 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d,
  13259. 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
  13260. 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63,
  13261. 0x55, 0x21, 0x0c, 0x7d]);
  13262. var mixCol = new Uint8Array(256);
  13263. for (var i = 0; i < 256; i++) {
  13264. if (i < 128) {
  13265. mixCol[i] = i << 1;
  13266. } else {
  13267. mixCol[i] = (i << 1) ^ 0x1b;
  13268. }
  13269. }
  13270. var mix = new Uint32Array([
  13271. 0x00000000, 0x0e090d0b, 0x1c121a16, 0x121b171d, 0x3824342c, 0x362d3927,
  13272. 0x24362e3a, 0x2a3f2331, 0x70486858, 0x7e416553, 0x6c5a724e, 0x62537f45,
  13273. 0x486c5c74, 0x4665517f, 0x547e4662, 0x5a774b69, 0xe090d0b0, 0xee99ddbb,
  13274. 0xfc82caa6, 0xf28bc7ad, 0xd8b4e49c, 0xd6bde997, 0xc4a6fe8a, 0xcaaff381,
  13275. 0x90d8b8e8, 0x9ed1b5e3, 0x8ccaa2fe, 0x82c3aff5, 0xa8fc8cc4, 0xa6f581cf,
  13276. 0xb4ee96d2, 0xbae79bd9, 0xdb3bbb7b, 0xd532b670, 0xc729a16d, 0xc920ac66,
  13277. 0xe31f8f57, 0xed16825c, 0xff0d9541, 0xf104984a, 0xab73d323, 0xa57ade28,
  13278. 0xb761c935, 0xb968c43e, 0x9357e70f, 0x9d5eea04, 0x8f45fd19, 0x814cf012,
  13279. 0x3bab6bcb, 0x35a266c0, 0x27b971dd, 0x29b07cd6, 0x038f5fe7, 0x0d8652ec,
  13280. 0x1f9d45f1, 0x119448fa, 0x4be30393, 0x45ea0e98, 0x57f11985, 0x59f8148e,
  13281. 0x73c737bf, 0x7dce3ab4, 0x6fd52da9, 0x61dc20a2, 0xad766df6, 0xa37f60fd,
  13282. 0xb16477e0, 0xbf6d7aeb, 0x955259da, 0x9b5b54d1, 0x894043cc, 0x87494ec7,
  13283. 0xdd3e05ae, 0xd33708a5, 0xc12c1fb8, 0xcf2512b3, 0xe51a3182, 0xeb133c89,
  13284. 0xf9082b94, 0xf701269f, 0x4de6bd46, 0x43efb04d, 0x51f4a750, 0x5ffdaa5b,
  13285. 0x75c2896a, 0x7bcb8461, 0x69d0937c, 0x67d99e77, 0x3daed51e, 0x33a7d815,
  13286. 0x21bccf08, 0x2fb5c203, 0x058ae132, 0x0b83ec39, 0x1998fb24, 0x1791f62f,
  13287. 0x764dd68d, 0x7844db86, 0x6a5fcc9b, 0x6456c190, 0x4e69e2a1, 0x4060efaa,
  13288. 0x527bf8b7, 0x5c72f5bc, 0x0605bed5, 0x080cb3de, 0x1a17a4c3, 0x141ea9c8,
  13289. 0x3e218af9, 0x302887f2, 0x223390ef, 0x2c3a9de4, 0x96dd063d, 0x98d40b36,
  13290. 0x8acf1c2b, 0x84c61120, 0xaef93211, 0xa0f03f1a, 0xb2eb2807, 0xbce2250c,
  13291. 0xe6956e65, 0xe89c636e, 0xfa877473, 0xf48e7978, 0xdeb15a49, 0xd0b85742,
  13292. 0xc2a3405f, 0xccaa4d54, 0x41ecdaf7, 0x4fe5d7fc, 0x5dfec0e1, 0x53f7cdea,
  13293. 0x79c8eedb, 0x77c1e3d0, 0x65daf4cd, 0x6bd3f9c6, 0x31a4b2af, 0x3fadbfa4,
  13294. 0x2db6a8b9, 0x23bfa5b2, 0x09808683, 0x07898b88, 0x15929c95, 0x1b9b919e,
  13295. 0xa17c0a47, 0xaf75074c, 0xbd6e1051, 0xb3671d5a, 0x99583e6b, 0x97513360,
  13296. 0x854a247d, 0x8b432976, 0xd134621f, 0xdf3d6f14, 0xcd267809, 0xc32f7502,
  13297. 0xe9105633, 0xe7195b38, 0xf5024c25, 0xfb0b412e, 0x9ad7618c, 0x94de6c87,
  13298. 0x86c57b9a, 0x88cc7691, 0xa2f355a0, 0xacfa58ab, 0xbee14fb6, 0xb0e842bd,
  13299. 0xea9f09d4, 0xe49604df, 0xf68d13c2, 0xf8841ec9, 0xd2bb3df8, 0xdcb230f3,
  13300. 0xcea927ee, 0xc0a02ae5, 0x7a47b13c, 0x744ebc37, 0x6655ab2a, 0x685ca621,
  13301. 0x42638510, 0x4c6a881b, 0x5e719f06, 0x5078920d, 0x0a0fd964, 0x0406d46f,
  13302. 0x161dc372, 0x1814ce79, 0x322bed48, 0x3c22e043, 0x2e39f75e, 0x2030fa55,
  13303. 0xec9ab701, 0xe293ba0a, 0xf088ad17, 0xfe81a01c, 0xd4be832d, 0xdab78e26,
  13304. 0xc8ac993b, 0xc6a59430, 0x9cd2df59, 0x92dbd252, 0x80c0c54f, 0x8ec9c844,
  13305. 0xa4f6eb75, 0xaaffe67e, 0xb8e4f163, 0xb6edfc68, 0x0c0a67b1, 0x02036aba,
  13306. 0x10187da7, 0x1e1170ac, 0x342e539d, 0x3a275e96, 0x283c498b, 0x26354480,
  13307. 0x7c420fe9, 0x724b02e2, 0x605015ff, 0x6e5918f4, 0x44663bc5, 0x4a6f36ce,
  13308. 0x587421d3, 0x567d2cd8, 0x37a10c7a, 0x39a80171, 0x2bb3166c, 0x25ba1b67,
  13309. 0x0f853856, 0x018c355d, 0x13972240, 0x1d9e2f4b, 0x47e96422, 0x49e06929,
  13310. 0x5bfb7e34, 0x55f2733f, 0x7fcd500e, 0x71c45d05, 0x63df4a18, 0x6dd64713,
  13311. 0xd731dcca, 0xd938d1c1, 0xcb23c6dc, 0xc52acbd7, 0xef15e8e6, 0xe11ce5ed,
  13312. 0xf307f2f0, 0xfd0efffb, 0xa779b492, 0xa970b999, 0xbb6bae84, 0xb562a38f,
  13313. 0x9f5d80be, 0x91548db5, 0x834f9aa8, 0x8d4697a3]);
  13314. function expandKey128(cipherKey) {
  13315. var b = 176, result = new Uint8Array(b);
  13316. result.set(cipherKey);
  13317. for (var j = 16, i = 1; j < b; ++i) {
  13318. // RotWord
  13319. var t1 = result[j - 3], t2 = result[j - 2],
  13320. t3 = result[j - 1], t4 = result[j - 4];
  13321. // SubWord
  13322. t1 = s[t1];
  13323. t2 = s[t2];
  13324. t3 = s[t3];
  13325. t4 = s[t4];
  13326. // Rcon
  13327. t1 = t1 ^ rcon[i];
  13328. for (var n = 0; n < 4; ++n) {
  13329. result[j] = (t1 ^= result[j - 16]);
  13330. j++;
  13331. result[j] = (t2 ^= result[j - 16]);
  13332. j++;
  13333. result[j] = (t3 ^= result[j - 16]);
  13334. j++;
  13335. result[j] = (t4 ^= result[j - 16]);
  13336. j++;
  13337. }
  13338. }
  13339. return result;
  13340. }
  13341. function decrypt128(input, key) {
  13342. var state = new Uint8Array(16);
  13343. state.set(input);
  13344. var i, j, k;
  13345. var t, u, v;
  13346. // AddRoundKey
  13347. for (j = 0, k = 160; j < 16; ++j, ++k) {
  13348. state[j] ^= key[k];
  13349. }
  13350. for (i = 9; i >= 1; --i) {
  13351. // InvShiftRows
  13352. t = state[13];
  13353. state[13] = state[9];
  13354. state[9] = state[5];
  13355. state[5] = state[1];
  13356. state[1] = t;
  13357. t = state[14];
  13358. u = state[10];
  13359. state[14] = state[6];
  13360. state[10] = state[2];
  13361. state[6] = t;
  13362. state[2] = u;
  13363. t = state[15];
  13364. u = state[11];
  13365. v = state[7];
  13366. state[15] = state[3];
  13367. state[11] = t;
  13368. state[7] = u;
  13369. state[3] = v;
  13370. // InvSubBytes
  13371. for (j = 0; j < 16; ++j) {
  13372. state[j] = inv_s[state[j]];
  13373. }
  13374. // AddRoundKey
  13375. for (j = 0, k = i * 16; j < 16; ++j, ++k) {
  13376. state[j] ^= key[k];
  13377. }
  13378. // InvMixColumns
  13379. for (j = 0; j < 16; j += 4) {
  13380. var s0 = mix[state[j]], s1 = mix[state[j + 1]],
  13381. s2 = mix[state[j + 2]], s3 = mix[state[j + 3]];
  13382. t = (s0 ^ (s1 >>> 8) ^ (s1 << 24) ^ (s2 >>> 16) ^ (s2 << 16) ^
  13383. (s3 >>> 24) ^ (s3 << 8));
  13384. state[j] = (t >>> 24) & 0xFF;
  13385. state[j + 1] = (t >> 16) & 0xFF;
  13386. state[j + 2] = (t >> 8) & 0xFF;
  13387. state[j + 3] = t & 0xFF;
  13388. }
  13389. }
  13390. // InvShiftRows
  13391. t = state[13];
  13392. state[13] = state[9];
  13393. state[9] = state[5];
  13394. state[5] = state[1];
  13395. state[1] = t;
  13396. t = state[14];
  13397. u = state[10];
  13398. state[14] = state[6];
  13399. state[10] = state[2];
  13400. state[6] = t;
  13401. state[2] = u;
  13402. t = state[15];
  13403. u = state[11];
  13404. v = state[7];
  13405. state[15] = state[3];
  13406. state[11] = t;
  13407. state[7] = u;
  13408. state[3] = v;
  13409. for (j = 0; j < 16; ++j) {
  13410. // InvSubBytes
  13411. state[j] = inv_s[state[j]];
  13412. // AddRoundKey
  13413. state[j] ^= key[j];
  13414. }
  13415. return state;
  13416. }
  13417. function encrypt128(input, key) {
  13418. var t, u, v, k;
  13419. var state = new Uint8Array(16);
  13420. state.set(input);
  13421. for (j = 0; j < 16; ++j) {
  13422. // AddRoundKey
  13423. state[j] ^= key[j];
  13424. }
  13425. for (i = 1; i < 10; i++) {
  13426. //SubBytes
  13427. for (j = 0; j < 16; ++j) {
  13428. state[j] = s[state[j]];
  13429. }
  13430. //ShiftRows
  13431. v = state[1];
  13432. state[1] = state[5];
  13433. state[5] = state[9];
  13434. state[9] = state[13];
  13435. state[13] = v;
  13436. v = state[2];
  13437. u = state[6];
  13438. state[2] = state[10];
  13439. state[6] = state[14];
  13440. state[10] = v;
  13441. state[14] = u;
  13442. v = state[3];
  13443. u = state[7];
  13444. t = state[11];
  13445. state[3] = state[15];
  13446. state[7] = v;
  13447. state[11] = u;
  13448. state[15] = t;
  13449. //MixColumns
  13450. for (var j = 0; j < 16; j += 4) {
  13451. var s0 = state[j + 0], s1 = state[j + 1];
  13452. var s2 = state[j + 2], s3 = state[j + 3];
  13453. t = s0 ^ s1 ^ s2 ^ s3;
  13454. state[j + 0] ^= t ^ mixCol[s0 ^ s1];
  13455. state[j + 1] ^= t ^ mixCol[s1 ^ s2];
  13456. state[j + 2] ^= t ^ mixCol[s2 ^ s3];
  13457. state[j + 3] ^= t ^ mixCol[s3 ^ s0];
  13458. }
  13459. //AddRoundKey
  13460. for (j = 0, k = i * 16; j < 16; ++j, ++k) {
  13461. state[j] ^= key[k];
  13462. }
  13463. }
  13464. //SubBytes
  13465. for (j = 0; j < 16; ++j) {
  13466. state[j] = s[state[j]];
  13467. }
  13468. //ShiftRows
  13469. v = state[1];
  13470. state[1] = state[5];
  13471. state[5] = state[9];
  13472. state[9] = state[13];
  13473. state[13] = v;
  13474. v = state[2];
  13475. u = state[6];
  13476. state[2] = state[10];
  13477. state[6] = state[14];
  13478. state[10] = v;
  13479. state[14] = u;
  13480. v = state[3];
  13481. u = state[7];
  13482. t = state[11];
  13483. state[3] = state[15];
  13484. state[7] = v;
  13485. state[11] = u;
  13486. state[15] = t;
  13487. //AddRoundKey
  13488. for (j = 0, k = 160; j < 16; ++j, ++k) {
  13489. state[j] ^= key[k];
  13490. }
  13491. return state;
  13492. }
  13493. function AES128Cipher(key) {
  13494. this.key = expandKey128(key);
  13495. this.buffer = new Uint8Array(16);
  13496. this.bufferPosition = 0;
  13497. }
  13498. function decryptBlock2(data, finalize) {
  13499. var i, j, ii, sourceLength = data.length,
  13500. buffer = this.buffer, bufferLength = this.bufferPosition,
  13501. result = [], iv = this.iv;
  13502. for (i = 0; i < sourceLength; ++i) {
  13503. buffer[bufferLength] = data[i];
  13504. ++bufferLength;
  13505. if (bufferLength < 16) {
  13506. continue;
  13507. }
  13508. // buffer is full, decrypting
  13509. var plain = decrypt128(buffer, this.key);
  13510. // xor-ing the IV vector to get plain text
  13511. for (j = 0; j < 16; ++j) {
  13512. plain[j] ^= iv[j];
  13513. }
  13514. iv = buffer;
  13515. result.push(plain);
  13516. buffer = new Uint8Array(16);
  13517. bufferLength = 0;
  13518. }
  13519. // saving incomplete buffer
  13520. this.buffer = buffer;
  13521. this.bufferLength = bufferLength;
  13522. this.iv = iv;
  13523. if (result.length === 0) {
  13524. return new Uint8Array([]);
  13525. }
  13526. // combining plain text blocks into one
  13527. var outputLength = 16 * result.length;
  13528. if (finalize) {
  13529. // undo a padding that is described in RFC 2898
  13530. var lastBlock = result[result.length - 1];
  13531. var psLen = lastBlock[15];
  13532. if (psLen <= 16) {
  13533. for (i = 15, ii = 16 - psLen; i >= ii; --i) {
  13534. if (lastBlock[i] !== psLen) {
  13535. // Invalid padding, assume that the block has no padding.
  13536. psLen = 0;
  13537. break;
  13538. }
  13539. }
  13540. outputLength -= psLen;
  13541. result[result.length - 1] = lastBlock.subarray(0, 16 - psLen);
  13542. }
  13543. }
  13544. var output = new Uint8Array(outputLength);
  13545. for (i = 0, j = 0, ii = result.length; i < ii; ++i, j += 16) {
  13546. output.set(result[i], j);
  13547. }
  13548. return output;
  13549. }
  13550. AES128Cipher.prototype = {
  13551. decryptBlock: function AES128Cipher_decryptBlock(data, finalize) {
  13552. var i, sourceLength = data.length;
  13553. var buffer = this.buffer, bufferLength = this.bufferPosition;
  13554. // waiting for IV values -- they are at the start of the stream
  13555. for (i = 0; bufferLength < 16 && i < sourceLength; ++i, ++bufferLength) {
  13556. buffer[bufferLength] = data[i];
  13557. }
  13558. if (bufferLength < 16) {
  13559. // need more data
  13560. this.bufferLength = bufferLength;
  13561. return new Uint8Array([]);
  13562. }
  13563. this.iv = buffer;
  13564. this.buffer = new Uint8Array(16);
  13565. this.bufferLength = 0;
  13566. // starting decryption
  13567. this.decryptBlock = decryptBlock2;
  13568. return this.decryptBlock(data.subarray(16), finalize);
  13569. },
  13570. encrypt: function AES128Cipher_encrypt(data, iv) {
  13571. var i, j, ii, sourceLength = data.length,
  13572. buffer = this.buffer, bufferLength = this.bufferPosition,
  13573. result = [];
  13574. if (!iv) {
  13575. iv = new Uint8Array(16);
  13576. }
  13577. for (i = 0; i < sourceLength; ++i) {
  13578. buffer[bufferLength] = data[i];
  13579. ++bufferLength;
  13580. if (bufferLength < 16) {
  13581. continue;
  13582. }
  13583. for (j = 0; j < 16; ++j) {
  13584. buffer[j] ^= iv[j];
  13585. }
  13586. // buffer is full, encrypting
  13587. var cipher = encrypt128(buffer, this.key);
  13588. iv = cipher;
  13589. result.push(cipher);
  13590. buffer = new Uint8Array(16);
  13591. bufferLength = 0;
  13592. }
  13593. // saving incomplete buffer
  13594. this.buffer = buffer;
  13595. this.bufferLength = bufferLength;
  13596. this.iv = iv;
  13597. if (result.length === 0) {
  13598. return new Uint8Array([]);
  13599. }
  13600. // combining plain text blocks into one
  13601. var outputLength = 16 * result.length;
  13602. var output = new Uint8Array(outputLength);
  13603. for (i = 0, j = 0, ii = result.length; i < ii; ++i, j += 16) {
  13604. output.set(result[i], j);
  13605. }
  13606. return output;
  13607. }
  13608. };
  13609. return AES128Cipher;
  13610. })();
  13611. var AES256Cipher = (function AES256CipherClosure() {
  13612. var rcon = new Uint8Array([
  13613. 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c,
  13614. 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a,
  13615. 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd,
  13616. 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
  13617. 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80,
  13618. 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6,
  13619. 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72,
  13620. 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc,
  13621. 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10,
  13622. 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e,
  13623. 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5,
  13624. 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94,
  13625. 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02,
  13626. 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d,
  13627. 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d,
  13628. 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f,
  13629. 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb,
  13630. 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c,
  13631. 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a,
  13632. 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd,
  13633. 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
  13634. 0x74, 0xe8, 0xcb, 0x8d]);
  13635. var s = new Uint8Array([
  13636. 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b,
  13637. 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0,
  13638. 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26,
  13639. 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
  13640. 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2,
  13641. 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0,
  13642. 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed,
  13643. 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
  13644. 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f,
  13645. 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5,
  13646. 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec,
  13647. 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
  13648. 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14,
  13649. 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c,
  13650. 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d,
  13651. 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
  13652. 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f,
  13653. 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e,
  13654. 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11,
  13655. 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
  13656. 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f,
  13657. 0xb0, 0x54, 0xbb, 0x16]);
  13658. var inv_s = new Uint8Array([
  13659. 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e,
  13660. 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87,
  13661. 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32,
  13662. 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
  13663. 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49,
  13664. 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16,
  13665. 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50,
  13666. 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
  13667. 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05,
  13668. 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02,
  13669. 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41,
  13670. 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
  13671. 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8,
  13672. 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89,
  13673. 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b,
  13674. 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
  13675. 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59,
  13676. 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d,
  13677. 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d,
  13678. 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
  13679. 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63,
  13680. 0x55, 0x21, 0x0c, 0x7d]);
  13681. var mixCol = new Uint8Array(256);
  13682. for (var i = 0; i < 256; i++) {
  13683. if (i < 128) {
  13684. mixCol[i] = i << 1;
  13685. } else {
  13686. mixCol[i] = (i << 1) ^ 0x1b;
  13687. }
  13688. }
  13689. var mix = new Uint32Array([
  13690. 0x00000000, 0x0e090d0b, 0x1c121a16, 0x121b171d, 0x3824342c, 0x362d3927,
  13691. 0x24362e3a, 0x2a3f2331, 0x70486858, 0x7e416553, 0x6c5a724e, 0x62537f45,
  13692. 0x486c5c74, 0x4665517f, 0x547e4662, 0x5a774b69, 0xe090d0b0, 0xee99ddbb,
  13693. 0xfc82caa6, 0xf28bc7ad, 0xd8b4e49c, 0xd6bde997, 0xc4a6fe8a, 0xcaaff381,
  13694. 0x90d8b8e8, 0x9ed1b5e3, 0x8ccaa2fe, 0x82c3aff5, 0xa8fc8cc4, 0xa6f581cf,
  13695. 0xb4ee96d2, 0xbae79bd9, 0xdb3bbb7b, 0xd532b670, 0xc729a16d, 0xc920ac66,
  13696. 0xe31f8f57, 0xed16825c, 0xff0d9541, 0xf104984a, 0xab73d323, 0xa57ade28,
  13697. 0xb761c935, 0xb968c43e, 0x9357e70f, 0x9d5eea04, 0x8f45fd19, 0x814cf012,
  13698. 0x3bab6bcb, 0x35a266c0, 0x27b971dd, 0x29b07cd6, 0x038f5fe7, 0x0d8652ec,
  13699. 0x1f9d45f1, 0x119448fa, 0x4be30393, 0x45ea0e98, 0x57f11985, 0x59f8148e,
  13700. 0x73c737bf, 0x7dce3ab4, 0x6fd52da9, 0x61dc20a2, 0xad766df6, 0xa37f60fd,
  13701. 0xb16477e0, 0xbf6d7aeb, 0x955259da, 0x9b5b54d1, 0x894043cc, 0x87494ec7,
  13702. 0xdd3e05ae, 0xd33708a5, 0xc12c1fb8, 0xcf2512b3, 0xe51a3182, 0xeb133c89,
  13703. 0xf9082b94, 0xf701269f, 0x4de6bd46, 0x43efb04d, 0x51f4a750, 0x5ffdaa5b,
  13704. 0x75c2896a, 0x7bcb8461, 0x69d0937c, 0x67d99e77, 0x3daed51e, 0x33a7d815,
  13705. 0x21bccf08, 0x2fb5c203, 0x058ae132, 0x0b83ec39, 0x1998fb24, 0x1791f62f,
  13706. 0x764dd68d, 0x7844db86, 0x6a5fcc9b, 0x6456c190, 0x4e69e2a1, 0x4060efaa,
  13707. 0x527bf8b7, 0x5c72f5bc, 0x0605bed5, 0x080cb3de, 0x1a17a4c3, 0x141ea9c8,
  13708. 0x3e218af9, 0x302887f2, 0x223390ef, 0x2c3a9de4, 0x96dd063d, 0x98d40b36,
  13709. 0x8acf1c2b, 0x84c61120, 0xaef93211, 0xa0f03f1a, 0xb2eb2807, 0xbce2250c,
  13710. 0xe6956e65, 0xe89c636e, 0xfa877473, 0xf48e7978, 0xdeb15a49, 0xd0b85742,
  13711. 0xc2a3405f, 0xccaa4d54, 0x41ecdaf7, 0x4fe5d7fc, 0x5dfec0e1, 0x53f7cdea,
  13712. 0x79c8eedb, 0x77c1e3d0, 0x65daf4cd, 0x6bd3f9c6, 0x31a4b2af, 0x3fadbfa4,
  13713. 0x2db6a8b9, 0x23bfa5b2, 0x09808683, 0x07898b88, 0x15929c95, 0x1b9b919e,
  13714. 0xa17c0a47, 0xaf75074c, 0xbd6e1051, 0xb3671d5a, 0x99583e6b, 0x97513360,
  13715. 0x854a247d, 0x8b432976, 0xd134621f, 0xdf3d6f14, 0xcd267809, 0xc32f7502,
  13716. 0xe9105633, 0xe7195b38, 0xf5024c25, 0xfb0b412e, 0x9ad7618c, 0x94de6c87,
  13717. 0x86c57b9a, 0x88cc7691, 0xa2f355a0, 0xacfa58ab, 0xbee14fb6, 0xb0e842bd,
  13718. 0xea9f09d4, 0xe49604df, 0xf68d13c2, 0xf8841ec9, 0xd2bb3df8, 0xdcb230f3,
  13719. 0xcea927ee, 0xc0a02ae5, 0x7a47b13c, 0x744ebc37, 0x6655ab2a, 0x685ca621,
  13720. 0x42638510, 0x4c6a881b, 0x5e719f06, 0x5078920d, 0x0a0fd964, 0x0406d46f,
  13721. 0x161dc372, 0x1814ce79, 0x322bed48, 0x3c22e043, 0x2e39f75e, 0x2030fa55,
  13722. 0xec9ab701, 0xe293ba0a, 0xf088ad17, 0xfe81a01c, 0xd4be832d, 0xdab78e26,
  13723. 0xc8ac993b, 0xc6a59430, 0x9cd2df59, 0x92dbd252, 0x80c0c54f, 0x8ec9c844,
  13724. 0xa4f6eb75, 0xaaffe67e, 0xb8e4f163, 0xb6edfc68, 0x0c0a67b1, 0x02036aba,
  13725. 0x10187da7, 0x1e1170ac, 0x342e539d, 0x3a275e96, 0x283c498b, 0x26354480,
  13726. 0x7c420fe9, 0x724b02e2, 0x605015ff, 0x6e5918f4, 0x44663bc5, 0x4a6f36ce,
  13727. 0x587421d3, 0x567d2cd8, 0x37a10c7a, 0x39a80171, 0x2bb3166c, 0x25ba1b67,
  13728. 0x0f853856, 0x018c355d, 0x13972240, 0x1d9e2f4b, 0x47e96422, 0x49e06929,
  13729. 0x5bfb7e34, 0x55f2733f, 0x7fcd500e, 0x71c45d05, 0x63df4a18, 0x6dd64713,
  13730. 0xd731dcca, 0xd938d1c1, 0xcb23c6dc, 0xc52acbd7, 0xef15e8e6, 0xe11ce5ed,
  13731. 0xf307f2f0, 0xfd0efffb, 0xa779b492, 0xa970b999, 0xbb6bae84, 0xb562a38f,
  13732. 0x9f5d80be, 0x91548db5, 0x834f9aa8, 0x8d4697a3]);
  13733. function expandKey256(cipherKey) {
  13734. var b = 240, result = new Uint8Array(b);
  13735. var r = 1;
  13736. result.set(cipherKey);
  13737. for (var j = 32, i = 1; j < b; ++i) {
  13738. if (j % 32 === 16) {
  13739. t1 = s[t1];
  13740. t2 = s[t2];
  13741. t3 = s[t3];
  13742. t4 = s[t4];
  13743. } else if (j % 32 === 0) {
  13744. // RotWord
  13745. var t1 = result[j - 3], t2 = result[j - 2],
  13746. t3 = result[j - 1], t4 = result[j - 4];
  13747. // SubWord
  13748. t1 = s[t1];
  13749. t2 = s[t2];
  13750. t3 = s[t3];
  13751. t4 = s[t4];
  13752. // Rcon
  13753. t1 = t1 ^ r;
  13754. if ((r <<= 1) >= 256) {
  13755. r = (r ^ 0x1b) & 0xFF;
  13756. }
  13757. }
  13758. for (var n = 0; n < 4; ++n) {
  13759. result[j] = (t1 ^= result[j - 32]);
  13760. j++;
  13761. result[j] = (t2 ^= result[j - 32]);
  13762. j++;
  13763. result[j] = (t3 ^= result[j - 32]);
  13764. j++;
  13765. result[j] = (t4 ^= result[j - 32]);
  13766. j++;
  13767. }
  13768. }
  13769. return result;
  13770. }
  13771. function decrypt256(input, key) {
  13772. var state = new Uint8Array(16);
  13773. state.set(input);
  13774. var i, j, k;
  13775. var t, u, v;
  13776. // AddRoundKey
  13777. for (j = 0, k = 224; j < 16; ++j, ++k) {
  13778. state[j] ^= key[k];
  13779. }
  13780. for (i = 13; i >= 1; --i) {
  13781. // InvShiftRows
  13782. t = state[13];
  13783. state[13] = state[9];
  13784. state[9] = state[5];
  13785. state[5] = state[1];
  13786. state[1] = t;
  13787. t = state[14];
  13788. u = state[10];
  13789. state[14] = state[6];
  13790. state[10] = state[2];
  13791. state[6] = t;
  13792. state[2] = u;
  13793. t = state[15];
  13794. u = state[11];
  13795. v = state[7];
  13796. state[15] = state[3];
  13797. state[11] = t;
  13798. state[7] = u;
  13799. state[3] = v;
  13800. // InvSubBytes
  13801. for (j = 0; j < 16; ++j) {
  13802. state[j] = inv_s[state[j]];
  13803. }
  13804. // AddRoundKey
  13805. for (j = 0, k = i * 16; j < 16; ++j, ++k) {
  13806. state[j] ^= key[k];
  13807. }
  13808. // InvMixColumns
  13809. for (j = 0; j < 16; j += 4) {
  13810. var s0 = mix[state[j]], s1 = mix[state[j + 1]],
  13811. s2 = mix[state[j + 2]], s3 = mix[state[j + 3]];
  13812. t = (s0 ^ (s1 >>> 8) ^ (s1 << 24) ^ (s2 >>> 16) ^ (s2 << 16) ^
  13813. (s3 >>> 24) ^ (s3 << 8));
  13814. state[j] = (t >>> 24) & 0xFF;
  13815. state[j + 1] = (t >> 16) & 0xFF;
  13816. state[j + 2] = (t >> 8) & 0xFF;
  13817. state[j + 3] = t & 0xFF;
  13818. }
  13819. }
  13820. // InvShiftRows
  13821. t = state[13];
  13822. state[13] = state[9];
  13823. state[9] = state[5];
  13824. state[5] = state[1];
  13825. state[1] = t;
  13826. t = state[14];
  13827. u = state[10];
  13828. state[14] = state[6];
  13829. state[10] = state[2];
  13830. state[6] = t;
  13831. state[2] = u;
  13832. t = state[15];
  13833. u = state[11];
  13834. v = state[7];
  13835. state[15] = state[3];
  13836. state[11] = t;
  13837. state[7] = u;
  13838. state[3] = v;
  13839. for (j = 0; j < 16; ++j) {
  13840. // InvSubBytes
  13841. state[j] = inv_s[state[j]];
  13842. // AddRoundKey
  13843. state[j] ^= key[j];
  13844. }
  13845. return state;
  13846. }
  13847. function encrypt256(input, key) {
  13848. var t, u, v, k;
  13849. var state = new Uint8Array(16);
  13850. state.set(input);
  13851. for (j = 0; j < 16; ++j) {
  13852. // AddRoundKey
  13853. state[j] ^= key[j];
  13854. }
  13855. for (i = 1; i < 14; i++) {
  13856. //SubBytes
  13857. for (j = 0; j < 16; ++j) {
  13858. state[j] = s[state[j]];
  13859. }
  13860. //ShiftRows
  13861. v = state[1];
  13862. state[1] = state[5];
  13863. state[5] = state[9];
  13864. state[9] = state[13];
  13865. state[13] = v;
  13866. v = state[2];
  13867. u = state[6];
  13868. state[2] = state[10];
  13869. state[6] = state[14];
  13870. state[10] = v;
  13871. state[14] = u;
  13872. v = state[3];
  13873. u = state[7];
  13874. t = state[11];
  13875. state[3] = state[15];
  13876. state[7] = v;
  13877. state[11] = u;
  13878. state[15] = t;
  13879. //MixColumns
  13880. for (var j = 0; j < 16; j += 4) {
  13881. var s0 = state[j + 0], s1 = state[j + 1];
  13882. var s2 = state[j + 2], s3 = state[j + 3];
  13883. t = s0 ^ s1 ^ s2 ^ s3;
  13884. state[j + 0] ^= t ^ mixCol[s0 ^ s1];
  13885. state[j + 1] ^= t ^ mixCol[s1 ^ s2];
  13886. state[j + 2] ^= t ^ mixCol[s2 ^ s3];
  13887. state[j + 3] ^= t ^ mixCol[s3 ^ s0];
  13888. }
  13889. //AddRoundKey
  13890. for (j = 0, k = i * 16; j < 16; ++j, ++k) {
  13891. state[j] ^= key[k];
  13892. }
  13893. }
  13894. //SubBytes
  13895. for (j = 0; j < 16; ++j) {
  13896. state[j] = s[state[j]];
  13897. }
  13898. //ShiftRows
  13899. v = state[1];
  13900. state[1] = state[5];
  13901. state[5] = state[9];
  13902. state[9] = state[13];
  13903. state[13] = v;
  13904. v = state[2];
  13905. u = state[6];
  13906. state[2] = state[10];
  13907. state[6] = state[14];
  13908. state[10] = v;
  13909. state[14] = u;
  13910. v = state[3];
  13911. u = state[7];
  13912. t = state[11];
  13913. state[3] = state[15];
  13914. state[7] = v;
  13915. state[11] = u;
  13916. state[15] = t;
  13917. //AddRoundKey
  13918. for (j = 0, k = 224; j < 16; ++j, ++k) {
  13919. state[j] ^= key[k];
  13920. }
  13921. return state;
  13922. }
  13923. function AES256Cipher(key) {
  13924. this.key = expandKey256(key);
  13925. this.buffer = new Uint8Array(16);
  13926. this.bufferPosition = 0;
  13927. }
  13928. function decryptBlock2(data, finalize) {
  13929. var i, j, ii, sourceLength = data.length,
  13930. buffer = this.buffer, bufferLength = this.bufferPosition,
  13931. result = [], iv = this.iv;
  13932. for (i = 0; i < sourceLength; ++i) {
  13933. buffer[bufferLength] = data[i];
  13934. ++bufferLength;
  13935. if (bufferLength < 16) {
  13936. continue;
  13937. }
  13938. // buffer is full, decrypting
  13939. var plain = decrypt256(buffer, this.key);
  13940. // xor-ing the IV vector to get plain text
  13941. for (j = 0; j < 16; ++j) {
  13942. plain[j] ^= iv[j];
  13943. }
  13944. iv = buffer;
  13945. result.push(plain);
  13946. buffer = new Uint8Array(16);
  13947. bufferLength = 0;
  13948. }
  13949. // saving incomplete buffer
  13950. this.buffer = buffer;
  13951. this.bufferLength = bufferLength;
  13952. this.iv = iv;
  13953. if (result.length === 0) {
  13954. return new Uint8Array([]);
  13955. }
  13956. // combining plain text blocks into one
  13957. var outputLength = 16 * result.length;
  13958. if (finalize) {
  13959. // undo a padding that is described in RFC 2898
  13960. var lastBlock = result[result.length - 1];
  13961. var psLen = lastBlock[15];
  13962. if (psLen <= 16) {
  13963. for (i = 15, ii = 16 - psLen; i >= ii; --i) {
  13964. if (lastBlock[i] !== psLen) {
  13965. // Invalid padding, assume that the block has no padding.
  13966. psLen = 0;
  13967. break;
  13968. }
  13969. }
  13970. outputLength -= psLen;
  13971. result[result.length - 1] = lastBlock.subarray(0, 16 - psLen);
  13972. }
  13973. }
  13974. var output = new Uint8Array(outputLength);
  13975. for (i = 0, j = 0, ii = result.length; i < ii; ++i, j += 16) {
  13976. output.set(result[i], j);
  13977. }
  13978. return output;
  13979. }
  13980. AES256Cipher.prototype = {
  13981. decryptBlock: function AES256Cipher_decryptBlock(data, finalize, iv) {
  13982. var i, sourceLength = data.length;
  13983. var buffer = this.buffer, bufferLength = this.bufferPosition;
  13984. // if not supplied an IV wait for IV values
  13985. // they are at the start of the stream
  13986. if (iv) {
  13987. this.iv = iv;
  13988. } else {
  13989. for (i = 0; bufferLength < 16 &&
  13990. i < sourceLength; ++i, ++bufferLength) {
  13991. buffer[bufferLength] = data[i];
  13992. }
  13993. if (bufferLength < 16) {
  13994. //need more data
  13995. this.bufferLength = bufferLength;
  13996. return new Uint8Array([]);
  13997. }
  13998. this.iv = buffer;
  13999. data = data.subarray(16);
  14000. }
  14001. this.buffer = new Uint8Array(16);
  14002. this.bufferLength = 0;
  14003. // starting decryption
  14004. this.decryptBlock = decryptBlock2;
  14005. return this.decryptBlock(data, finalize);
  14006. },
  14007. encrypt: function AES256Cipher_encrypt(data, iv) {
  14008. var i, j, ii, sourceLength = data.length,
  14009. buffer = this.buffer, bufferLength = this.bufferPosition,
  14010. result = [];
  14011. if (!iv) {
  14012. iv = new Uint8Array(16);
  14013. }
  14014. for (i = 0; i < sourceLength; ++i) {
  14015. buffer[bufferLength] = data[i];
  14016. ++bufferLength;
  14017. if (bufferLength < 16) {
  14018. continue;
  14019. }
  14020. for (j = 0; j < 16; ++j) {
  14021. buffer[j] ^= iv[j];
  14022. }
  14023. // buffer is full, encrypting
  14024. var cipher = encrypt256(buffer, this.key);
  14025. this.iv = cipher;
  14026. result.push(cipher);
  14027. buffer = new Uint8Array(16);
  14028. bufferLength = 0;
  14029. }
  14030. // saving incomplete buffer
  14031. this.buffer = buffer;
  14032. this.bufferLength = bufferLength;
  14033. this.iv = iv;
  14034. if (result.length === 0) {
  14035. return new Uint8Array([]);
  14036. }
  14037. // combining plain text blocks into one
  14038. var outputLength = 16 * result.length;
  14039. var output = new Uint8Array(outputLength);
  14040. for (i = 0, j = 0, ii = result.length; i < ii; ++i, j += 16) {
  14041. output.set(result[i], j);
  14042. }
  14043. return output;
  14044. }
  14045. };
  14046. return AES256Cipher;
  14047. })();
  14048. var PDF17 = (function PDF17Closure() {
  14049. function compareByteArrays(array1, array2) {
  14050. if (array1.length !== array2.length) {
  14051. return false;
  14052. }
  14053. for (var i = 0; i < array1.length; i++) {
  14054. if (array1[i] !== array2[i]) {
  14055. return false;
  14056. }
  14057. }
  14058. return true;
  14059. }
  14060. function PDF17() {
  14061. }
  14062. PDF17.prototype = {
  14063. checkOwnerPassword: function PDF17_checkOwnerPassword(password,
  14064. ownerValidationSalt,
  14065. userBytes,
  14066. ownerPassword) {
  14067. var hashData = new Uint8Array(password.length + 56);
  14068. hashData.set(password, 0);
  14069. hashData.set(ownerValidationSalt, password.length);
  14070. hashData.set(userBytes, password.length + ownerValidationSalt.length);
  14071. var result = calculateSHA256(hashData, 0, hashData.length);
  14072. return compareByteArrays(result, ownerPassword);
  14073. },
  14074. checkUserPassword: function PDF17_checkUserPassword(password,
  14075. userValidationSalt,
  14076. userPassword) {
  14077. var hashData = new Uint8Array(password.length + 8);
  14078. hashData.set(password, 0);
  14079. hashData.set(userValidationSalt, password.length);
  14080. var result = calculateSHA256(hashData, 0, hashData.length);
  14081. return compareByteArrays(result, userPassword);
  14082. },
  14083. getOwnerKey: function PDF17_getOwnerKey(password, ownerKeySalt, userBytes,
  14084. ownerEncryption) {
  14085. var hashData = new Uint8Array(password.length + 56);
  14086. hashData.set(password, 0);
  14087. hashData.set(ownerKeySalt, password.length);
  14088. hashData.set(userBytes, password.length + ownerKeySalt.length);
  14089. var key = calculateSHA256(hashData, 0, hashData.length);
  14090. var cipher = new AES256Cipher(key);
  14091. return cipher.decryptBlock(ownerEncryption,
  14092. false,
  14093. new Uint8Array(16));
  14094. },
  14095. getUserKey: function PDF17_getUserKey(password, userKeySalt,
  14096. userEncryption) {
  14097. var hashData = new Uint8Array(password.length + 8);
  14098. hashData.set(password, 0);
  14099. hashData.set(userKeySalt, password.length);
  14100. //key is the decryption key for the UE string
  14101. var key = calculateSHA256(hashData, 0, hashData.length);
  14102. var cipher = new AES256Cipher(key);
  14103. return cipher.decryptBlock(userEncryption,
  14104. false,
  14105. new Uint8Array(16));
  14106. }
  14107. };
  14108. return PDF17;
  14109. })();
  14110. var PDF20 = (function PDF20Closure() {
  14111. function concatArrays(array1, array2) {
  14112. var t = new Uint8Array(array1.length + array2.length);
  14113. t.set(array1, 0);
  14114. t.set(array2, array1.length);
  14115. return t;
  14116. }
  14117. function calculatePDF20Hash(password, input, userBytes) {
  14118. //This refers to Algorithm 2.B as defined in ISO 32000-2
  14119. var k = calculateSHA256(input, 0, input.length).subarray(0, 32);
  14120. var e = [0];
  14121. var i = 0;
  14122. while (i < 64 || e[e.length - 1] > i - 32) {
  14123. var arrayLength = password.length + k.length + userBytes.length;
  14124. var k1 = new Uint8Array(arrayLength * 64);
  14125. var array = concatArrays(password, k);
  14126. array = concatArrays(array, userBytes);
  14127. for (var j = 0, pos = 0; j < 64; j++, pos += arrayLength) {
  14128. k1.set(array, pos);
  14129. }
  14130. //AES128 CBC NO PADDING with
  14131. //first 16 bytes of k as the key and the second 16 as the iv.
  14132. var cipher = new AES128Cipher(k.subarray(0, 16));
  14133. e = cipher.encrypt(k1, k.subarray(16, 32));
  14134. //Now we have to take the first 16 bytes of an unsigned
  14135. //big endian integer... and compute the remainder
  14136. //modulo 3.... That is a fairly large number and
  14137. //JavaScript isn't going to handle that well...
  14138. //So we're using a trick that allows us to perform
  14139. //modulo math byte by byte
  14140. var remainder = 0;
  14141. for (var z = 0; z < 16; z++) {
  14142. remainder *= (256 % 3);
  14143. remainder %= 3;
  14144. remainder += ((e[z] >>> 0) % 3);
  14145. remainder %= 3;
  14146. }
  14147. if (remainder === 0) {
  14148. k = calculateSHA256(e, 0, e.length);
  14149. }
  14150. else if (remainder === 1) {
  14151. k = calculateSHA384(e, 0, e.length);
  14152. }
  14153. else if (remainder === 2) {
  14154. k = calculateSHA512(e, 0, e.length);
  14155. }
  14156. i++;
  14157. }
  14158. return k.subarray(0, 32);
  14159. }
  14160. function PDF20() {
  14161. }
  14162. function compareByteArrays(array1, array2) {
  14163. if (array1.length !== array2.length) {
  14164. return false;
  14165. }
  14166. for (var i = 0; i < array1.length; i++) {
  14167. if (array1[i] !== array2[i]) {
  14168. return false;
  14169. }
  14170. }
  14171. return true;
  14172. }
  14173. PDF20.prototype = {
  14174. hash: function PDF20_hash(password, concatBytes, userBytes) {
  14175. return calculatePDF20Hash(password, concatBytes, userBytes);
  14176. },
  14177. checkOwnerPassword: function PDF20_checkOwnerPassword(password,
  14178. ownerValidationSalt,
  14179. userBytes,
  14180. ownerPassword) {
  14181. var hashData = new Uint8Array(password.length + 56);
  14182. hashData.set(password, 0);
  14183. hashData.set(ownerValidationSalt, password.length);
  14184. hashData.set(userBytes, password.length + ownerValidationSalt.length);
  14185. var result = calculatePDF20Hash(password, hashData, userBytes);
  14186. return compareByteArrays(result, ownerPassword);
  14187. },
  14188. checkUserPassword: function PDF20_checkUserPassword(password,
  14189. userValidationSalt,
  14190. userPassword) {
  14191. var hashData = new Uint8Array(password.length + 8);
  14192. hashData.set(password, 0);
  14193. hashData.set(userValidationSalt, password.length);
  14194. var result = calculatePDF20Hash(password, hashData, []);
  14195. return compareByteArrays(result, userPassword);
  14196. },
  14197. getOwnerKey: function PDF20_getOwnerKey(password, ownerKeySalt, userBytes,
  14198. ownerEncryption) {
  14199. var hashData = new Uint8Array(password.length + 56);
  14200. hashData.set(password, 0);
  14201. hashData.set(ownerKeySalt, password.length);
  14202. hashData.set(userBytes, password.length + ownerKeySalt.length);
  14203. var key = calculatePDF20Hash(password, hashData, userBytes);
  14204. var cipher = new AES256Cipher(key);
  14205. return cipher.decryptBlock(ownerEncryption,
  14206. false,
  14207. new Uint8Array(16));
  14208. },
  14209. getUserKey: function PDF20_getUserKey(password, userKeySalt,
  14210. userEncryption) {
  14211. var hashData = new Uint8Array(password.length + 8);
  14212. hashData.set(password, 0);
  14213. hashData.set(userKeySalt, password.length);
  14214. //key is the decryption key for the UE string
  14215. var key = calculatePDF20Hash(password, hashData, []);
  14216. var cipher = new AES256Cipher(key);
  14217. return cipher.decryptBlock(userEncryption,
  14218. false,
  14219. new Uint8Array(16));
  14220. }
  14221. };
  14222. return PDF20;
  14223. })();
  14224. var CipherTransform = (function CipherTransformClosure() {
  14225. function CipherTransform(stringCipherConstructor, streamCipherConstructor) {
  14226. this.stringCipherConstructor = stringCipherConstructor;
  14227. this.streamCipherConstructor = streamCipherConstructor;
  14228. }
  14229. CipherTransform.prototype = {
  14230. createStream: function CipherTransform_createStream(stream, length) {
  14231. var cipher = new this.streamCipherConstructor();
  14232. return new DecryptStream(stream, length,
  14233. function cipherTransformDecryptStream(data, finalize) {
  14234. return cipher.decryptBlock(data, finalize);
  14235. }
  14236. );
  14237. },
  14238. decryptString: function CipherTransform_decryptString(s) {
  14239. var cipher = new this.stringCipherConstructor();
  14240. var data = stringToBytes(s);
  14241. data = cipher.decryptBlock(data, true);
  14242. return bytesToString(data);
  14243. }
  14244. };
  14245. return CipherTransform;
  14246. })();
  14247. var CipherTransformFactory = (function CipherTransformFactoryClosure() {
  14248. var defaultPasswordBytes = new Uint8Array([
  14249. 0x28, 0xBF, 0x4E, 0x5E, 0x4E, 0x75, 0x8A, 0x41,
  14250. 0x64, 0x00, 0x4E, 0x56, 0xFF, 0xFA, 0x01, 0x08,
  14251. 0x2E, 0x2E, 0x00, 0xB6, 0xD0, 0x68, 0x3E, 0x80,
  14252. 0x2F, 0x0C, 0xA9, 0xFE, 0x64, 0x53, 0x69, 0x7A]);
  14253. function createEncryptionKey20(revision, password, ownerPassword,
  14254. ownerValidationSalt, ownerKeySalt, uBytes,
  14255. userPassword, userValidationSalt, userKeySalt,
  14256. ownerEncryption, userEncryption, perms) {
  14257. if (password) {
  14258. var passwordLength = Math.min(127, password.length);
  14259. password = password.subarray(0, passwordLength);
  14260. } else {
  14261. password = [];
  14262. }
  14263. var pdfAlgorithm;
  14264. if (revision === 6) {
  14265. pdfAlgorithm = new PDF20();
  14266. } else {
  14267. pdfAlgorithm = new PDF17();
  14268. }
  14269. if (pdfAlgorithm) {
  14270. if (pdfAlgorithm.checkUserPassword(password, userValidationSalt,
  14271. userPassword)) {
  14272. return pdfAlgorithm.getUserKey(password, userKeySalt, userEncryption);
  14273. } else if (pdfAlgorithm.checkOwnerPassword(password, ownerValidationSalt,
  14274. uBytes,
  14275. ownerPassword)) {
  14276. return pdfAlgorithm.getOwnerKey(password, ownerKeySalt, uBytes,
  14277. ownerEncryption);
  14278. }
  14279. }
  14280. return null;
  14281. }
  14282. function prepareKeyData(fileId, password, ownerPassword, userPassword,
  14283. flags, revision, keyLength, encryptMetadata) {
  14284. var hashDataSize = 40 + ownerPassword.length + fileId.length;
  14285. var hashData = new Uint8Array(hashDataSize), i = 0, j, n;
  14286. if (password) {
  14287. n = Math.min(32, password.length);
  14288. for (; i < n; ++i) {
  14289. hashData[i] = password[i];
  14290. }
  14291. }
  14292. j = 0;
  14293. while (i < 32) {
  14294. hashData[i++] = defaultPasswordBytes[j++];
  14295. }
  14296. // as now the padded password in the hashData[0..i]
  14297. for (j = 0, n = ownerPassword.length; j < n; ++j) {
  14298. hashData[i++] = ownerPassword[j];
  14299. }
  14300. hashData[i++] = flags & 0xFF;
  14301. hashData[i++] = (flags >> 8) & 0xFF;
  14302. hashData[i++] = (flags >> 16) & 0xFF;
  14303. hashData[i++] = (flags >>> 24) & 0xFF;
  14304. for (j = 0, n = fileId.length; j < n; ++j) {
  14305. hashData[i++] = fileId[j];
  14306. }
  14307. if (revision >= 4 && !encryptMetadata) {
  14308. hashData[i++] = 0xFF;
  14309. hashData[i++] = 0xFF;
  14310. hashData[i++] = 0xFF;
  14311. hashData[i++] = 0xFF;
  14312. }
  14313. var hash = calculateMD5(hashData, 0, i);
  14314. var keyLengthInBytes = keyLength >> 3;
  14315. if (revision >= 3) {
  14316. for (j = 0; j < 50; ++j) {
  14317. hash = calculateMD5(hash, 0, keyLengthInBytes);
  14318. }
  14319. }
  14320. var encryptionKey = hash.subarray(0, keyLengthInBytes);
  14321. var cipher, checkData;
  14322. if (revision >= 3) {
  14323. for (i = 0; i < 32; ++i) {
  14324. hashData[i] = defaultPasswordBytes[i];
  14325. }
  14326. for (j = 0, n = fileId.length; j < n; ++j) {
  14327. hashData[i++] = fileId[j];
  14328. }
  14329. cipher = new ARCFourCipher(encryptionKey);
  14330. checkData = cipher.encryptBlock(calculateMD5(hashData, 0, i));
  14331. n = encryptionKey.length;
  14332. var derivedKey = new Uint8Array(n), k;
  14333. for (j = 1; j <= 19; ++j) {
  14334. for (k = 0; k < n; ++k) {
  14335. derivedKey[k] = encryptionKey[k] ^ j;
  14336. }
  14337. cipher = new ARCFourCipher(derivedKey);
  14338. checkData = cipher.encryptBlock(checkData);
  14339. }
  14340. for (j = 0, n = checkData.length; j < n; ++j) {
  14341. if (userPassword[j] !== checkData[j]) {
  14342. return null;
  14343. }
  14344. }
  14345. } else {
  14346. cipher = new ARCFourCipher(encryptionKey);
  14347. checkData = cipher.encryptBlock(defaultPasswordBytes);
  14348. for (j = 0, n = checkData.length; j < n; ++j) {
  14349. if (userPassword[j] !== checkData[j]) {
  14350. return null;
  14351. }
  14352. }
  14353. }
  14354. return encryptionKey;
  14355. }
  14356. function decodeUserPassword(password, ownerPassword, revision, keyLength) {
  14357. var hashData = new Uint8Array(32), i = 0, j, n;
  14358. n = Math.min(32, password.length);
  14359. for (; i < n; ++i) {
  14360. hashData[i] = password[i];
  14361. }
  14362. j = 0;
  14363. while (i < 32) {
  14364. hashData[i++] = defaultPasswordBytes[j++];
  14365. }
  14366. var hash = calculateMD5(hashData, 0, i);
  14367. var keyLengthInBytes = keyLength >> 3;
  14368. if (revision >= 3) {
  14369. for (j = 0; j < 50; ++j) {
  14370. hash = calculateMD5(hash, 0, hash.length);
  14371. }
  14372. }
  14373. var cipher, userPassword;
  14374. if (revision >= 3) {
  14375. userPassword = ownerPassword;
  14376. var derivedKey = new Uint8Array(keyLengthInBytes), k;
  14377. for (j = 19; j >= 0; j--) {
  14378. for (k = 0; k < keyLengthInBytes; ++k) {
  14379. derivedKey[k] = hash[k] ^ j;
  14380. }
  14381. cipher = new ARCFourCipher(derivedKey);
  14382. userPassword = cipher.encryptBlock(userPassword);
  14383. }
  14384. } else {
  14385. cipher = new ARCFourCipher(hash.subarray(0, keyLengthInBytes));
  14386. userPassword = cipher.encryptBlock(ownerPassword);
  14387. }
  14388. return userPassword;
  14389. }
  14390. var identityName = Name.get('Identity');
  14391. function CipherTransformFactory(dict, fileId, password) {
  14392. var filter = dict.get('Filter');
  14393. if (!isName(filter) || filter.name !== 'Standard') {
  14394. error('unknown encryption method');
  14395. }
  14396. this.dict = dict;
  14397. var algorithm = dict.get('V');
  14398. if (!isInt(algorithm) ||
  14399. (algorithm !== 1 && algorithm !== 2 && algorithm !== 4 &&
  14400. algorithm !== 5)) {
  14401. error('unsupported encryption algorithm');
  14402. }
  14403. this.algorithm = algorithm;
  14404. var keyLength = dict.get('Length') || 40;
  14405. if (!isInt(keyLength) ||
  14406. keyLength < 40 || (keyLength % 8) !== 0) {
  14407. error('invalid key length');
  14408. }
  14409. // prepare keys
  14410. var ownerPassword = stringToBytes(dict.get('O')).subarray(0, 32);
  14411. var userPassword = stringToBytes(dict.get('U')).subarray(0, 32);
  14412. var flags = dict.get('P');
  14413. var revision = dict.get('R');
  14414. // meaningful when V is 4 or 5
  14415. var encryptMetadata = ((algorithm === 4 || algorithm === 5) &&
  14416. dict.get('EncryptMetadata') !== false);
  14417. this.encryptMetadata = encryptMetadata;
  14418. var fileIdBytes = stringToBytes(fileId);
  14419. var passwordBytes;
  14420. if (password) {
  14421. if (revision === 6) {
  14422. try {
  14423. password = utf8StringToString(password);
  14424. } catch (ex) {
  14425. warn('CipherTransformFactory: ' +
  14426. 'Unable to convert UTF8 encoded password.');
  14427. }
  14428. }
  14429. passwordBytes = stringToBytes(password);
  14430. }
  14431. var encryptionKey;
  14432. if (algorithm !== 5) {
  14433. encryptionKey = prepareKeyData(fileIdBytes, passwordBytes,
  14434. ownerPassword, userPassword, flags,
  14435. revision, keyLength, encryptMetadata);
  14436. }
  14437. else {
  14438. var ownerValidationSalt = stringToBytes(dict.get('O')).subarray(32, 40);
  14439. var ownerKeySalt = stringToBytes(dict.get('O')).subarray(40, 48);
  14440. var uBytes = stringToBytes(dict.get('U')).subarray(0, 48);
  14441. var userValidationSalt = stringToBytes(dict.get('U')).subarray(32, 40);
  14442. var userKeySalt = stringToBytes(dict.get('U')).subarray(40, 48);
  14443. var ownerEncryption = stringToBytes(dict.get('OE'));
  14444. var userEncryption = stringToBytes(dict.get('UE'));
  14445. var perms = stringToBytes(dict.get('Perms'));
  14446. encryptionKey =
  14447. createEncryptionKey20(revision, passwordBytes,
  14448. ownerPassword, ownerValidationSalt,
  14449. ownerKeySalt, uBytes,
  14450. userPassword, userValidationSalt,
  14451. userKeySalt, ownerEncryption,
  14452. userEncryption, perms);
  14453. }
  14454. if (!encryptionKey && !password) {
  14455. throw new PasswordException('No password given',
  14456. PasswordResponses.NEED_PASSWORD);
  14457. } else if (!encryptionKey && password) {
  14458. // Attempting use the password as an owner password
  14459. var decodedPassword = decodeUserPassword(passwordBytes, ownerPassword,
  14460. revision, keyLength);
  14461. encryptionKey = prepareKeyData(fileIdBytes, decodedPassword,
  14462. ownerPassword, userPassword, flags,
  14463. revision, keyLength, encryptMetadata);
  14464. }
  14465. if (!encryptionKey) {
  14466. throw new PasswordException('Incorrect Password',
  14467. PasswordResponses.INCORRECT_PASSWORD);
  14468. }
  14469. this.encryptionKey = encryptionKey;
  14470. if (algorithm >= 4) {
  14471. this.cf = dict.get('CF');
  14472. this.stmf = dict.get('StmF') || identityName;
  14473. this.strf = dict.get('StrF') || identityName;
  14474. this.eff = dict.get('EFF') || this.stmf;
  14475. }
  14476. }
  14477. function buildObjectKey(num, gen, encryptionKey, isAes) {
  14478. var key = new Uint8Array(encryptionKey.length + 9), i, n;
  14479. for (i = 0, n = encryptionKey.length; i < n; ++i) {
  14480. key[i] = encryptionKey[i];
  14481. }
  14482. key[i++] = num & 0xFF;
  14483. key[i++] = (num >> 8) & 0xFF;
  14484. key[i++] = (num >> 16) & 0xFF;
  14485. key[i++] = gen & 0xFF;
  14486. key[i++] = (gen >> 8) & 0xFF;
  14487. if (isAes) {
  14488. key[i++] = 0x73;
  14489. key[i++] = 0x41;
  14490. key[i++] = 0x6C;
  14491. key[i++] = 0x54;
  14492. }
  14493. var hash = calculateMD5(key, 0, i);
  14494. return hash.subarray(0, Math.min(encryptionKey.length + 5, 16));
  14495. }
  14496. function buildCipherConstructor(cf, name, num, gen, key) {
  14497. var cryptFilter = cf.get(name.name);
  14498. var cfm;
  14499. if (cryptFilter !== null && cryptFilter !== undefined) {
  14500. cfm = cryptFilter.get('CFM');
  14501. }
  14502. if (!cfm || cfm.name === 'None') {
  14503. return function cipherTransformFactoryBuildCipherConstructorNone() {
  14504. return new NullCipher();
  14505. };
  14506. }
  14507. if ('V2' === cfm.name) {
  14508. return function cipherTransformFactoryBuildCipherConstructorV2() {
  14509. return new ARCFourCipher(buildObjectKey(num, gen, key, false));
  14510. };
  14511. }
  14512. if ('AESV2' === cfm.name) {
  14513. return function cipherTransformFactoryBuildCipherConstructorAESV2() {
  14514. return new AES128Cipher(buildObjectKey(num, gen, key, true));
  14515. };
  14516. }
  14517. if ('AESV3' === cfm.name) {
  14518. return function cipherTransformFactoryBuildCipherConstructorAESV3() {
  14519. return new AES256Cipher(key);
  14520. };
  14521. }
  14522. error('Unknown crypto method');
  14523. }
  14524. CipherTransformFactory.prototype = {
  14525. createCipherTransform:
  14526. function CipherTransformFactory_createCipherTransform(num, gen) {
  14527. if (this.algorithm === 4 || this.algorithm === 5) {
  14528. return new CipherTransform(
  14529. buildCipherConstructor(this.cf, this.stmf,
  14530. num, gen, this.encryptionKey),
  14531. buildCipherConstructor(this.cf, this.strf,
  14532. num, gen, this.encryptionKey));
  14533. }
  14534. // algorithms 1 and 2
  14535. var key = buildObjectKey(num, gen, this.encryptionKey, false);
  14536. var cipherConstructor = function buildCipherCipherConstructor() {
  14537. return new ARCFourCipher(key);
  14538. };
  14539. return new CipherTransform(cipherConstructor, cipherConstructor);
  14540. }
  14541. };
  14542. return CipherTransformFactory;
  14543. })();
  14544. var PatternType = {
  14545. FUNCTION_BASED: 1,
  14546. AXIAL: 2,
  14547. RADIAL: 3,
  14548. FREE_FORM_MESH: 4,
  14549. LATTICE_FORM_MESH: 5,
  14550. COONS_PATCH_MESH: 6,
  14551. TENSOR_PATCH_MESH: 7
  14552. };
  14553. var Pattern = (function PatternClosure() {
  14554. // Constructor should define this.getPattern
  14555. function Pattern() {
  14556. error('should not call Pattern constructor');
  14557. }
  14558. Pattern.prototype = {
  14559. // Input: current Canvas context
  14560. // Output: the appropriate fillStyle or strokeStyle
  14561. getPattern: function Pattern_getPattern(ctx) {
  14562. error('Should not call Pattern.getStyle: ' + ctx);
  14563. }
  14564. };
  14565. Pattern.parseShading = function Pattern_parseShading(shading, matrix, xref,
  14566. res) {
  14567. var dict = isStream(shading) ? shading.dict : shading;
  14568. var type = dict.get('ShadingType');
  14569. try {
  14570. switch (type) {
  14571. case PatternType.AXIAL:
  14572. case PatternType.RADIAL:
  14573. // Both radial and axial shadings are handled by RadialAxial shading.
  14574. return new Shadings.RadialAxial(dict, matrix, xref, res);
  14575. case PatternType.FREE_FORM_MESH:
  14576. case PatternType.LATTICE_FORM_MESH:
  14577. case PatternType.COONS_PATCH_MESH:
  14578. case PatternType.TENSOR_PATCH_MESH:
  14579. return new Shadings.Mesh(shading, matrix, xref, res);
  14580. default:
  14581. throw new Error('Unknown PatternType: ' + type);
  14582. }
  14583. } catch (ex) {
  14584. if (ex instanceof MissingDataException) {
  14585. throw ex;
  14586. }
  14587. UnsupportedManager.notify(UNSUPPORTED_FEATURES.shadingPattern);
  14588. warn(ex);
  14589. return new Shadings.Dummy();
  14590. }
  14591. };
  14592. return Pattern;
  14593. })();
  14594. var Shadings = {};
  14595. // A small number to offset the first/last color stops so we can insert ones to
  14596. // support extend. Number.MIN_VALUE appears to be too small and breaks the
  14597. // extend. 1e-7 works in FF but chrome seems to use an even smaller sized number
  14598. // internally so we have to go bigger.
  14599. Shadings.SMALL_NUMBER = 1e-2;
  14600. // Radial and axial shading have very similar implementations
  14601. // If needed, the implementations can be broken into two classes
  14602. Shadings.RadialAxial = (function RadialAxialClosure() {
  14603. function RadialAxial(dict, matrix, xref, res) {
  14604. this.matrix = matrix;
  14605. this.coordsArr = dict.get('Coords');
  14606. this.shadingType = dict.get('ShadingType');
  14607. this.type = 'Pattern';
  14608. var cs = dict.get('ColorSpace', 'CS');
  14609. cs = ColorSpace.parse(cs, xref, res);
  14610. this.cs = cs;
  14611. var t0 = 0.0, t1 = 1.0;
  14612. if (dict.has('Domain')) {
  14613. var domainArr = dict.get('Domain');
  14614. t0 = domainArr[0];
  14615. t1 = domainArr[1];
  14616. }
  14617. var extendStart = false, extendEnd = false;
  14618. if (dict.has('Extend')) {
  14619. var extendArr = dict.get('Extend');
  14620. extendStart = extendArr[0];
  14621. extendEnd = extendArr[1];
  14622. }
  14623. if (this.shadingType === PatternType.RADIAL &&
  14624. (!extendStart || !extendEnd)) {
  14625. // Radial gradient only currently works if either circle is fully within
  14626. // the other circle.
  14627. var x1 = this.coordsArr[0];
  14628. var y1 = this.coordsArr[1];
  14629. var r1 = this.coordsArr[2];
  14630. var x2 = this.coordsArr[3];
  14631. var y2 = this.coordsArr[4];
  14632. var r2 = this.coordsArr[5];
  14633. var distance = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
  14634. if (r1 <= r2 + distance &&
  14635. r2 <= r1 + distance) {
  14636. warn('Unsupported radial gradient.');
  14637. }
  14638. }
  14639. this.extendStart = extendStart;
  14640. this.extendEnd = extendEnd;
  14641. var fnObj = dict.get('Function');
  14642. var fn = PDFFunction.parseArray(xref, fnObj);
  14643. // 10 samples seems good enough for now, but probably won't work
  14644. // if there are sharp color changes. Ideally, we would implement
  14645. // the spec faithfully and add lossless optimizations.
  14646. var diff = t1 - t0;
  14647. var step = diff / 10;
  14648. var colorStops = this.colorStops = [];
  14649. // Protect against bad domains so we don't end up in an infinte loop below.
  14650. if (t0 >= t1 || step <= 0) {
  14651. // Acrobat doesn't seem to handle these cases so we'll ignore for
  14652. // now.
  14653. info('Bad shading domain.');
  14654. return;
  14655. }
  14656. var color = new Float32Array(cs.numComps), ratio = new Float32Array(1);
  14657. var rgbColor;
  14658. for (var i = t0; i <= t1; i += step) {
  14659. ratio[0] = i;
  14660. fn(ratio, 0, color, 0);
  14661. rgbColor = cs.getRgb(color, 0);
  14662. var cssColor = Util.makeCssRgb(rgbColor[0], rgbColor[1], rgbColor[2]);
  14663. colorStops.push([(i - t0) / diff, cssColor]);
  14664. }
  14665. var background = 'transparent';
  14666. if (dict.has('Background')) {
  14667. rgbColor = cs.getRgb(dict.get('Background'), 0);
  14668. background = Util.makeCssRgb(rgbColor[0], rgbColor[1], rgbColor[2]);
  14669. }
  14670. if (!extendStart) {
  14671. // Insert a color stop at the front and offset the first real color stop
  14672. // so it doesn't conflict with the one we insert.
  14673. colorStops.unshift([0, background]);
  14674. colorStops[1][0] += Shadings.SMALL_NUMBER;
  14675. }
  14676. if (!extendEnd) {
  14677. // Same idea as above in extendStart but for the end.
  14678. colorStops[colorStops.length - 1][0] -= Shadings.SMALL_NUMBER;
  14679. colorStops.push([1, background]);
  14680. }
  14681. this.colorStops = colorStops;
  14682. }
  14683. RadialAxial.prototype = {
  14684. getIR: function RadialAxial_getIR() {
  14685. var coordsArr = this.coordsArr;
  14686. var shadingType = this.shadingType;
  14687. var type, p0, p1, r0, r1;
  14688. if (shadingType === PatternType.AXIAL) {
  14689. p0 = [coordsArr[0], coordsArr[1]];
  14690. p1 = [coordsArr[2], coordsArr[3]];
  14691. r0 = null;
  14692. r1 = null;
  14693. type = 'axial';
  14694. } else if (shadingType === PatternType.RADIAL) {
  14695. p0 = [coordsArr[0], coordsArr[1]];
  14696. p1 = [coordsArr[3], coordsArr[4]];
  14697. r0 = coordsArr[2];
  14698. r1 = coordsArr[5];
  14699. type = 'radial';
  14700. } else {
  14701. error('getPattern type unknown: ' + shadingType);
  14702. }
  14703. var matrix = this.matrix;
  14704. if (matrix) {
  14705. p0 = Util.applyTransform(p0, matrix);
  14706. p1 = Util.applyTransform(p1, matrix);
  14707. }
  14708. return ['RadialAxial', type, this.colorStops, p0, p1, r0, r1];
  14709. }
  14710. };
  14711. return RadialAxial;
  14712. })();
  14713. // All mesh shading. For now, they will be presented as set of the triangles
  14714. // to be drawn on the canvas and rgb color for each vertex.
  14715. Shadings.Mesh = (function MeshClosure() {
  14716. function MeshStreamReader(stream, context) {
  14717. this.stream = stream;
  14718. this.context = context;
  14719. this.buffer = 0;
  14720. this.bufferLength = 0;
  14721. var numComps = context.numComps;
  14722. this.tmpCompsBuf = new Float32Array(numComps);
  14723. var csNumComps = context.colorSpace;
  14724. this.tmpCsCompsBuf = context.colorFn ? new Float32Array(csNumComps) :
  14725. this.tmpCompsBuf;
  14726. }
  14727. MeshStreamReader.prototype = {
  14728. get hasData() {
  14729. if (this.stream.end) {
  14730. return this.stream.pos < this.stream.end;
  14731. }
  14732. if (this.bufferLength > 0) {
  14733. return true;
  14734. }
  14735. var nextByte = this.stream.getByte();
  14736. if (nextByte < 0) {
  14737. return false;
  14738. }
  14739. this.buffer = nextByte;
  14740. this.bufferLength = 8;
  14741. return true;
  14742. },
  14743. readBits: function MeshStreamReader_readBits(n) {
  14744. var buffer = this.buffer;
  14745. var bufferLength = this.bufferLength;
  14746. if (n === 32) {
  14747. if (bufferLength === 0) {
  14748. return ((this.stream.getByte() << 24) |
  14749. (this.stream.getByte() << 16) | (this.stream.getByte() << 8) |
  14750. this.stream.getByte()) >>> 0;
  14751. }
  14752. buffer = (buffer << 24) | (this.stream.getByte() << 16) |
  14753. (this.stream.getByte() << 8) | this.stream.getByte();
  14754. var nextByte = this.stream.getByte();
  14755. this.buffer = nextByte & ((1 << bufferLength) - 1);
  14756. return ((buffer << (8 - bufferLength)) |
  14757. ((nextByte & 0xFF) >> bufferLength)) >>> 0;
  14758. }
  14759. if (n === 8 && bufferLength === 0) {
  14760. return this.stream.getByte();
  14761. }
  14762. while (bufferLength < n) {
  14763. buffer = (buffer << 8) | this.stream.getByte();
  14764. bufferLength += 8;
  14765. }
  14766. bufferLength -= n;
  14767. this.bufferLength = bufferLength;
  14768. this.buffer = buffer & ((1 << bufferLength) - 1);
  14769. return buffer >> bufferLength;
  14770. },
  14771. align: function MeshStreamReader_align() {
  14772. this.buffer = 0;
  14773. this.bufferLength = 0;
  14774. },
  14775. readFlag: function MeshStreamReader_readFlag() {
  14776. return this.readBits(this.context.bitsPerFlag);
  14777. },
  14778. readCoordinate: function MeshStreamReader_readCoordinate() {
  14779. var bitsPerCoordinate = this.context.bitsPerCoordinate;
  14780. var xi = this.readBits(bitsPerCoordinate);
  14781. var yi = this.readBits(bitsPerCoordinate);
  14782. var decode = this.context.decode;
  14783. var scale = bitsPerCoordinate < 32 ? 1 / ((1 << bitsPerCoordinate) - 1) :
  14784. 2.3283064365386963e-10; // 2 ^ -32
  14785. return [
  14786. xi * scale * (decode[1] - decode[0]) + decode[0],
  14787. yi * scale * (decode[3] - decode[2]) + decode[2]
  14788. ];
  14789. },
  14790. readComponents: function MeshStreamReader_readComponents() {
  14791. var numComps = this.context.numComps;
  14792. var bitsPerComponent = this.context.bitsPerComponent;
  14793. var scale = bitsPerComponent < 32 ? 1 / ((1 << bitsPerComponent) - 1) :
  14794. 2.3283064365386963e-10; // 2 ^ -32
  14795. var decode = this.context.decode;
  14796. var components = this.tmpCompsBuf;
  14797. for (var i = 0, j = 4; i < numComps; i++, j += 2) {
  14798. var ci = this.readBits(bitsPerComponent);
  14799. components[i] = ci * scale * (decode[j + 1] - decode[j]) + decode[j];
  14800. }
  14801. var color = this.tmpCsCompsBuf;
  14802. if (this.context.colorFn) {
  14803. this.context.colorFn(components, 0, color, 0);
  14804. }
  14805. return this.context.colorSpace.getRgb(color, 0);
  14806. }
  14807. };
  14808. function decodeType4Shading(mesh, reader) {
  14809. var coords = mesh.coords;
  14810. var colors = mesh.colors;
  14811. var operators = [];
  14812. var ps = []; // not maintaining cs since that will match ps
  14813. var verticesLeft = 0; // assuming we have all data to start a new triangle
  14814. while (reader.hasData) {
  14815. var f = reader.readFlag();
  14816. var coord = reader.readCoordinate();
  14817. var color = reader.readComponents();
  14818. if (verticesLeft === 0) { // ignoring flags if we started a triangle
  14819. assert(0 <= f && f <= 2, 'Unknown type4 flag');
  14820. switch (f) {
  14821. case 0:
  14822. verticesLeft = 3;
  14823. break;
  14824. case 1:
  14825. ps.push(ps[ps.length - 2], ps[ps.length - 1]);
  14826. verticesLeft = 1;
  14827. break;
  14828. case 2:
  14829. ps.push(ps[ps.length - 3], ps[ps.length - 1]);
  14830. verticesLeft = 1;
  14831. break;
  14832. }
  14833. operators.push(f);
  14834. }
  14835. ps.push(coords.length);
  14836. coords.push(coord);
  14837. colors.push(color);
  14838. verticesLeft--;
  14839. reader.align();
  14840. }
  14841. var psPacked = new Int32Array(ps);
  14842. mesh.figures.push({
  14843. type: 'triangles',
  14844. coords: psPacked,
  14845. colors: psPacked
  14846. });
  14847. }
  14848. function decodeType5Shading(mesh, reader, verticesPerRow) {
  14849. var coords = mesh.coords;
  14850. var colors = mesh.colors;
  14851. var ps = []; // not maintaining cs since that will match ps
  14852. while (reader.hasData) {
  14853. var coord = reader.readCoordinate();
  14854. var color = reader.readComponents();
  14855. ps.push(coords.length);
  14856. coords.push(coord);
  14857. colors.push(color);
  14858. }
  14859. var psPacked = new Int32Array(ps);
  14860. mesh.figures.push({
  14861. type: 'lattice',
  14862. coords: psPacked,
  14863. colors: psPacked,
  14864. verticesPerRow: verticesPerRow
  14865. });
  14866. }
  14867. var MIN_SPLIT_PATCH_CHUNKS_AMOUNT = 3;
  14868. var MAX_SPLIT_PATCH_CHUNKS_AMOUNT = 20;
  14869. var TRIANGLE_DENSITY = 20; // count of triangles per entire mesh bounds
  14870. var getB = (function getBClosure() {
  14871. function buildB(count) {
  14872. var lut = [];
  14873. for (var i = 0; i <= count; i++) {
  14874. var t = i / count, t_ = 1 - t;
  14875. lut.push(new Float32Array([t_ * t_ * t_, 3 * t * t_ * t_,
  14876. 3 * t * t * t_, t * t * t]));
  14877. }
  14878. return lut;
  14879. }
  14880. var cache = [];
  14881. return function getB(count) {
  14882. if (!cache[count]) {
  14883. cache[count] = buildB(count);
  14884. }
  14885. return cache[count];
  14886. };
  14887. })();
  14888. function buildFigureFromPatch(mesh, index) {
  14889. var figure = mesh.figures[index];
  14890. assert(figure.type === 'patch', 'Unexpected patch mesh figure');
  14891. var coords = mesh.coords, colors = mesh.colors;
  14892. var pi = figure.coords;
  14893. var ci = figure.colors;
  14894. var figureMinX = Math.min(coords[pi[0]][0], coords[pi[3]][0],
  14895. coords[pi[12]][0], coords[pi[15]][0]);
  14896. var figureMinY = Math.min(coords[pi[0]][1], coords[pi[3]][1],
  14897. coords[pi[12]][1], coords[pi[15]][1]);
  14898. var figureMaxX = Math.max(coords[pi[0]][0], coords[pi[3]][0],
  14899. coords[pi[12]][0], coords[pi[15]][0]);
  14900. var figureMaxY = Math.max(coords[pi[0]][1], coords[pi[3]][1],
  14901. coords[pi[12]][1], coords[pi[15]][1]);
  14902. var splitXBy = Math.ceil((figureMaxX - figureMinX) * TRIANGLE_DENSITY /
  14903. (mesh.bounds[2] - mesh.bounds[0]));
  14904. splitXBy = Math.max(MIN_SPLIT_PATCH_CHUNKS_AMOUNT,
  14905. Math.min(MAX_SPLIT_PATCH_CHUNKS_AMOUNT, splitXBy));
  14906. var splitYBy = Math.ceil((figureMaxY - figureMinY) * TRIANGLE_DENSITY /
  14907. (mesh.bounds[3] - mesh.bounds[1]));
  14908. splitYBy = Math.max(MIN_SPLIT_PATCH_CHUNKS_AMOUNT,
  14909. Math.min(MAX_SPLIT_PATCH_CHUNKS_AMOUNT, splitYBy));
  14910. var verticesPerRow = splitXBy + 1;
  14911. var figureCoords = new Int32Array((splitYBy + 1) * verticesPerRow);
  14912. var figureColors = new Int32Array((splitYBy + 1) * verticesPerRow);
  14913. var k = 0;
  14914. var cl = new Uint8Array(3), cr = new Uint8Array(3);
  14915. var c0 = colors[ci[0]], c1 = colors[ci[1]],
  14916. c2 = colors[ci[2]], c3 = colors[ci[3]];
  14917. var bRow = getB(splitYBy), bCol = getB(splitXBy);
  14918. for (var row = 0; row <= splitYBy; row++) {
  14919. cl[0] = ((c0[0] * (splitYBy - row) + c2[0] * row) / splitYBy) | 0;
  14920. cl[1] = ((c0[1] * (splitYBy - row) + c2[1] * row) / splitYBy) | 0;
  14921. cl[2] = ((c0[2] * (splitYBy - row) + c2[2] * row) / splitYBy) | 0;
  14922. cr[0] = ((c1[0] * (splitYBy - row) + c3[0] * row) / splitYBy) | 0;
  14923. cr[1] = ((c1[1] * (splitYBy - row) + c3[1] * row) / splitYBy) | 0;
  14924. cr[2] = ((c1[2] * (splitYBy - row) + c3[2] * row) / splitYBy) | 0;
  14925. for (var col = 0; col <= splitXBy; col++, k++) {
  14926. if ((row === 0 || row === splitYBy) &&
  14927. (col === 0 || col === splitXBy)) {
  14928. continue;
  14929. }
  14930. var x = 0, y = 0;
  14931. var q = 0;
  14932. for (var i = 0; i <= 3; i++) {
  14933. for (var j = 0; j <= 3; j++, q++) {
  14934. var m = bRow[row][i] * bCol[col][j];
  14935. x += coords[pi[q]][0] * m;
  14936. y += coords[pi[q]][1] * m;
  14937. }
  14938. }
  14939. figureCoords[k] = coords.length;
  14940. coords.push([x, y]);
  14941. figureColors[k] = colors.length;
  14942. var newColor = new Uint8Array(3);
  14943. newColor[0] = ((cl[0] * (splitXBy - col) + cr[0] * col) / splitXBy) | 0;
  14944. newColor[1] = ((cl[1] * (splitXBy - col) + cr[1] * col) / splitXBy) | 0;
  14945. newColor[2] = ((cl[2] * (splitXBy - col) + cr[2] * col) / splitXBy) | 0;
  14946. colors.push(newColor);
  14947. }
  14948. }
  14949. figureCoords[0] = pi[0];
  14950. figureColors[0] = ci[0];
  14951. figureCoords[splitXBy] = pi[3];
  14952. figureColors[splitXBy] = ci[1];
  14953. figureCoords[verticesPerRow * splitYBy] = pi[12];
  14954. figureColors[verticesPerRow * splitYBy] = ci[2];
  14955. figureCoords[verticesPerRow * splitYBy + splitXBy] = pi[15];
  14956. figureColors[verticesPerRow * splitYBy + splitXBy] = ci[3];
  14957. mesh.figures[index] = {
  14958. type: 'lattice',
  14959. coords: figureCoords,
  14960. colors: figureColors,
  14961. verticesPerRow: verticesPerRow
  14962. };
  14963. }
  14964. function decodeType6Shading(mesh, reader) {
  14965. // A special case of Type 7. The p11, p12, p21, p22 automatically filled
  14966. var coords = mesh.coords;
  14967. var colors = mesh.colors;
  14968. var ps = new Int32Array(16); // p00, p10, ..., p30, p01, ..., p33
  14969. var cs = new Int32Array(4); // c00, c30, c03, c33
  14970. while (reader.hasData) {
  14971. var f = reader.readFlag();
  14972. assert(0 <= f && f <= 3, 'Unknown type6 flag');
  14973. var i, ii;
  14974. var pi = coords.length;
  14975. for (i = 0, ii = (f !== 0 ? 8 : 12); i < ii; i++) {
  14976. coords.push(reader.readCoordinate());
  14977. }
  14978. var ci = colors.length;
  14979. for (i = 0, ii = (f !== 0 ? 2 : 4); i < ii; i++) {
  14980. colors.push(reader.readComponents());
  14981. }
  14982. var tmp1, tmp2, tmp3, tmp4;
  14983. switch (f) {
  14984. case 0:
  14985. ps[12] = pi + 3; ps[13] = pi + 4; ps[14] = pi + 5; ps[15] = pi + 6;
  14986. ps[ 8] = pi + 2; /* values for 5, 6, 9, 10 are */ ps[11] = pi + 7;
  14987. ps[ 4] = pi + 1; /* calculated below */ ps[ 7] = pi + 8;
  14988. ps[ 0] = pi; ps[ 1] = pi + 11; ps[ 2] = pi + 10; ps[ 3] = pi + 9;
  14989. cs[2] = ci + 1; cs[3] = ci + 2;
  14990. cs[0] = ci; cs[1] = ci + 3;
  14991. break;
  14992. case 1:
  14993. tmp1 = ps[12]; tmp2 = ps[13]; tmp3 = ps[14]; tmp4 = ps[15];
  14994. ps[12] = pi + 5; ps[13] = pi + 4; ps[14] = pi + 3; ps[15] = pi + 2;
  14995. ps[ 8] = pi + 6; /* values for 5, 6, 9, 10 are */ ps[11] = pi + 1;
  14996. ps[ 4] = pi + 7; /* calculated below */ ps[ 7] = pi;
  14997. ps[ 0] = tmp1; ps[ 1] = tmp2; ps[ 2] = tmp3; ps[ 3] = tmp4;
  14998. tmp1 = cs[2]; tmp2 = cs[3];
  14999. cs[2] = ci + 1; cs[3] = ci;
  15000. cs[0] = tmp1; cs[1] = tmp2;
  15001. break;
  15002. case 2:
  15003. ps[12] = ps[15]; ps[13] = pi + 7; ps[14] = pi + 6; ps[15] = pi + 5;
  15004. ps[ 8] = ps[11]; /* values for 5, 6, 9, 10 are */ ps[11] = pi + 4;
  15005. ps[ 4] = ps[7]; /* calculated below */ ps[ 7] = pi + 3;
  15006. ps[ 0] = ps[3]; ps[ 1] = pi; ps[ 2] = pi + 1; ps[ 3] = pi + 2;
  15007. cs[2] = cs[3]; cs[3] = ci + 1;
  15008. cs[0] = cs[1]; cs[1] = ci;
  15009. break;
  15010. case 3:
  15011. ps[12] = ps[0]; ps[13] = ps[1]; ps[14] = ps[2]; ps[15] = ps[3];
  15012. ps[ 8] = pi; /* values for 5, 6, 9, 10 are */ ps[11] = pi + 7;
  15013. ps[ 4] = pi + 1; /* calculated below */ ps[ 7] = pi + 6;
  15014. ps[ 0] = pi + 2; ps[ 1] = pi + 3; ps[ 2] = pi + 4; ps[ 3] = pi + 5;
  15015. cs[2] = cs[0]; cs[3] = cs[1];
  15016. cs[0] = ci; cs[1] = ci + 1;
  15017. break;
  15018. }
  15019. // set p11, p12, p21, p22
  15020. ps[5] = coords.length;
  15021. coords.push([
  15022. (-4 * coords[ps[0]][0] - coords[ps[15]][0] +
  15023. 6 * (coords[ps[4]][0] + coords[ps[1]][0]) -
  15024. 2 * (coords[ps[12]][0] + coords[ps[3]][0]) +
  15025. 3 * (coords[ps[13]][0] + coords[ps[7]][0])) / 9,
  15026. (-4 * coords[ps[0]][1] - coords[ps[15]][1] +
  15027. 6 * (coords[ps[4]][1] + coords[ps[1]][1]) -
  15028. 2 * (coords[ps[12]][1] + coords[ps[3]][1]) +
  15029. 3 * (coords[ps[13]][1] + coords[ps[7]][1])) / 9
  15030. ]);
  15031. ps[6] = coords.length;
  15032. coords.push([
  15033. (-4 * coords[ps[3]][0] - coords[ps[12]][0] +
  15034. 6 * (coords[ps[2]][0] + coords[ps[7]][0]) -
  15035. 2 * (coords[ps[0]][0] + coords[ps[15]][0]) +
  15036. 3 * (coords[ps[4]][0] + coords[ps[14]][0])) / 9,
  15037. (-4 * coords[ps[3]][1] - coords[ps[12]][1] +
  15038. 6 * (coords[ps[2]][1] + coords[ps[7]][1]) -
  15039. 2 * (coords[ps[0]][1] + coords[ps[15]][1]) +
  15040. 3 * (coords[ps[4]][1] + coords[ps[14]][1])) / 9
  15041. ]);
  15042. ps[9] = coords.length;
  15043. coords.push([
  15044. (-4 * coords[ps[12]][0] - coords[ps[3]][0] +
  15045. 6 * (coords[ps[8]][0] + coords[ps[13]][0]) -
  15046. 2 * (coords[ps[0]][0] + coords[ps[15]][0]) +
  15047. 3 * (coords[ps[11]][0] + coords[ps[1]][0])) / 9,
  15048. (-4 * coords[ps[12]][1] - coords[ps[3]][1] +
  15049. 6 * (coords[ps[8]][1] + coords[ps[13]][1]) -
  15050. 2 * (coords[ps[0]][1] + coords[ps[15]][1]) +
  15051. 3 * (coords[ps[11]][1] + coords[ps[1]][1])) / 9
  15052. ]);
  15053. ps[10] = coords.length;
  15054. coords.push([
  15055. (-4 * coords[ps[15]][0] - coords[ps[0]][0] +
  15056. 6 * (coords[ps[11]][0] + coords[ps[14]][0]) -
  15057. 2 * (coords[ps[12]][0] + coords[ps[3]][0]) +
  15058. 3 * (coords[ps[2]][0] + coords[ps[8]][0])) / 9,
  15059. (-4 * coords[ps[15]][1] - coords[ps[0]][1] +
  15060. 6 * (coords[ps[11]][1] + coords[ps[14]][1]) -
  15061. 2 * (coords[ps[12]][1] + coords[ps[3]][1]) +
  15062. 3 * (coords[ps[2]][1] + coords[ps[8]][1])) / 9
  15063. ]);
  15064. mesh.figures.push({
  15065. type: 'patch',
  15066. coords: new Int32Array(ps), // making copies of ps and cs
  15067. colors: new Int32Array(cs)
  15068. });
  15069. }
  15070. }
  15071. function decodeType7Shading(mesh, reader) {
  15072. var coords = mesh.coords;
  15073. var colors = mesh.colors;
  15074. var ps = new Int32Array(16); // p00, p10, ..., p30, p01, ..., p33
  15075. var cs = new Int32Array(4); // c00, c30, c03, c33
  15076. while (reader.hasData) {
  15077. var f = reader.readFlag();
  15078. assert(0 <= f && f <= 3, 'Unknown type7 flag');
  15079. var i, ii;
  15080. var pi = coords.length;
  15081. for (i = 0, ii = (f !== 0 ? 12 : 16); i < ii; i++) {
  15082. coords.push(reader.readCoordinate());
  15083. }
  15084. var ci = colors.length;
  15085. for (i = 0, ii = (f !== 0 ? 2 : 4); i < ii; i++) {
  15086. colors.push(reader.readComponents());
  15087. }
  15088. var tmp1, tmp2, tmp3, tmp4;
  15089. switch (f) {
  15090. case 0:
  15091. ps[12] = pi + 3; ps[13] = pi + 4; ps[14] = pi + 5; ps[15] = pi + 6;
  15092. ps[ 8] = pi + 2; ps[ 9] = pi + 13; ps[10] = pi + 14; ps[11] = pi + 7;
  15093. ps[ 4] = pi + 1; ps[ 5] = pi + 12; ps[ 6] = pi + 15; ps[ 7] = pi + 8;
  15094. ps[ 0] = pi; ps[ 1] = pi + 11; ps[ 2] = pi + 10; ps[ 3] = pi + 9;
  15095. cs[2] = ci + 1; cs[3] = ci + 2;
  15096. cs[0] = ci; cs[1] = ci + 3;
  15097. break;
  15098. case 1:
  15099. tmp1 = ps[12]; tmp2 = ps[13]; tmp3 = ps[14]; tmp4 = ps[15];
  15100. ps[12] = pi + 5; ps[13] = pi + 4; ps[14] = pi + 3; ps[15] = pi + 2;
  15101. ps[ 8] = pi + 6; ps[ 9] = pi + 11; ps[10] = pi + 10; ps[11] = pi + 1;
  15102. ps[ 4] = pi + 7; ps[ 5] = pi + 8; ps[ 6] = pi + 9; ps[ 7] = pi;
  15103. ps[ 0] = tmp1; ps[ 1] = tmp2; ps[ 2] = tmp3; ps[ 3] = tmp4;
  15104. tmp1 = cs[2]; tmp2 = cs[3];
  15105. cs[2] = ci + 1; cs[3] = ci;
  15106. cs[0] = tmp1; cs[1] = tmp2;
  15107. break;
  15108. case 2:
  15109. ps[12] = ps[15]; ps[13] = pi + 7; ps[14] = pi + 6; ps[15] = pi + 5;
  15110. ps[ 8] = ps[11]; ps[ 9] = pi + 8; ps[10] = pi + 11; ps[11] = pi + 4;
  15111. ps[ 4] = ps[7]; ps[ 5] = pi + 9; ps[ 6] = pi + 10; ps[ 7] = pi + 3;
  15112. ps[ 0] = ps[3]; ps[ 1] = pi; ps[ 2] = pi + 1; ps[ 3] = pi + 2;
  15113. cs[2] = cs[3]; cs[3] = ci + 1;
  15114. cs[0] = cs[1]; cs[1] = ci;
  15115. break;
  15116. case 3:
  15117. ps[12] = ps[0]; ps[13] = ps[1]; ps[14] = ps[2]; ps[15] = ps[3];
  15118. ps[ 8] = pi; ps[ 9] = pi + 9; ps[10] = pi + 8; ps[11] = pi + 7;
  15119. ps[ 4] = pi + 1; ps[ 5] = pi + 10; ps[ 6] = pi + 11; ps[ 7] = pi + 6;
  15120. ps[ 0] = pi + 2; ps[ 1] = pi + 3; ps[ 2] = pi + 4; ps[ 3] = pi + 5;
  15121. cs[2] = cs[0]; cs[3] = cs[1];
  15122. cs[0] = ci; cs[1] = ci + 1;
  15123. break;
  15124. }
  15125. mesh.figures.push({
  15126. type: 'patch',
  15127. coords: new Int32Array(ps), // making copies of ps and cs
  15128. colors: new Int32Array(cs)
  15129. });
  15130. }
  15131. }
  15132. function updateBounds(mesh) {
  15133. var minX = mesh.coords[0][0], minY = mesh.coords[0][1],
  15134. maxX = minX, maxY = minY;
  15135. for (var i = 1, ii = mesh.coords.length; i < ii; i++) {
  15136. var x = mesh.coords[i][0], y = mesh.coords[i][1];
  15137. minX = minX > x ? x : minX;
  15138. minY = minY > y ? y : minY;
  15139. maxX = maxX < x ? x : maxX;
  15140. maxY = maxY < y ? y : maxY;
  15141. }
  15142. mesh.bounds = [minX, minY, maxX, maxY];
  15143. }
  15144. function packData(mesh) {
  15145. var i, ii, j, jj;
  15146. var coords = mesh.coords;
  15147. var coordsPacked = new Float32Array(coords.length * 2);
  15148. for (i = 0, j = 0, ii = coords.length; i < ii; i++) {
  15149. var xy = coords[i];
  15150. coordsPacked[j++] = xy[0];
  15151. coordsPacked[j++] = xy[1];
  15152. }
  15153. mesh.coords = coordsPacked;
  15154. var colors = mesh.colors;
  15155. var colorsPacked = new Uint8Array(colors.length * 3);
  15156. for (i = 0, j = 0, ii = colors.length; i < ii; i++) {
  15157. var c = colors[i];
  15158. colorsPacked[j++] = c[0];
  15159. colorsPacked[j++] = c[1];
  15160. colorsPacked[j++] = c[2];
  15161. }
  15162. mesh.colors = colorsPacked;
  15163. var figures = mesh.figures;
  15164. for (i = 0, ii = figures.length; i < ii; i++) {
  15165. var figure = figures[i], ps = figure.coords, cs = figure.colors;
  15166. for (j = 0, jj = ps.length; j < jj; j++) {
  15167. ps[j] *= 2;
  15168. cs[j] *= 3;
  15169. }
  15170. }
  15171. }
  15172. function Mesh(stream, matrix, xref, res) {
  15173. assert(isStream(stream), 'Mesh data is not a stream');
  15174. var dict = stream.dict;
  15175. this.matrix = matrix;
  15176. this.shadingType = dict.get('ShadingType');
  15177. this.type = 'Pattern';
  15178. this.bbox = dict.get('BBox');
  15179. var cs = dict.get('ColorSpace', 'CS');
  15180. cs = ColorSpace.parse(cs, xref, res);
  15181. this.cs = cs;
  15182. this.background = dict.has('Background') ?
  15183. cs.getRgb(dict.get('Background'), 0) : null;
  15184. var fnObj = dict.get('Function');
  15185. var fn = fnObj ? PDFFunction.parseArray(xref, fnObj) : null;
  15186. this.coords = [];
  15187. this.colors = [];
  15188. this.figures = [];
  15189. var decodeContext = {
  15190. bitsPerCoordinate: dict.get('BitsPerCoordinate'),
  15191. bitsPerComponent: dict.get('BitsPerComponent'),
  15192. bitsPerFlag: dict.get('BitsPerFlag'),
  15193. decode: dict.get('Decode'),
  15194. colorFn: fn,
  15195. colorSpace: cs,
  15196. numComps: fn ? 1 : cs.numComps
  15197. };
  15198. var reader = new MeshStreamReader(stream, decodeContext);
  15199. var patchMesh = false;
  15200. switch (this.shadingType) {
  15201. case PatternType.FREE_FORM_MESH:
  15202. decodeType4Shading(this, reader);
  15203. break;
  15204. case PatternType.LATTICE_FORM_MESH:
  15205. var verticesPerRow = dict.get('VerticesPerRow') | 0;
  15206. assert(verticesPerRow >= 2, 'Invalid VerticesPerRow');
  15207. decodeType5Shading(this, reader, verticesPerRow);
  15208. break;
  15209. case PatternType.COONS_PATCH_MESH:
  15210. decodeType6Shading(this, reader);
  15211. patchMesh = true;
  15212. break;
  15213. case PatternType.TENSOR_PATCH_MESH:
  15214. decodeType7Shading(this, reader);
  15215. patchMesh = true;
  15216. break;
  15217. default:
  15218. error('Unsupported mesh type.');
  15219. break;
  15220. }
  15221. if (patchMesh) {
  15222. // dirty bounds calculation for determining, how dense shall be triangles
  15223. updateBounds(this);
  15224. for (var i = 0, ii = this.figures.length; i < ii; i++) {
  15225. buildFigureFromPatch(this, i);
  15226. }
  15227. }
  15228. // calculate bounds
  15229. updateBounds(this);
  15230. packData(this);
  15231. }
  15232. Mesh.prototype = {
  15233. getIR: function Mesh_getIR() {
  15234. return ['Mesh', this.shadingType, this.coords, this.colors, this.figures,
  15235. this.bounds, this.matrix, this.bbox, this.background];
  15236. }
  15237. };
  15238. return Mesh;
  15239. })();
  15240. Shadings.Dummy = (function DummyClosure() {
  15241. function Dummy() {
  15242. this.type = 'Pattern';
  15243. }
  15244. Dummy.prototype = {
  15245. getIR: function Dummy_getIR() {
  15246. return ['Dummy'];
  15247. }
  15248. };
  15249. return Dummy;
  15250. })();
  15251. function getTilingPatternIR(operatorList, dict, args) {
  15252. var matrix = dict.get('Matrix');
  15253. var bbox = dict.get('BBox');
  15254. var xstep = dict.get('XStep');
  15255. var ystep = dict.get('YStep');
  15256. var paintType = dict.get('PaintType');
  15257. var tilingType = dict.get('TilingType');
  15258. return [
  15259. 'TilingPattern', args, operatorList, matrix, bbox, xstep, ystep,
  15260. paintType, tilingType
  15261. ];
  15262. }
  15263. var PartialEvaluator = (function PartialEvaluatorClosure() {
  15264. function PartialEvaluator(pdfManager, xref, handler, pageIndex,
  15265. uniquePrefix, idCounters, fontCache) {
  15266. this.pdfManager = pdfManager;
  15267. this.xref = xref;
  15268. this.handler = handler;
  15269. this.pageIndex = pageIndex;
  15270. this.uniquePrefix = uniquePrefix;
  15271. this.idCounters = idCounters;
  15272. this.fontCache = fontCache;
  15273. }
  15274. // Trying to minimize Date.now() usage and check every 100 time
  15275. var TIME_SLOT_DURATION_MS = 20;
  15276. var CHECK_TIME_EVERY = 100;
  15277. function TimeSlotManager() {
  15278. this.reset();
  15279. }
  15280. TimeSlotManager.prototype = {
  15281. check: function TimeSlotManager_check() {
  15282. if (++this.checked < CHECK_TIME_EVERY) {
  15283. return false;
  15284. }
  15285. this.checked = 0;
  15286. return this.endTime <= Date.now();
  15287. },
  15288. reset: function TimeSlotManager_reset() {
  15289. this.endTime = Date.now() + TIME_SLOT_DURATION_MS;
  15290. this.checked = 0;
  15291. }
  15292. };
  15293. var deferred = Promise.resolve();
  15294. var TILING_PATTERN = 1, SHADING_PATTERN = 2;
  15295. PartialEvaluator.prototype = {
  15296. hasBlendModes: function PartialEvaluator_hasBlendModes(resources) {
  15297. if (!isDict(resources)) {
  15298. return false;
  15299. }
  15300. var processed = Object.create(null);
  15301. if (resources.objId) {
  15302. processed[resources.objId] = true;
  15303. }
  15304. var nodes = [resources];
  15305. while (nodes.length) {
  15306. var key;
  15307. var node = nodes.shift();
  15308. // First check the current resources for blend modes.
  15309. var graphicStates = node.get('ExtGState');
  15310. if (isDict(graphicStates)) {
  15311. graphicStates = graphicStates.getAll();
  15312. for (key in graphicStates) {
  15313. var graphicState = graphicStates[key];
  15314. var bm = graphicState['BM'];
  15315. if (isName(bm) && bm.name !== 'Normal') {
  15316. return true;
  15317. }
  15318. }
  15319. }
  15320. // Descend into the XObjects to look for more resources and blend modes.
  15321. var xObjects = node.get('XObject');
  15322. if (!isDict(xObjects)) {
  15323. continue;
  15324. }
  15325. xObjects = xObjects.getAll();
  15326. for (key in xObjects) {
  15327. var xObject = xObjects[key];
  15328. if (!isStream(xObject)) {
  15329. continue;
  15330. }
  15331. if (xObject.dict.objId) {
  15332. if (processed[xObject.dict.objId]) {
  15333. // stream has objId and is processed already
  15334. continue;
  15335. }
  15336. processed[xObject.dict.objId] = true;
  15337. }
  15338. var xResources = xObject.dict.get('Resources');
  15339. // Checking objId to detect an infinite loop.
  15340. if (isDict(xResources) &&
  15341. (!xResources.objId || !processed[xResources.objId])) {
  15342. nodes.push(xResources);
  15343. if (xResources.objId) {
  15344. processed[xResources.objId] = true;
  15345. }
  15346. }
  15347. }
  15348. }
  15349. return false;
  15350. },
  15351. buildFormXObject: function PartialEvaluator_buildFormXObject(resources,
  15352. xobj, smask,
  15353. operatorList,
  15354. initialState) {
  15355. var matrix = xobj.dict.get('Matrix');
  15356. var bbox = xobj.dict.get('BBox');
  15357. var group = xobj.dict.get('Group');
  15358. if (group) {
  15359. var groupOptions = {
  15360. matrix: matrix,
  15361. bbox: bbox,
  15362. smask: smask,
  15363. isolated: false,
  15364. knockout: false
  15365. };
  15366. var groupSubtype = group.get('S');
  15367. var colorSpace;
  15368. if (isName(groupSubtype) && groupSubtype.name === 'Transparency') {
  15369. groupOptions.isolated = (group.get('I') || false);
  15370. groupOptions.knockout = (group.get('K') || false);
  15371. colorSpace = (group.has('CS') ?
  15372. ColorSpace.parse(group.get('CS'), this.xref, resources) : null);
  15373. }
  15374. if (smask && smask.backdrop) {
  15375. colorSpace = colorSpace || ColorSpace.singletons.rgb;
  15376. smask.backdrop = colorSpace.getRgb(smask.backdrop, 0);
  15377. }
  15378. operatorList.addOp(OPS.beginGroup, [groupOptions]);
  15379. }
  15380. operatorList.addOp(OPS.paintFormXObjectBegin, [matrix, bbox]);
  15381. return this.getOperatorList(xobj,
  15382. (xobj.dict.get('Resources') || resources), operatorList, initialState).
  15383. then(function () {
  15384. operatorList.addOp(OPS.paintFormXObjectEnd, []);
  15385. if (group) {
  15386. operatorList.addOp(OPS.endGroup, [groupOptions]);
  15387. }
  15388. });
  15389. },
  15390. buildPaintImageXObject:
  15391. function PartialEvaluator_buildPaintImageXObject(resources, image,
  15392. inline, operatorList,
  15393. cacheKey, imageCache) {
  15394. var self = this;
  15395. var dict = image.dict;
  15396. var w = dict.get('Width', 'W');
  15397. var h = dict.get('Height', 'H');
  15398. if (!(w && isNum(w)) || !(h && isNum(h))) {
  15399. warn('Image dimensions are missing, or not numbers.');
  15400. return;
  15401. }
  15402. if (PDFJS.maxImageSize !== -1 && w * h > PDFJS.maxImageSize) {
  15403. warn('Image exceeded maximum allowed size and was removed.');
  15404. return;
  15405. }
  15406. var imageMask = (dict.get('ImageMask', 'IM') || false);
  15407. var imgData, args;
  15408. if (imageMask) {
  15409. // This depends on a tmpCanvas being filled with the
  15410. // current fillStyle, such that processing the pixel
  15411. // data can't be done here. Instead of creating a
  15412. // complete PDFImage, only read the information needed
  15413. // for later.
  15414. var width = dict.get('Width', 'W');
  15415. var height = dict.get('Height', 'H');
  15416. var bitStrideLength = (width + 7) >> 3;
  15417. var imgArray = image.getBytes(bitStrideLength * height);
  15418. var decode = dict.get('Decode', 'D');
  15419. var inverseDecode = (!!decode && decode[0] > 0);
  15420. imgData = PDFImage.createMask(imgArray, width, height,
  15421. image instanceof DecodeStream,
  15422. inverseDecode);
  15423. imgData.cached = true;
  15424. args = [imgData];
  15425. operatorList.addOp(OPS.paintImageMaskXObject, args);
  15426. if (cacheKey) {
  15427. imageCache[cacheKey] = {
  15428. fn: OPS.paintImageMaskXObject,
  15429. args: args
  15430. };
  15431. }
  15432. return;
  15433. }
  15434. var softMask = (dict.get('SMask', 'SM') || false);
  15435. var mask = (dict.get('Mask') || false);
  15436. var SMALL_IMAGE_DIMENSIONS = 200;
  15437. // Inlining small images into the queue as RGB data
  15438. if (inline && !softMask && !mask && !(image instanceof JpegStream) &&
  15439. (w + h) < SMALL_IMAGE_DIMENSIONS) {
  15440. var imageObj = new PDFImage(this.xref, resources, image,
  15441. inline, null, null);
  15442. // We force the use of RGBA_32BPP images here, because we can't handle
  15443. // any other kind.
  15444. imgData = imageObj.createImageData(/* forceRGBA = */ true);
  15445. operatorList.addOp(OPS.paintInlineImageXObject, [imgData]);
  15446. return;
  15447. }
  15448. // If there is no imageMask, create the PDFImage and a lot
  15449. // of image processing can be done here.
  15450. var uniquePrefix = (this.uniquePrefix || '');
  15451. var objId = 'img_' + uniquePrefix + (++this.idCounters.obj);
  15452. operatorList.addDependency(objId);
  15453. args = [objId, w, h];
  15454. if (!softMask && !mask && image instanceof JpegStream &&
  15455. image.isNativelySupported(this.xref, resources)) {
  15456. // These JPEGs don't need any more processing so we can just send it.
  15457. operatorList.addOp(OPS.paintJpegXObject, args);
  15458. this.handler.send('obj',
  15459. [objId, this.pageIndex, 'JpegStream', image.getIR()]);
  15460. return;
  15461. }
  15462. PDFImage.buildImage(self.handler, self.xref, resources, image, inline).
  15463. then(function(imageObj) {
  15464. var imgData = imageObj.createImageData(/* forceRGBA = */ false);
  15465. self.handler.send('obj', [objId, self.pageIndex, 'Image', imgData],
  15466. [imgData.data.buffer]);
  15467. }).then(undefined, function (reason) {
  15468. warn('Unable to decode image: ' + reason);
  15469. self.handler.send('obj', [objId, self.pageIndex, 'Image', null]);
  15470. });
  15471. operatorList.addOp(OPS.paintImageXObject, args);
  15472. if (cacheKey) {
  15473. imageCache[cacheKey] = {
  15474. fn: OPS.paintImageXObject,
  15475. args: args
  15476. };
  15477. }
  15478. },
  15479. handleSMask: function PartialEvaluator_handleSmask(smask, resources,
  15480. operatorList,
  15481. stateManager) {
  15482. var smaskContent = smask.get('G');
  15483. var smaskOptions = {
  15484. subtype: smask.get('S').name,
  15485. backdrop: smask.get('BC')
  15486. };
  15487. return this.buildFormXObject(resources, smaskContent, smaskOptions,
  15488. operatorList, stateManager.state.clone());
  15489. },
  15490. handleTilingType:
  15491. function PartialEvaluator_handleTilingType(fn, args, resources,
  15492. pattern, patternDict,
  15493. operatorList) {
  15494. // Create an IR of the pattern code.
  15495. var tilingOpList = new OperatorList();
  15496. return this.getOperatorList(pattern,
  15497. (patternDict.get('Resources') || resources), tilingOpList).
  15498. then(function () {
  15499. // Add the dependencies to the parent operator list so they are
  15500. // resolved before sub operator list is executed synchronously.
  15501. operatorList.addDependencies(tilingOpList.dependencies);
  15502. operatorList.addOp(fn, getTilingPatternIR({
  15503. fnArray: tilingOpList.fnArray,
  15504. argsArray: tilingOpList.argsArray
  15505. }, patternDict, args));
  15506. });
  15507. },
  15508. handleSetFont:
  15509. function PartialEvaluator_handleSetFont(resources, fontArgs, fontRef,
  15510. operatorList, state) {
  15511. // TODO(mack): Not needed?
  15512. var fontName;
  15513. if (fontArgs) {
  15514. fontArgs = fontArgs.slice();
  15515. fontName = fontArgs[0].name;
  15516. }
  15517. var self = this;
  15518. return this.loadFont(fontName, fontRef, this.xref, resources).then(
  15519. function (translated) {
  15520. if (!translated.font.isType3Font) {
  15521. return translated;
  15522. }
  15523. return translated.loadType3Data(self, resources, operatorList).then(
  15524. function () {
  15525. return translated;
  15526. });
  15527. }).then(function (translated) {
  15528. state.font = translated.font;
  15529. translated.send(self.handler);
  15530. return translated.loadedName;
  15531. });
  15532. },
  15533. handleText: function PartialEvaluator_handleText(chars, state) {
  15534. var font = state.font;
  15535. var glyphs = font.charsToGlyphs(chars);
  15536. var isAddToPathSet = !!(state.textRenderingMode &
  15537. TextRenderingMode.ADD_TO_PATH_FLAG);
  15538. if (font.data && (isAddToPathSet || PDFJS.disableFontFace)) {
  15539. var buildPath = function (fontChar) {
  15540. if (!font.renderer.hasBuiltPath(fontChar)) {
  15541. var path = font.renderer.getPathJs(fontChar);
  15542. this.handler.send('commonobj', [
  15543. font.loadedName + '_path_' + fontChar,
  15544. 'FontPath',
  15545. path
  15546. ]);
  15547. }
  15548. }.bind(this);
  15549. for (var i = 0, ii = glyphs.length; i < ii; i++) {
  15550. var glyph = glyphs[i];
  15551. if (glyph === null) {
  15552. continue;
  15553. }
  15554. buildPath(glyph.fontChar);
  15555. // If the glyph has an accent we need to build a path for its
  15556. // fontChar too, otherwise CanvasGraphics_paintChar will fail.
  15557. var accent = glyph.accent;
  15558. if (accent && accent.fontChar) {
  15559. buildPath(accent.fontChar);
  15560. }
  15561. }
  15562. }
  15563. return glyphs;
  15564. },
  15565. setGState: function PartialEvaluator_setGState(resources, gState,
  15566. operatorList, xref,
  15567. stateManager) {
  15568. // This array holds the converted/processed state data.
  15569. var gStateObj = [];
  15570. var gStateMap = gState.map;
  15571. var self = this;
  15572. var promise = Promise.resolve();
  15573. for (var key in gStateMap) {
  15574. var value = gStateMap[key];
  15575. switch (key) {
  15576. case 'Type':
  15577. break;
  15578. case 'LW':
  15579. case 'LC':
  15580. case 'LJ':
  15581. case 'ML':
  15582. case 'D':
  15583. case 'RI':
  15584. case 'FL':
  15585. case 'CA':
  15586. case 'ca':
  15587. gStateObj.push([key, value]);
  15588. break;
  15589. case 'Font':
  15590. promise = promise.then(function () {
  15591. return self.handleSetFont(resources, null, value[0],
  15592. operatorList, stateManager.state).
  15593. then(function (loadedName) {
  15594. operatorList.addDependency(loadedName);
  15595. gStateObj.push([key, [loadedName, value[1]]]);
  15596. });
  15597. });
  15598. break;
  15599. case 'BM':
  15600. gStateObj.push([key, value]);
  15601. break;
  15602. case 'SMask':
  15603. if (isName(value) && value.name === 'None') {
  15604. gStateObj.push([key, false]);
  15605. break;
  15606. }
  15607. var dict = xref.fetchIfRef(value);
  15608. if (isDict(dict)) {
  15609. promise = promise.then(function () {
  15610. return self.handleSMask(dict, resources, operatorList,
  15611. stateManager);
  15612. });
  15613. gStateObj.push([key, true]);
  15614. } else {
  15615. warn('Unsupported SMask type');
  15616. }
  15617. break;
  15618. // Only generate info log messages for the following since
  15619. // they are unlikely to have a big impact on the rendering.
  15620. case 'OP':
  15621. case 'op':
  15622. case 'OPM':
  15623. case 'BG':
  15624. case 'BG2':
  15625. case 'UCR':
  15626. case 'UCR2':
  15627. case 'TR':
  15628. case 'TR2':
  15629. case 'HT':
  15630. case 'SM':
  15631. case 'SA':
  15632. case 'AIS':
  15633. case 'TK':
  15634. // TODO implement these operators.
  15635. info('graphic state operator ' + key);
  15636. break;
  15637. default:
  15638. info('Unknown graphic state operator ' + key);
  15639. break;
  15640. }
  15641. }
  15642. return promise.then(function () {
  15643. if (gStateObj.length >= 0) {
  15644. operatorList.addOp(OPS.setGState, [gStateObj]);
  15645. }
  15646. });
  15647. },
  15648. loadFont: function PartialEvaluator_loadFont(fontName, font, xref,
  15649. resources) {
  15650. function errorFont() {
  15651. return Promise.resolve(new TranslatedFont('g_font_error',
  15652. new ErrorFont('Font ' + fontName + ' is not available'), font));
  15653. }
  15654. var fontRef;
  15655. if (font) { // Loading by ref.
  15656. assert(isRef(font));
  15657. fontRef = font;
  15658. } else { // Loading by name.
  15659. var fontRes = resources.get('Font');
  15660. if (fontRes) {
  15661. fontRef = fontRes.getRaw(fontName);
  15662. } else {
  15663. warn('fontRes not available');
  15664. return errorFont();
  15665. }
  15666. }
  15667. if (!fontRef) {
  15668. warn('fontRef not available');
  15669. return errorFont();
  15670. }
  15671. if (this.fontCache.has(fontRef)) {
  15672. return this.fontCache.get(fontRef);
  15673. }
  15674. font = xref.fetchIfRef(fontRef);
  15675. if (!isDict(font)) {
  15676. return errorFont();
  15677. }
  15678. // We are holding font.translated references just for fontRef that are not
  15679. // dictionaries (Dict). See explanation below.
  15680. if (font.translated) {
  15681. return font.translated;
  15682. }
  15683. var fontCapability = createPromiseCapability();
  15684. var preEvaluatedFont = this.preEvaluateFont(font, xref);
  15685. var descriptor = preEvaluatedFont.descriptor;
  15686. var fontID = fontRef.num + '_' + fontRef.gen;
  15687. if (isDict(descriptor)) {
  15688. if (!descriptor.fontAliases) {
  15689. descriptor.fontAliases = Object.create(null);
  15690. }
  15691. var fontAliases = descriptor.fontAliases;
  15692. var hash = preEvaluatedFont.hash;
  15693. if (fontAliases[hash]) {
  15694. var aliasFontRef = fontAliases[hash].aliasRef;
  15695. if (aliasFontRef && this.fontCache.has(aliasFontRef)) {
  15696. this.fontCache.putAlias(fontRef, aliasFontRef);
  15697. return this.fontCache.get(fontRef);
  15698. }
  15699. }
  15700. if (!fontAliases[hash]) {
  15701. fontAliases[hash] = {
  15702. fontID: Font.getFontID()
  15703. };
  15704. }
  15705. fontAliases[hash].aliasRef = fontRef;
  15706. fontID = fontAliases[hash].fontID;
  15707. }
  15708. // Workaround for bad PDF generators that don't reference fonts
  15709. // properly, i.e. by not using an object identifier.
  15710. // Check if the fontRef is a Dict (as opposed to a standard object),
  15711. // in which case we don't cache the font and instead reference it by
  15712. // fontName in font.loadedName below.
  15713. var fontRefIsDict = isDict(fontRef);
  15714. if (!fontRefIsDict) {
  15715. this.fontCache.put(fontRef, fontCapability.promise);
  15716. }
  15717. // Keep track of each font we translated so the caller can
  15718. // load them asynchronously before calling display on a page.
  15719. font.loadedName = 'g_font_' + (fontRefIsDict ?
  15720. fontName.replace(/\W/g, '') : fontID);
  15721. font.translated = fontCapability.promise;
  15722. // TODO move promises into translate font
  15723. var translatedPromise;
  15724. try {
  15725. translatedPromise = Promise.resolve(
  15726. this.translateFont(preEvaluatedFont, xref));
  15727. } catch (e) {
  15728. translatedPromise = Promise.reject(e);
  15729. }
  15730. translatedPromise.then(function (translatedFont) {
  15731. if (translatedFont.fontType !== undefined) {
  15732. var xrefFontStats = xref.stats.fontTypes;
  15733. xrefFontStats[translatedFont.fontType] = true;
  15734. }
  15735. fontCapability.resolve(new TranslatedFont(font.loadedName,
  15736. translatedFont, font));
  15737. }, function (reason) {
  15738. // TODO fontCapability.reject?
  15739. UnsupportedManager.notify(UNSUPPORTED_FEATURES.font);
  15740. try {
  15741. // error, but it's still nice to have font type reported
  15742. var descriptor = preEvaluatedFont.descriptor;
  15743. var fontFile3 = descriptor && descriptor.get('FontFile3');
  15744. var subtype = fontFile3 && fontFile3.get('Subtype');
  15745. var fontType = getFontType(preEvaluatedFont.type,
  15746. subtype && subtype.name);
  15747. var xrefFontStats = xref.stats.fontTypes;
  15748. xrefFontStats[fontType] = true;
  15749. } catch (ex) { }
  15750. fontCapability.resolve(new TranslatedFont(font.loadedName,
  15751. new ErrorFont(reason instanceof Error ? reason.message : reason),
  15752. font));
  15753. });
  15754. return fontCapability.promise;
  15755. },
  15756. buildPath: function PartialEvaluator_buildPath(operatorList, fn, args) {
  15757. var lastIndex = operatorList.length - 1;
  15758. if (!args) {
  15759. args = [];
  15760. }
  15761. if (lastIndex < 0 ||
  15762. operatorList.fnArray[lastIndex] !== OPS.constructPath) {
  15763. operatorList.addOp(OPS.constructPath, [[fn], args]);
  15764. } else {
  15765. var opArgs = operatorList.argsArray[lastIndex];
  15766. opArgs[0].push(fn);
  15767. Array.prototype.push.apply(opArgs[1], args);
  15768. }
  15769. },
  15770. handleColorN: function PartialEvaluator_handleColorN(operatorList, fn, args,
  15771. cs, patterns, resources, xref) {
  15772. // compile tiling patterns
  15773. var patternName = args[args.length - 1];
  15774. // SCN/scn applies patterns along with normal colors
  15775. var pattern;
  15776. if (isName(patternName) &&
  15777. (pattern = patterns.get(patternName.name))) {
  15778. var dict = (isStream(pattern) ? pattern.dict : pattern);
  15779. var typeNum = dict.get('PatternType');
  15780. if (typeNum === TILING_PATTERN) {
  15781. var color = cs.base ? cs.base.getRgb(args, 0) : null;
  15782. return this.handleTilingType(fn, color, resources, pattern,
  15783. dict, operatorList);
  15784. } else if (typeNum === SHADING_PATTERN) {
  15785. var shading = dict.get('Shading');
  15786. var matrix = dict.get('Matrix');
  15787. pattern = Pattern.parseShading(shading, matrix, xref, resources);
  15788. operatorList.addOp(fn, pattern.getIR());
  15789. return Promise.resolve();
  15790. } else {
  15791. return Promise.reject('Unknown PatternType: ' + typeNum);
  15792. }
  15793. }
  15794. // TODO shall we fail here?
  15795. operatorList.addOp(fn, args);
  15796. return Promise.resolve();
  15797. },
  15798. getOperatorList: function PartialEvaluator_getOperatorList(stream,
  15799. resources,
  15800. operatorList,
  15801. initialState) {
  15802. var self = this;
  15803. var xref = this.xref;
  15804. var imageCache = {};
  15805. assert(operatorList);
  15806. resources = (resources || Dict.empty);
  15807. var xobjs = (resources.get('XObject') || Dict.empty);
  15808. var patterns = (resources.get('Pattern') || Dict.empty);
  15809. var stateManager = new StateManager(initialState || new EvalState());
  15810. var preprocessor = new EvaluatorPreprocessor(stream, xref, stateManager);
  15811. var timeSlotManager = new TimeSlotManager();
  15812. return new Promise(function next(resolve, reject) {
  15813. timeSlotManager.reset();
  15814. var stop, operation = {}, i, ii, cs;
  15815. while (!(stop = timeSlotManager.check())) {
  15816. // The arguments parsed by read() are used beyond this loop, so we
  15817. // cannot reuse the same array on each iteration. Therefore we pass
  15818. // in |null| as the initial value (see the comment on
  15819. // EvaluatorPreprocessor_read() for why).
  15820. operation.args = null;
  15821. if (!(preprocessor.read(operation))) {
  15822. break;
  15823. }
  15824. var args = operation.args;
  15825. var fn = operation.fn;
  15826. switch (fn | 0) {
  15827. case OPS.paintXObject:
  15828. if (args[0].code) {
  15829. break;
  15830. }
  15831. // eagerly compile XForm objects
  15832. var name = args[0].name;
  15833. if (!name) {
  15834. warn('XObject must be referred to by name.');
  15835. continue;
  15836. }
  15837. if (imageCache[name] !== undefined) {
  15838. operatorList.addOp(imageCache[name].fn, imageCache[name].args);
  15839. args = null;
  15840. continue;
  15841. }
  15842. var xobj = xobjs.get(name);
  15843. if (xobj) {
  15844. assert(isStream(xobj), 'XObject should be a stream');
  15845. var type = xobj.dict.get('Subtype');
  15846. assert(isName(type),
  15847. 'XObject should have a Name subtype');
  15848. if (type.name === 'Form') {
  15849. stateManager.save();
  15850. return self.buildFormXObject(resources, xobj, null,
  15851. operatorList,
  15852. stateManager.state.clone()).
  15853. then(function () {
  15854. stateManager.restore();
  15855. next(resolve, reject);
  15856. }, reject);
  15857. } else if (type.name === 'Image') {
  15858. self.buildPaintImageXObject(resources, xobj, false,
  15859. operatorList, name, imageCache);
  15860. args = null;
  15861. continue;
  15862. } else if (type.name === 'PS') {
  15863. // PostScript XObjects are unused when viewing documents.
  15864. // See section 4.7.1 of Adobe's PDF reference.
  15865. info('Ignored XObject subtype PS');
  15866. continue;
  15867. } else {
  15868. error('Unhandled XObject subtype ' + type.name);
  15869. }
  15870. }
  15871. break;
  15872. case OPS.setFont:
  15873. var fontSize = args[1];
  15874. // eagerly collect all fonts
  15875. return self.handleSetFont(resources, args, null,
  15876. operatorList, stateManager.state).
  15877. then(function (loadedName) {
  15878. operatorList.addDependency(loadedName);
  15879. operatorList.addOp(OPS.setFont, [loadedName, fontSize]);
  15880. next(resolve, reject);
  15881. }, reject);
  15882. case OPS.endInlineImage:
  15883. var cacheKey = args[0].cacheKey;
  15884. if (cacheKey) {
  15885. var cacheEntry = imageCache[cacheKey];
  15886. if (cacheEntry !== undefined) {
  15887. operatorList.addOp(cacheEntry.fn, cacheEntry.args);
  15888. args = null;
  15889. continue;
  15890. }
  15891. }
  15892. self.buildPaintImageXObject(resources, args[0], true,
  15893. operatorList, cacheKey, imageCache);
  15894. args = null;
  15895. continue;
  15896. case OPS.showText:
  15897. args[0] = self.handleText(args[0], stateManager.state);
  15898. break;
  15899. case OPS.showSpacedText:
  15900. var arr = args[0];
  15901. var combinedGlyphs = [];
  15902. var arrLength = arr.length;
  15903. for (i = 0; i < arrLength; ++i) {
  15904. var arrItem = arr[i];
  15905. if (isString(arrItem)) {
  15906. Array.prototype.push.apply(combinedGlyphs,
  15907. self.handleText(arrItem, stateManager.state));
  15908. } else if (isNum(arrItem)) {
  15909. combinedGlyphs.push(arrItem);
  15910. }
  15911. }
  15912. args[0] = combinedGlyphs;
  15913. fn = OPS.showText;
  15914. break;
  15915. case OPS.nextLineShowText:
  15916. operatorList.addOp(OPS.nextLine);
  15917. args[0] = self.handleText(args[0], stateManager.state);
  15918. fn = OPS.showText;
  15919. break;
  15920. case OPS.nextLineSetSpacingShowText:
  15921. operatorList.addOp(OPS.nextLine);
  15922. operatorList.addOp(OPS.setWordSpacing, [args.shift()]);
  15923. operatorList.addOp(OPS.setCharSpacing, [args.shift()]);
  15924. args[0] = self.handleText(args[0], stateManager.state);
  15925. fn = OPS.showText;
  15926. break;
  15927. case OPS.setTextRenderingMode:
  15928. stateManager.state.textRenderingMode = args[0];
  15929. break;
  15930. case OPS.setFillColorSpace:
  15931. stateManager.state.fillColorSpace =
  15932. ColorSpace.parse(args[0], xref, resources);
  15933. continue;
  15934. case OPS.setStrokeColorSpace:
  15935. stateManager.state.strokeColorSpace =
  15936. ColorSpace.parse(args[0], xref, resources);
  15937. continue;
  15938. case OPS.setFillColor:
  15939. cs = stateManager.state.fillColorSpace;
  15940. args = cs.getRgb(args, 0);
  15941. fn = OPS.setFillRGBColor;
  15942. break;
  15943. case OPS.setStrokeColor:
  15944. cs = stateManager.state.strokeColorSpace;
  15945. args = cs.getRgb(args, 0);
  15946. fn = OPS.setStrokeRGBColor;
  15947. break;
  15948. case OPS.setFillGray:
  15949. stateManager.state.fillColorSpace = ColorSpace.singletons.gray;
  15950. args = ColorSpace.singletons.gray.getRgb(args, 0);
  15951. fn = OPS.setFillRGBColor;
  15952. break;
  15953. case OPS.setStrokeGray:
  15954. stateManager.state.strokeColorSpace = ColorSpace.singletons.gray;
  15955. args = ColorSpace.singletons.gray.getRgb(args, 0);
  15956. fn = OPS.setStrokeRGBColor;
  15957. break;
  15958. case OPS.setFillCMYKColor:
  15959. stateManager.state.fillColorSpace = ColorSpace.singletons.cmyk;
  15960. args = ColorSpace.singletons.cmyk.getRgb(args, 0);
  15961. fn = OPS.setFillRGBColor;
  15962. break;
  15963. case OPS.setStrokeCMYKColor:
  15964. stateManager.state.strokeColorSpace = ColorSpace.singletons.cmyk;
  15965. args = ColorSpace.singletons.cmyk.getRgb(args, 0);
  15966. fn = OPS.setStrokeRGBColor;
  15967. break;
  15968. case OPS.setFillRGBColor:
  15969. stateManager.state.fillColorSpace = ColorSpace.singletons.rgb;
  15970. args = ColorSpace.singletons.rgb.getRgb(args, 0);
  15971. break;
  15972. case OPS.setStrokeRGBColor:
  15973. stateManager.state.strokeColorSpace = ColorSpace.singletons.rgb;
  15974. args = ColorSpace.singletons.rgb.getRgb(args, 0);
  15975. break;
  15976. case OPS.setFillColorN:
  15977. cs = stateManager.state.fillColorSpace;
  15978. if (cs.name === 'Pattern') {
  15979. return self.handleColorN(operatorList, OPS.setFillColorN,
  15980. args, cs, patterns, resources, xref).then(function() {
  15981. next(resolve, reject);
  15982. }, reject);
  15983. }
  15984. args = cs.getRgb(args, 0);
  15985. fn = OPS.setFillRGBColor;
  15986. break;
  15987. case OPS.setStrokeColorN:
  15988. cs = stateManager.state.strokeColorSpace;
  15989. if (cs.name === 'Pattern') {
  15990. return self.handleColorN(operatorList, OPS.setStrokeColorN,
  15991. args, cs, patterns, resources, xref).then(function() {
  15992. next(resolve, reject);
  15993. }, reject);
  15994. }
  15995. args = cs.getRgb(args, 0);
  15996. fn = OPS.setStrokeRGBColor;
  15997. break;
  15998. case OPS.shadingFill:
  15999. var shadingRes = resources.get('Shading');
  16000. if (!shadingRes) {
  16001. error('No shading resource found');
  16002. }
  16003. var shading = shadingRes.get(args[0].name);
  16004. if (!shading) {
  16005. error('No shading object found');
  16006. }
  16007. var shadingFill = Pattern.parseShading(shading, null, xref,
  16008. resources);
  16009. var patternIR = shadingFill.getIR();
  16010. args = [patternIR];
  16011. fn = OPS.shadingFill;
  16012. break;
  16013. case OPS.setGState:
  16014. var dictName = args[0];
  16015. var extGState = resources.get('ExtGState');
  16016. if (!isDict(extGState) || !extGState.has(dictName.name)) {
  16017. break;
  16018. }
  16019. var gState = extGState.get(dictName.name);
  16020. return self.setGState(resources, gState, operatorList, xref,
  16021. stateManager).then(function() {
  16022. next(resolve, reject);
  16023. }, reject);
  16024. case OPS.moveTo:
  16025. case OPS.lineTo:
  16026. case OPS.curveTo:
  16027. case OPS.curveTo2:
  16028. case OPS.curveTo3:
  16029. case OPS.closePath:
  16030. self.buildPath(operatorList, fn, args);
  16031. continue;
  16032. case OPS.rectangle:
  16033. self.buildPath(operatorList, fn, args);
  16034. continue;
  16035. }
  16036. operatorList.addOp(fn, args);
  16037. }
  16038. if (stop) {
  16039. deferred.then(function () {
  16040. next(resolve, reject);
  16041. });
  16042. return;
  16043. }
  16044. // Some PDFs don't close all restores inside object/form.
  16045. // Closing those for them.
  16046. for (i = 0, ii = preprocessor.savedStatesDepth; i < ii; i++) {
  16047. operatorList.addOp(OPS.restore, []);
  16048. }
  16049. resolve();
  16050. });
  16051. },
  16052. getTextContent: function PartialEvaluator_getTextContent(stream, resources,
  16053. stateManager) {
  16054. stateManager = (stateManager || new StateManager(new TextState()));
  16055. var textContent = {
  16056. items: [],
  16057. styles: Object.create(null)
  16058. };
  16059. var bidiTexts = textContent.items;
  16060. var SPACE_FACTOR = 0.3;
  16061. var MULTI_SPACE_FACTOR = 1.5;
  16062. var self = this;
  16063. var xref = this.xref;
  16064. resources = (xref.fetchIfRef(resources) || Dict.empty);
  16065. // The xobj is parsed iff it's needed, e.g. if there is a `DO` cmd.
  16066. var xobjs = null;
  16067. var xobjsCache = {};
  16068. var preprocessor = new EvaluatorPreprocessor(stream, xref, stateManager);
  16069. var textState;
  16070. function newTextChunk() {
  16071. var font = textState.font;
  16072. if (!(font.loadedName in textContent.styles)) {
  16073. textContent.styles[font.loadedName] = {
  16074. fontFamily: font.fallbackName,
  16075. ascent: font.ascent,
  16076. descent: font.descent,
  16077. vertical: font.vertical
  16078. };
  16079. }
  16080. return {
  16081. // |str| is initially an array which we push individual chars to, and
  16082. // then runBidi() overwrites it with the final string.
  16083. str: [],
  16084. dir: null,
  16085. width: 0,
  16086. height: 0,
  16087. transform: null,
  16088. fontName: font.loadedName
  16089. };
  16090. }
  16091. function runBidi(textChunk) {
  16092. var str = textChunk.str.join('');
  16093. var bidiResult = PDFJS.bidi(str, -1, textState.font.vertical);
  16094. textChunk.str = bidiResult.str;
  16095. textChunk.dir = bidiResult.dir;
  16096. return textChunk;
  16097. }
  16098. function handleSetFont(fontName, fontRef) {
  16099. return self.loadFont(fontName, fontRef, xref, resources).
  16100. then(function (translated) {
  16101. textState.font = translated.font;
  16102. textState.fontMatrix = translated.font.fontMatrix ||
  16103. FONT_IDENTITY_MATRIX;
  16104. });
  16105. }
  16106. function buildTextGeometry(chars, textChunk) {
  16107. var font = textState.font;
  16108. textChunk = textChunk || newTextChunk();
  16109. if (!textChunk.transform) {
  16110. // 9.4.4 Text Space Details
  16111. var tsm = [textState.fontSize * textState.textHScale, 0,
  16112. 0, textState.fontSize,
  16113. 0, textState.textRise];
  16114. if (font.isType3Font &&
  16115. textState.fontMatrix !== FONT_IDENTITY_MATRIX &&
  16116. textState.fontSize === 1) {
  16117. var glyphHeight = font.bbox[3] - font.bbox[1];
  16118. if (glyphHeight > 0) {
  16119. glyphHeight = glyphHeight * textState.fontMatrix[3];
  16120. tsm[3] *= glyphHeight;
  16121. }
  16122. }
  16123. var trm = textChunk.transform = Util.transform(textState.ctm,
  16124. Util.transform(textState.textMatrix, tsm));
  16125. if (!font.vertical) {
  16126. textChunk.height = Math.sqrt(trm[2] * trm[2] + trm[3] * trm[3]);
  16127. } else {
  16128. textChunk.width = Math.sqrt(trm[0] * trm[0] + trm[1] * trm[1]);
  16129. }
  16130. }
  16131. var width = 0;
  16132. var height = 0;
  16133. var glyphs = font.charsToGlyphs(chars);
  16134. var defaultVMetrics = font.defaultVMetrics;
  16135. for (var i = 0; i < glyphs.length; i++) {
  16136. var glyph = glyphs[i];
  16137. if (!glyph) { // Previous glyph was a space.
  16138. width += textState.wordSpacing * textState.textHScale;
  16139. continue;
  16140. }
  16141. var vMetricX = null;
  16142. var vMetricY = null;
  16143. var glyphWidth = null;
  16144. if (font.vertical) {
  16145. if (glyph.vmetric) {
  16146. glyphWidth = glyph.vmetric[0];
  16147. vMetricX = glyph.vmetric[1];
  16148. vMetricY = glyph.vmetric[2];
  16149. } else {
  16150. glyphWidth = glyph.width;
  16151. vMetricX = glyph.width * 0.5;
  16152. vMetricY = defaultVMetrics[2];
  16153. }
  16154. } else {
  16155. glyphWidth = glyph.width;
  16156. }
  16157. var glyphUnicode = glyph.unicode;
  16158. if (NormalizedUnicodes[glyphUnicode] !== undefined) {
  16159. glyphUnicode = NormalizedUnicodes[glyphUnicode];
  16160. }
  16161. glyphUnicode = reverseIfRtl(glyphUnicode);
  16162. // The following will calculate the x and y of the individual glyphs.
  16163. // if (font.vertical) {
  16164. // tsm[4] -= vMetricX * Math.abs(textState.fontSize) *
  16165. // textState.fontMatrix[0];
  16166. // tsm[5] -= vMetricY * textState.fontSize *
  16167. // textState.fontMatrix[0];
  16168. // }
  16169. // var trm = Util.transform(textState.textMatrix, tsm);
  16170. // var pt = Util.applyTransform([trm[4], trm[5]], textState.ctm);
  16171. // var x = pt[0];
  16172. // var y = pt[1];
  16173. var charSpacing = 0;
  16174. if (textChunk.str.length > 0) {
  16175. // Apply char spacing only when there are chars.
  16176. // As a result there is only spacing between glyphs.
  16177. charSpacing = textState.charSpacing;
  16178. }
  16179. var tx = 0;
  16180. var ty = 0;
  16181. if (!font.vertical) {
  16182. var w0 = glyphWidth * textState.fontMatrix[0];
  16183. tx = (w0 * textState.fontSize + charSpacing) *
  16184. textState.textHScale;
  16185. width += tx;
  16186. } else {
  16187. var w1 = glyphWidth * textState.fontMatrix[0];
  16188. ty = w1 * textState.fontSize + charSpacing;
  16189. height += ty;
  16190. }
  16191. textState.translateTextMatrix(tx, ty);
  16192. textChunk.str.push(glyphUnicode);
  16193. }
  16194. var a = textState.textLineMatrix[0];
  16195. var b = textState.textLineMatrix[1];
  16196. var scaleLineX = Math.sqrt(a * a + b * b);
  16197. a = textState.ctm[0];
  16198. b = textState.ctm[1];
  16199. var scaleCtmX = Math.sqrt(a * a + b * b);
  16200. if (!font.vertical) {
  16201. textChunk.width += width * scaleCtmX * scaleLineX;
  16202. } else {
  16203. textChunk.height += Math.abs(height * scaleCtmX * scaleLineX);
  16204. }
  16205. return textChunk;
  16206. }
  16207. var timeSlotManager = new TimeSlotManager();
  16208. return new Promise(function next(resolve, reject) {
  16209. timeSlotManager.reset();
  16210. var stop, operation = {}, args = [];
  16211. while (!(stop = timeSlotManager.check())) {
  16212. // The arguments parsed by read() are not used beyond this loop, so
  16213. // we can reuse the same array on every iteration, thus avoiding
  16214. // unnecessary allocations.
  16215. args.length = 0;
  16216. operation.args = args;
  16217. if (!(preprocessor.read(operation))) {
  16218. break;
  16219. }
  16220. textState = stateManager.state;
  16221. var fn = operation.fn;
  16222. args = operation.args;
  16223. switch (fn | 0) {
  16224. case OPS.setFont:
  16225. textState.fontSize = args[1];
  16226. return handleSetFont(args[0].name).then(function() {
  16227. next(resolve, reject);
  16228. }, reject);
  16229. case OPS.setTextRise:
  16230. textState.textRise = args[0];
  16231. break;
  16232. case OPS.setHScale:
  16233. textState.textHScale = args[0] / 100;
  16234. break;
  16235. case OPS.setLeading:
  16236. textState.leading = args[0];
  16237. break;
  16238. case OPS.moveText:
  16239. textState.translateTextLineMatrix(args[0], args[1]);
  16240. textState.textMatrix = textState.textLineMatrix.slice();
  16241. break;
  16242. case OPS.setLeadingMoveText:
  16243. textState.leading = -args[1];
  16244. textState.translateTextLineMatrix(args[0], args[1]);
  16245. textState.textMatrix = textState.textLineMatrix.slice();
  16246. break;
  16247. case OPS.nextLine:
  16248. textState.carriageReturn();
  16249. break;
  16250. case OPS.setTextMatrix:
  16251. textState.setTextMatrix(args[0], args[1], args[2], args[3],
  16252. args[4], args[5]);
  16253. textState.setTextLineMatrix(args[0], args[1], args[2], args[3],
  16254. args[4], args[5]);
  16255. break;
  16256. case OPS.setCharSpacing:
  16257. textState.charSpacing = args[0];
  16258. break;
  16259. case OPS.setWordSpacing:
  16260. textState.wordSpacing = args[0];
  16261. break;
  16262. case OPS.beginText:
  16263. textState.textMatrix = IDENTITY_MATRIX.slice();
  16264. textState.textLineMatrix = IDENTITY_MATRIX.slice();
  16265. break;
  16266. case OPS.showSpacedText:
  16267. var items = args[0];
  16268. var textChunk = newTextChunk();
  16269. var offset;
  16270. for (var j = 0, jj = items.length; j < jj; j++) {
  16271. if (typeof items[j] === 'string') {
  16272. buildTextGeometry(items[j], textChunk);
  16273. } else {
  16274. var val = items[j] / 1000;
  16275. if (!textState.font.vertical) {
  16276. offset = -val * textState.fontSize * textState.textHScale *
  16277. textState.textMatrix[0];
  16278. textState.translateTextMatrix(offset, 0);
  16279. textChunk.width += offset;
  16280. } else {
  16281. offset = -val * textState.fontSize *
  16282. textState.textMatrix[3];
  16283. textState.translateTextMatrix(0, offset);
  16284. textChunk.height += offset;
  16285. }
  16286. if (items[j] < 0 && textState.font.spaceWidth > 0) {
  16287. var fakeSpaces = -items[j] / textState.font.spaceWidth;
  16288. if (fakeSpaces > MULTI_SPACE_FACTOR) {
  16289. fakeSpaces = Math.round(fakeSpaces);
  16290. while (fakeSpaces--) {
  16291. textChunk.str.push(' ');
  16292. }
  16293. } else if (fakeSpaces > SPACE_FACTOR) {
  16294. textChunk.str.push(' ');
  16295. }
  16296. }
  16297. }
  16298. }
  16299. bidiTexts.push(runBidi(textChunk));
  16300. break;
  16301. case OPS.showText:
  16302. bidiTexts.push(runBidi(buildTextGeometry(args[0])));
  16303. break;
  16304. case OPS.nextLineShowText:
  16305. textState.carriageReturn();
  16306. bidiTexts.push(runBidi(buildTextGeometry(args[0])));
  16307. break;
  16308. case OPS.nextLineSetSpacingShowText:
  16309. textState.wordSpacing = args[0];
  16310. textState.charSpacing = args[1];
  16311. textState.carriageReturn();
  16312. bidiTexts.push(runBidi(buildTextGeometry(args[2])));
  16313. break;
  16314. case OPS.paintXObject:
  16315. if (args[0].code) {
  16316. break;
  16317. }
  16318. if (!xobjs) {
  16319. xobjs = (resources.get('XObject') || Dict.empty);
  16320. }
  16321. var name = args[0].name;
  16322. if (xobjsCache.key === name) {
  16323. if (xobjsCache.texts) {
  16324. Util.appendToArray(bidiTexts, xobjsCache.texts.items);
  16325. Util.extendObj(textContent.styles, xobjsCache.texts.styles);
  16326. }
  16327. break;
  16328. }
  16329. var xobj = xobjs.get(name);
  16330. if (!xobj) {
  16331. break;
  16332. }
  16333. assert(isStream(xobj), 'XObject should be a stream');
  16334. var type = xobj.dict.get('Subtype');
  16335. assert(isName(type),
  16336. 'XObject should have a Name subtype');
  16337. if ('Form' !== type.name) {
  16338. xobjsCache.key = name;
  16339. xobjsCache.texts = null;
  16340. break;
  16341. }
  16342. stateManager.save();
  16343. var matrix = xobj.dict.get('Matrix');
  16344. if (isArray(matrix) && matrix.length === 6) {
  16345. stateManager.transform(matrix);
  16346. }
  16347. return self.getTextContent(xobj,
  16348. xobj.dict.get('Resources') || resources, stateManager).
  16349. then(function (formTextContent) {
  16350. Util.appendToArray(bidiTexts, formTextContent.items);
  16351. Util.extendObj(textContent.styles, formTextContent.styles);
  16352. stateManager.restore();
  16353. xobjsCache.key = name;
  16354. xobjsCache.texts = formTextContent;
  16355. next(resolve, reject);
  16356. }, reject);
  16357. case OPS.setGState:
  16358. var dictName = args[0];
  16359. var extGState = resources.get('ExtGState');
  16360. if (!isDict(extGState) || !extGState.has(dictName.name)) {
  16361. break;
  16362. }
  16363. var gsStateMap = extGState.get(dictName.name);
  16364. var gsStateFont = null;
  16365. for (var key in gsStateMap) {
  16366. if (key === 'Font') {
  16367. assert(!gsStateFont);
  16368. gsStateFont = gsStateMap[key];
  16369. }
  16370. }
  16371. if (gsStateFont) {
  16372. textState.fontSize = gsStateFont[1];
  16373. return handleSetFont(gsStateFont[0]).then(function() {
  16374. next(resolve, reject);
  16375. }, reject);
  16376. }
  16377. break;
  16378. } // switch
  16379. } // while
  16380. if (stop) {
  16381. deferred.then(function () {
  16382. next(resolve, reject);
  16383. });
  16384. return;
  16385. }
  16386. resolve(textContent);
  16387. });
  16388. },
  16389. extractDataStructures: function
  16390. partialEvaluatorExtractDataStructures(dict, baseDict,
  16391. xref, properties) {
  16392. // 9.10.2
  16393. var toUnicode = (dict.get('ToUnicode') || baseDict.get('ToUnicode'));
  16394. if (toUnicode) {
  16395. properties.toUnicode = this.readToUnicode(toUnicode);
  16396. }
  16397. if (properties.composite) {
  16398. // CIDSystemInfo helps to match CID to glyphs
  16399. var cidSystemInfo = dict.get('CIDSystemInfo');
  16400. if (isDict(cidSystemInfo)) {
  16401. properties.cidSystemInfo = {
  16402. registry: cidSystemInfo.get('Registry'),
  16403. ordering: cidSystemInfo.get('Ordering'),
  16404. supplement: cidSystemInfo.get('Supplement')
  16405. };
  16406. }
  16407. var cidToGidMap = dict.get('CIDToGIDMap');
  16408. if (isStream(cidToGidMap)) {
  16409. properties.cidToGidMap = this.readCidToGidMap(cidToGidMap);
  16410. }
  16411. }
  16412. // Based on 9.6.6 of the spec the encoding can come from multiple places
  16413. // and depends on the font type. The base encoding and differences are
  16414. // read here, but the encoding that is actually used is chosen during
  16415. // glyph mapping in the font.
  16416. // TODO: Loading the built in encoding in the font would allow the
  16417. // differences to be merged in here not require us to hold on to it.
  16418. var differences = [];
  16419. var baseEncodingName = null;
  16420. var encoding;
  16421. if (dict.has('Encoding')) {
  16422. encoding = dict.get('Encoding');
  16423. if (isDict(encoding)) {
  16424. baseEncodingName = encoding.get('BaseEncoding');
  16425. baseEncodingName = (isName(baseEncodingName) ?
  16426. baseEncodingName.name : null);
  16427. // Load the differences between the base and original
  16428. if (encoding.has('Differences')) {
  16429. var diffEncoding = encoding.get('Differences');
  16430. var index = 0;
  16431. for (var j = 0, jj = diffEncoding.length; j < jj; j++) {
  16432. var data = diffEncoding[j];
  16433. if (isNum(data)) {
  16434. index = data;
  16435. } else if (isName(data)) {
  16436. differences[index++] = data.name;
  16437. } else if (isRef(data)) {
  16438. diffEncoding[j--] = xref.fetch(data);
  16439. continue;
  16440. } else {
  16441. error('Invalid entry in \'Differences\' array: ' + data);
  16442. }
  16443. }
  16444. }
  16445. } else if (isName(encoding)) {
  16446. baseEncodingName = encoding.name;
  16447. } else {
  16448. error('Encoding is not a Name nor a Dict');
  16449. }
  16450. // According to table 114 if the encoding is a named encoding it must be
  16451. // one of these predefined encodings.
  16452. if ((baseEncodingName !== 'MacRomanEncoding' &&
  16453. baseEncodingName !== 'MacExpertEncoding' &&
  16454. baseEncodingName !== 'WinAnsiEncoding')) {
  16455. baseEncodingName = null;
  16456. }
  16457. }
  16458. if (baseEncodingName) {
  16459. properties.defaultEncoding = Encodings[baseEncodingName].slice();
  16460. } else {
  16461. encoding = (properties.type === 'TrueType' ?
  16462. Encodings.WinAnsiEncoding : Encodings.StandardEncoding);
  16463. // The Symbolic attribute can be misused for regular fonts
  16464. // Heuristic: we have to check if the font is a standard one also
  16465. if (!!(properties.flags & FontFlags.Symbolic)) {
  16466. encoding = Encodings.MacRomanEncoding;
  16467. if (!properties.file) {
  16468. if (/Symbol/i.test(properties.name)) {
  16469. encoding = Encodings.SymbolSetEncoding;
  16470. } else if (/Dingbats/i.test(properties.name)) {
  16471. encoding = Encodings.ZapfDingbatsEncoding;
  16472. }
  16473. }
  16474. }
  16475. properties.defaultEncoding = encoding;
  16476. }
  16477. properties.differences = differences;
  16478. properties.baseEncodingName = baseEncodingName;
  16479. properties.dict = dict;
  16480. },
  16481. readToUnicode: function PartialEvaluator_readToUnicode(toUnicode) {
  16482. var cmap, cmapObj = toUnicode;
  16483. if (isName(cmapObj)) {
  16484. cmap = CMapFactory.create(cmapObj,
  16485. { url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null);
  16486. if (cmap instanceof IdentityCMap) {
  16487. return new IdentityToUnicodeMap(0, 0xFFFF);
  16488. }
  16489. return new ToUnicodeMap(cmap.getMap());
  16490. } else if (isStream(cmapObj)) {
  16491. cmap = CMapFactory.create(cmapObj,
  16492. { url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null);
  16493. if (cmap instanceof IdentityCMap) {
  16494. return new IdentityToUnicodeMap(0, 0xFFFF);
  16495. }
  16496. cmap = cmap.getMap();
  16497. // Convert UTF-16BE
  16498. // NOTE: cmap can be a sparse array, so use forEach instead of for(;;)
  16499. // to iterate over all keys.
  16500. cmap.forEach(function(token, i) {
  16501. var str = [];
  16502. for (var k = 0; k < token.length; k += 2) {
  16503. var w1 = (token.charCodeAt(k) << 8) | token.charCodeAt(k + 1);
  16504. if ((w1 & 0xF800) !== 0xD800) { // w1 < 0xD800 || w1 > 0xDFFF
  16505. str.push(w1);
  16506. continue;
  16507. }
  16508. k += 2;
  16509. var w2 = (token.charCodeAt(k) << 8) | token.charCodeAt(k + 1);
  16510. str.push(((w1 & 0x3ff) << 10) + (w2 & 0x3ff) + 0x10000);
  16511. }
  16512. cmap[i] = String.fromCharCode.apply(String, str);
  16513. });
  16514. return new ToUnicodeMap(cmap);
  16515. }
  16516. return null;
  16517. },
  16518. readCidToGidMap: function PartialEvaluator_readCidToGidMap(cidToGidStream) {
  16519. // Extract the encoding from the CIDToGIDMap
  16520. var glyphsData = cidToGidStream.getBytes();
  16521. // Set encoding 0 to later verify the font has an encoding
  16522. var result = [];
  16523. for (var j = 0, jj = glyphsData.length; j < jj; j++) {
  16524. var glyphID = (glyphsData[j++] << 8) | glyphsData[j];
  16525. if (glyphID === 0) {
  16526. continue;
  16527. }
  16528. var code = j >> 1;
  16529. result[code] = glyphID;
  16530. }
  16531. return result;
  16532. },
  16533. extractWidths: function PartialEvaluator_extractWidths(dict, xref,
  16534. descriptor,
  16535. properties) {
  16536. var glyphsWidths = [];
  16537. var defaultWidth = 0;
  16538. var glyphsVMetrics = [];
  16539. var defaultVMetrics;
  16540. var i, ii, j, jj, start, code, widths;
  16541. if (properties.composite) {
  16542. defaultWidth = dict.get('DW') || 1000;
  16543. widths = dict.get('W');
  16544. if (widths) {
  16545. for (i = 0, ii = widths.length; i < ii; i++) {
  16546. start = widths[i++];
  16547. code = xref.fetchIfRef(widths[i]);
  16548. if (isArray(code)) {
  16549. for (j = 0, jj = code.length; j < jj; j++) {
  16550. glyphsWidths[start++] = code[j];
  16551. }
  16552. } else {
  16553. var width = widths[++i];
  16554. for (j = start; j <= code; j++) {
  16555. glyphsWidths[j] = width;
  16556. }
  16557. }
  16558. }
  16559. }
  16560. if (properties.vertical) {
  16561. var vmetrics = (dict.get('DW2') || [880, -1000]);
  16562. defaultVMetrics = [vmetrics[1], defaultWidth * 0.5, vmetrics[0]];
  16563. vmetrics = dict.get('W2');
  16564. if (vmetrics) {
  16565. for (i = 0, ii = vmetrics.length; i < ii; i++) {
  16566. start = vmetrics[i++];
  16567. code = xref.fetchIfRef(vmetrics[i]);
  16568. if (isArray(code)) {
  16569. for (j = 0, jj = code.length; j < jj; j++) {
  16570. glyphsVMetrics[start++] = [code[j++], code[j++], code[j]];
  16571. }
  16572. } else {
  16573. var vmetric = [vmetrics[++i], vmetrics[++i], vmetrics[++i]];
  16574. for (j = start; j <= code; j++) {
  16575. glyphsVMetrics[j] = vmetric;
  16576. }
  16577. }
  16578. }
  16579. }
  16580. }
  16581. } else {
  16582. var firstChar = properties.firstChar;
  16583. widths = dict.get('Widths');
  16584. if (widths) {
  16585. j = firstChar;
  16586. for (i = 0, ii = widths.length; i < ii; i++) {
  16587. glyphsWidths[j++] = widths[i];
  16588. }
  16589. defaultWidth = (parseFloat(descriptor.get('MissingWidth')) || 0);
  16590. } else {
  16591. // Trying get the BaseFont metrics (see comment above).
  16592. var baseFontName = dict.get('BaseFont');
  16593. if (isName(baseFontName)) {
  16594. var metrics = this.getBaseFontMetrics(baseFontName.name);
  16595. glyphsWidths = this.buildCharCodeToWidth(metrics.widths,
  16596. properties);
  16597. defaultWidth = metrics.defaultWidth;
  16598. }
  16599. }
  16600. }
  16601. // Heuristic: detection of monospace font by checking all non-zero widths
  16602. var isMonospace = true;
  16603. var firstWidth = defaultWidth;
  16604. for (var glyph in glyphsWidths) {
  16605. var glyphWidth = glyphsWidths[glyph];
  16606. if (!glyphWidth) {
  16607. continue;
  16608. }
  16609. if (!firstWidth) {
  16610. firstWidth = glyphWidth;
  16611. continue;
  16612. }
  16613. if (firstWidth !== glyphWidth) {
  16614. isMonospace = false;
  16615. break;
  16616. }
  16617. }
  16618. if (isMonospace) {
  16619. properties.flags |= FontFlags.FixedPitch;
  16620. }
  16621. properties.defaultWidth = defaultWidth;
  16622. properties.widths = glyphsWidths;
  16623. properties.defaultVMetrics = defaultVMetrics;
  16624. properties.vmetrics = glyphsVMetrics;
  16625. },
  16626. isSerifFont: function PartialEvaluator_isSerifFont(baseFontName) {
  16627. // Simulating descriptor flags attribute
  16628. var fontNameWoStyle = baseFontName.split('-')[0];
  16629. return (fontNameWoStyle in serifFonts) ||
  16630. (fontNameWoStyle.search(/serif/gi) !== -1);
  16631. },
  16632. getBaseFontMetrics: function PartialEvaluator_getBaseFontMetrics(name) {
  16633. var defaultWidth = 0;
  16634. var widths = [];
  16635. var monospace = false;
  16636. var lookupName = (stdFontMap[name] || name);
  16637. if (!(lookupName in Metrics)) {
  16638. // Use default fonts for looking up font metrics if the passed
  16639. // font is not a base font
  16640. if (this.isSerifFont(name)) {
  16641. lookupName = 'Times-Roman';
  16642. } else {
  16643. lookupName = 'Helvetica';
  16644. }
  16645. }
  16646. var glyphWidths = Metrics[lookupName];
  16647. if (isNum(glyphWidths)) {
  16648. defaultWidth = glyphWidths;
  16649. monospace = true;
  16650. } else {
  16651. widths = glyphWidths;
  16652. }
  16653. return {
  16654. defaultWidth: defaultWidth,
  16655. monospace: monospace,
  16656. widths: widths
  16657. };
  16658. },
  16659. buildCharCodeToWidth:
  16660. function PartialEvaluator_bulildCharCodeToWidth(widthsByGlyphName,
  16661. properties) {
  16662. var widths = Object.create(null);
  16663. var differences = properties.differences;
  16664. var encoding = properties.defaultEncoding;
  16665. for (var charCode = 0; charCode < 256; charCode++) {
  16666. if (charCode in differences &&
  16667. widthsByGlyphName[differences[charCode]]) {
  16668. widths[charCode] = widthsByGlyphName[differences[charCode]];
  16669. continue;
  16670. }
  16671. if (charCode in encoding && widthsByGlyphName[encoding[charCode]]) {
  16672. widths[charCode] = widthsByGlyphName[encoding[charCode]];
  16673. continue;
  16674. }
  16675. }
  16676. return widths;
  16677. },
  16678. preEvaluateFont: function PartialEvaluator_preEvaluateFont(dict, xref) {
  16679. var baseDict = dict;
  16680. var type = dict.get('Subtype');
  16681. assert(isName(type), 'invalid font Subtype');
  16682. var composite = false;
  16683. var uint8array;
  16684. if (type.name === 'Type0') {
  16685. // If font is a composite
  16686. // - get the descendant font
  16687. // - set the type according to the descendant font
  16688. // - get the FontDescriptor from the descendant font
  16689. var df = dict.get('DescendantFonts');
  16690. if (!df) {
  16691. error('Descendant fonts are not specified');
  16692. }
  16693. dict = (isArray(df) ? xref.fetchIfRef(df[0]) : df);
  16694. type = dict.get('Subtype');
  16695. assert(isName(type), 'invalid font Subtype');
  16696. composite = true;
  16697. }
  16698. var descriptor = dict.get('FontDescriptor');
  16699. if (descriptor) {
  16700. var hash = new MurmurHash3_64();
  16701. var encoding = baseDict.getRaw('Encoding');
  16702. if (isName(encoding)) {
  16703. hash.update(encoding.name);
  16704. } else if (isRef(encoding)) {
  16705. hash.update(encoding.num + '_' + encoding.gen);
  16706. } else if (isDict(encoding)) {
  16707. var keys = encoding.getKeys();
  16708. for (var i = 0, ii = keys.length; i < ii; i++) {
  16709. var entry = encoding.getRaw(keys[i]);
  16710. if (isName(entry)) {
  16711. hash.update(entry.name);
  16712. } else if (isRef(entry)) {
  16713. hash.update(entry.num + '_' + entry.gen);
  16714. } else if (isArray(entry)) { // 'Differences' entry.
  16715. // Ideally we should check the contents of the array, but to avoid
  16716. // parsing it here and then again in |extractDataStructures|,
  16717. // we only use the array length for now (fixes bug1157493.pdf).
  16718. hash.update(entry.length.toString());
  16719. }
  16720. }
  16721. }
  16722. var toUnicode = dict.get('ToUnicode') || baseDict.get('ToUnicode');
  16723. if (isStream(toUnicode)) {
  16724. var stream = toUnicode.str || toUnicode;
  16725. uint8array = stream.buffer ?
  16726. new Uint8Array(stream.buffer.buffer, 0, stream.bufferLength) :
  16727. new Uint8Array(stream.bytes.buffer,
  16728. stream.start, stream.end - stream.start);
  16729. hash.update(uint8array);
  16730. } else if (isName(toUnicode)) {
  16731. hash.update(toUnicode.name);
  16732. }
  16733. var widths = dict.get('Widths') || baseDict.get('Widths');
  16734. if (widths) {
  16735. uint8array = new Uint8Array(new Uint32Array(widths).buffer);
  16736. hash.update(uint8array);
  16737. }
  16738. }
  16739. return {
  16740. descriptor: descriptor,
  16741. dict: dict,
  16742. baseDict: baseDict,
  16743. composite: composite,
  16744. type: type.name,
  16745. hash: hash ? hash.hexdigest() : ''
  16746. };
  16747. },
  16748. translateFont: function PartialEvaluator_translateFont(preEvaluatedFont,
  16749. xref) {
  16750. var baseDict = preEvaluatedFont.baseDict;
  16751. var dict = preEvaluatedFont.dict;
  16752. var composite = preEvaluatedFont.composite;
  16753. var descriptor = preEvaluatedFont.descriptor;
  16754. var type = preEvaluatedFont.type;
  16755. var maxCharIndex = (composite ? 0xFFFF : 0xFF);
  16756. var properties;
  16757. if (!descriptor) {
  16758. if (type === 'Type3') {
  16759. // FontDescriptor is only required for Type3 fonts when the document
  16760. // is a tagged pdf. Create a barbebones one to get by.
  16761. descriptor = new Dict(null);
  16762. descriptor.set('FontName', Name.get(type));
  16763. descriptor.set('FontBBox', dict.get('FontBBox'));
  16764. } else {
  16765. // Before PDF 1.5 if the font was one of the base 14 fonts, having a
  16766. // FontDescriptor was not required.
  16767. // This case is here for compatibility.
  16768. var baseFontName = dict.get('BaseFont');
  16769. if (!isName(baseFontName)) {
  16770. error('Base font is not specified');
  16771. }
  16772. // Using base font name as a font name.
  16773. baseFontName = baseFontName.name.replace(/[,_]/g, '-');
  16774. var metrics = this.getBaseFontMetrics(baseFontName);
  16775. // Simulating descriptor flags attribute
  16776. var fontNameWoStyle = baseFontName.split('-')[0];
  16777. var flags =
  16778. (this.isSerifFont(fontNameWoStyle) ? FontFlags.Serif : 0) |
  16779. (metrics.monospace ? FontFlags.FixedPitch : 0) |
  16780. (symbolsFonts[fontNameWoStyle] ? FontFlags.Symbolic :
  16781. FontFlags.Nonsymbolic);
  16782. properties = {
  16783. type: type,
  16784. name: baseFontName,
  16785. widths: metrics.widths,
  16786. defaultWidth: metrics.defaultWidth,
  16787. flags: flags,
  16788. firstChar: 0,
  16789. lastChar: maxCharIndex
  16790. };
  16791. this.extractDataStructures(dict, dict, xref, properties);
  16792. properties.widths = this.buildCharCodeToWidth(metrics.widths,
  16793. properties);
  16794. return new Font(baseFontName, null, properties);
  16795. }
  16796. }
  16797. // According to the spec if 'FontDescriptor' is declared, 'FirstChar',
  16798. // 'LastChar' and 'Widths' should exist too, but some PDF encoders seem
  16799. // to ignore this rule when a variant of a standart font is used.
  16800. // TODO Fill the width array depending on which of the base font this is
  16801. // a variant.
  16802. var firstChar = (dict.get('FirstChar') || 0);
  16803. var lastChar = (dict.get('LastChar') || maxCharIndex);
  16804. var fontName = descriptor.get('FontName');
  16805. var baseFont = dict.get('BaseFont');
  16806. // Some bad PDFs have a string as the font name.
  16807. if (isString(fontName)) {
  16808. fontName = Name.get(fontName);
  16809. }
  16810. if (isString(baseFont)) {
  16811. baseFont = Name.get(baseFont);
  16812. }
  16813. if (type !== 'Type3') {
  16814. var fontNameStr = fontName && fontName.name;
  16815. var baseFontStr = baseFont && baseFont.name;
  16816. if (fontNameStr !== baseFontStr) {
  16817. info('The FontDescriptor\'s FontName is "' + fontNameStr +
  16818. '" but should be the same as the Font\'s BaseFont "' +
  16819. baseFontStr + '"');
  16820. // Workaround for cases where e.g. fontNameStr = 'Arial' and
  16821. // baseFontStr = 'Arial,Bold' (needed when no font file is embedded).
  16822. if (fontNameStr && baseFontStr &&
  16823. baseFontStr.indexOf(fontNameStr) === 0) {
  16824. fontName = baseFont;
  16825. }
  16826. }
  16827. }
  16828. fontName = (fontName || baseFont);
  16829. assert(isName(fontName), 'invalid font name');
  16830. var fontFile = descriptor.get('FontFile', 'FontFile2', 'FontFile3');
  16831. if (fontFile) {
  16832. if (fontFile.dict) {
  16833. var subtype = fontFile.dict.get('Subtype');
  16834. if (subtype) {
  16835. subtype = subtype.name;
  16836. }
  16837. var length1 = fontFile.dict.get('Length1');
  16838. var length2 = fontFile.dict.get('Length2');
  16839. }
  16840. }
  16841. properties = {
  16842. type: type,
  16843. name: fontName.name,
  16844. subtype: subtype,
  16845. file: fontFile,
  16846. length1: length1,
  16847. length2: length2,
  16848. loadedName: baseDict.loadedName,
  16849. composite: composite,
  16850. wideChars: composite,
  16851. fixedPitch: false,
  16852. fontMatrix: (dict.get('FontMatrix') || FONT_IDENTITY_MATRIX),
  16853. firstChar: firstChar || 0,
  16854. lastChar: (lastChar || maxCharIndex),
  16855. bbox: descriptor.get('FontBBox'),
  16856. ascent: descriptor.get('Ascent'),
  16857. descent: descriptor.get('Descent'),
  16858. xHeight: descriptor.get('XHeight'),
  16859. capHeight: descriptor.get('CapHeight'),
  16860. flags: descriptor.get('Flags'),
  16861. italicAngle: descriptor.get('ItalicAngle'),
  16862. coded: false
  16863. };
  16864. if (composite) {
  16865. var cidEncoding = baseDict.get('Encoding');
  16866. if (isName(cidEncoding)) {
  16867. properties.cidEncoding = cidEncoding.name;
  16868. }
  16869. properties.cMap = CMapFactory.create(cidEncoding,
  16870. { url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null);
  16871. properties.vertical = properties.cMap.vertical;
  16872. }
  16873. this.extractDataStructures(dict, baseDict, xref, properties);
  16874. this.extractWidths(dict, xref, descriptor, properties);
  16875. if (type === 'Type3') {
  16876. properties.isType3Font = true;
  16877. }
  16878. return new Font(fontName.name, fontFile, properties);
  16879. }
  16880. };
  16881. return PartialEvaluator;
  16882. })();
  16883. var TranslatedFont = (function TranslatedFontClosure() {
  16884. function TranslatedFont(loadedName, font, dict) {
  16885. this.loadedName = loadedName;
  16886. this.font = font;
  16887. this.dict = dict;
  16888. this.type3Loaded = null;
  16889. this.sent = false;
  16890. }
  16891. TranslatedFont.prototype = {
  16892. send: function (handler) {
  16893. if (this.sent) {
  16894. return;
  16895. }
  16896. var fontData = this.font.exportData();
  16897. handler.send('commonobj', [
  16898. this.loadedName,
  16899. 'Font',
  16900. fontData
  16901. ]);
  16902. this.sent = true;
  16903. },
  16904. loadType3Data: function (evaluator, resources, parentOperatorList) {
  16905. assert(this.font.isType3Font);
  16906. if (this.type3Loaded) {
  16907. return this.type3Loaded;
  16908. }
  16909. var translatedFont = this.font;
  16910. var loadCharProcsPromise = Promise.resolve();
  16911. var charProcs = this.dict.get('CharProcs').getAll();
  16912. var fontResources = this.dict.get('Resources') || resources;
  16913. var charProcKeys = Object.keys(charProcs);
  16914. var charProcOperatorList = {};
  16915. for (var i = 0, n = charProcKeys.length; i < n; ++i) {
  16916. loadCharProcsPromise = loadCharProcsPromise.then(function (key) {
  16917. var glyphStream = charProcs[key];
  16918. var operatorList = new OperatorList();
  16919. return evaluator.getOperatorList(glyphStream, fontResources,
  16920. operatorList).then(function () {
  16921. charProcOperatorList[key] = operatorList.getIR();
  16922. // Add the dependencies to the parent operator list so they are
  16923. // resolved before sub operator list is executed synchronously.
  16924. parentOperatorList.addDependencies(operatorList.dependencies);
  16925. }, function (reason) {
  16926. warn('Type3 font resource \"' + key + '\" is not available');
  16927. var operatorList = new OperatorList();
  16928. charProcOperatorList[key] = operatorList.getIR();
  16929. });
  16930. }.bind(this, charProcKeys[i]));
  16931. }
  16932. this.type3Loaded = loadCharProcsPromise.then(function () {
  16933. translatedFont.charProcOperatorList = charProcOperatorList;
  16934. });
  16935. return this.type3Loaded;
  16936. }
  16937. };
  16938. return TranslatedFont;
  16939. })();
  16940. var OperatorList = (function OperatorListClosure() {
  16941. var CHUNK_SIZE = 1000;
  16942. var CHUNK_SIZE_ABOUT = CHUNK_SIZE - 5; // close to chunk size
  16943. function getTransfers(queue) {
  16944. var transfers = [];
  16945. var fnArray = queue.fnArray, argsArray = queue.argsArray;
  16946. for (var i = 0, ii = queue.length; i < ii; i++) {
  16947. switch (fnArray[i]) {
  16948. case OPS.paintInlineImageXObject:
  16949. case OPS.paintInlineImageXObjectGroup:
  16950. case OPS.paintImageMaskXObject:
  16951. var arg = argsArray[i][0]; // first param in imgData
  16952. if (!arg.cached) {
  16953. transfers.push(arg.data.buffer);
  16954. }
  16955. break;
  16956. }
  16957. }
  16958. return transfers;
  16959. }
  16960. function OperatorList(intent, messageHandler, pageIndex) {
  16961. this.messageHandler = messageHandler;
  16962. this.fnArray = [];
  16963. this.argsArray = [];
  16964. this.dependencies = {};
  16965. this.pageIndex = pageIndex;
  16966. this.intent = intent;
  16967. }
  16968. OperatorList.prototype = {
  16969. get length() {
  16970. return this.argsArray.length;
  16971. },
  16972. addOp: function(fn, args) {
  16973. this.fnArray.push(fn);
  16974. this.argsArray.push(args);
  16975. if (this.messageHandler) {
  16976. if (this.fnArray.length >= CHUNK_SIZE) {
  16977. this.flush();
  16978. } else if (this.fnArray.length >= CHUNK_SIZE_ABOUT &&
  16979. (fn === OPS.restore || fn === OPS.endText)) {
  16980. // heuristic to flush on boundary of restore or endText
  16981. this.flush();
  16982. }
  16983. }
  16984. },
  16985. addDependency: function(dependency) {
  16986. if (dependency in this.dependencies) {
  16987. return;
  16988. }
  16989. this.dependencies[dependency] = true;
  16990. this.addOp(OPS.dependency, [dependency]);
  16991. },
  16992. addDependencies: function(dependencies) {
  16993. for (var key in dependencies) {
  16994. this.addDependency(key);
  16995. }
  16996. },
  16997. addOpList: function(opList) {
  16998. Util.extendObj(this.dependencies, opList.dependencies);
  16999. for (var i = 0, ii = opList.length; i < ii; i++) {
  17000. this.addOp(opList.fnArray[i], opList.argsArray[i]);
  17001. }
  17002. },
  17003. getIR: function() {
  17004. return {
  17005. fnArray: this.fnArray,
  17006. argsArray: this.argsArray,
  17007. length: this.length
  17008. };
  17009. },
  17010. flush: function(lastChunk) {
  17011. if (this.intent !== 'oplist') {
  17012. new QueueOptimizer().optimize(this);
  17013. }
  17014. var transfers = getTransfers(this);
  17015. this.messageHandler.send('RenderPageChunk', {
  17016. operatorList: {
  17017. fnArray: this.fnArray,
  17018. argsArray: this.argsArray,
  17019. lastChunk: lastChunk,
  17020. length: this.length
  17021. },
  17022. pageIndex: this.pageIndex,
  17023. intent: this.intent
  17024. }, transfers);
  17025. this.dependencies = {};
  17026. this.fnArray.length = 0;
  17027. this.argsArray.length = 0;
  17028. }
  17029. };
  17030. return OperatorList;
  17031. })();
  17032. var StateManager = (function StateManagerClosure() {
  17033. function StateManager(initialState) {
  17034. this.state = initialState;
  17035. this.stateStack = [];
  17036. }
  17037. StateManager.prototype = {
  17038. save: function () {
  17039. var old = this.state;
  17040. this.stateStack.push(this.state);
  17041. this.state = old.clone();
  17042. },
  17043. restore: function () {
  17044. var prev = this.stateStack.pop();
  17045. if (prev) {
  17046. this.state = prev;
  17047. }
  17048. },
  17049. transform: function (args) {
  17050. this.state.ctm = Util.transform(this.state.ctm, args);
  17051. }
  17052. };
  17053. return StateManager;
  17054. })();
  17055. var TextState = (function TextStateClosure() {
  17056. function TextState() {
  17057. this.ctm = new Float32Array(IDENTITY_MATRIX);
  17058. this.fontSize = 0;
  17059. this.font = null;
  17060. this.fontMatrix = FONT_IDENTITY_MATRIX;
  17061. this.textMatrix = IDENTITY_MATRIX.slice();
  17062. this.textLineMatrix = IDENTITY_MATRIX.slice();
  17063. this.charSpacing = 0;
  17064. this.wordSpacing = 0;
  17065. this.leading = 0;
  17066. this.textHScale = 1;
  17067. this.textRise = 0;
  17068. }
  17069. TextState.prototype = {
  17070. setTextMatrix: function TextState_setTextMatrix(a, b, c, d, e, f) {
  17071. var m = this.textMatrix;
  17072. m[0] = a; m[1] = b; m[2] = c; m[3] = d; m[4] = e; m[5] = f;
  17073. },
  17074. setTextLineMatrix: function TextState_setTextMatrix(a, b, c, d, e, f) {
  17075. var m = this.textLineMatrix;
  17076. m[0] = a; m[1] = b; m[2] = c; m[3] = d; m[4] = e; m[5] = f;
  17077. },
  17078. translateTextMatrix: function TextState_translateTextMatrix(x, y) {
  17079. var m = this.textMatrix;
  17080. m[4] = m[0] * x + m[2] * y + m[4];
  17081. m[5] = m[1] * x + m[3] * y + m[5];
  17082. },
  17083. translateTextLineMatrix: function TextState_translateTextMatrix(x, y) {
  17084. var m = this.textLineMatrix;
  17085. m[4] = m[0] * x + m[2] * y + m[4];
  17086. m[5] = m[1] * x + m[3] * y + m[5];
  17087. },
  17088. calcRenderMatrix: function TextState_calcRendeMatrix(ctm) {
  17089. // 9.4.4 Text Space Details
  17090. var tsm = [this.fontSize * this.textHScale, 0,
  17091. 0, this.fontSize,
  17092. 0, this.textRise];
  17093. return Util.transform(ctm, Util.transform(this.textMatrix, tsm));
  17094. },
  17095. carriageReturn: function TextState_carriageReturn() {
  17096. this.translateTextLineMatrix(0, -this.leading);
  17097. this.textMatrix = this.textLineMatrix.slice();
  17098. },
  17099. clone: function TextState_clone() {
  17100. var clone = Object.create(this);
  17101. clone.textMatrix = this.textMatrix.slice();
  17102. clone.textLineMatrix = this.textLineMatrix.slice();
  17103. clone.fontMatrix = this.fontMatrix.slice();
  17104. return clone;
  17105. }
  17106. };
  17107. return TextState;
  17108. })();
  17109. var EvalState = (function EvalStateClosure() {
  17110. function EvalState() {
  17111. this.ctm = new Float32Array(IDENTITY_MATRIX);
  17112. this.font = null;
  17113. this.textRenderingMode = TextRenderingMode.FILL;
  17114. this.fillColorSpace = ColorSpace.singletons.gray;
  17115. this.strokeColorSpace = ColorSpace.singletons.gray;
  17116. }
  17117. EvalState.prototype = {
  17118. clone: function CanvasExtraState_clone() {
  17119. return Object.create(this);
  17120. },
  17121. };
  17122. return EvalState;
  17123. })();
  17124. var EvaluatorPreprocessor = (function EvaluatorPreprocessorClosure() {
  17125. // Specifies properties for each command
  17126. //
  17127. // If variableArgs === true: [0, `numArgs`] expected
  17128. // If variableArgs === false: exactly `numArgs` expected
  17129. var OP_MAP = {
  17130. // Graphic state
  17131. w: { id: OPS.setLineWidth, numArgs: 1, variableArgs: false },
  17132. J: { id: OPS.setLineCap, numArgs: 1, variableArgs: false },
  17133. j: { id: OPS.setLineJoin, numArgs: 1, variableArgs: false },
  17134. M: { id: OPS.setMiterLimit, numArgs: 1, variableArgs: false },
  17135. d: { id: OPS.setDash, numArgs: 2, variableArgs: false },
  17136. ri: { id: OPS.setRenderingIntent, numArgs: 1, variableArgs: false },
  17137. i: { id: OPS.setFlatness, numArgs: 1, variableArgs: false },
  17138. gs: { id: OPS.setGState, numArgs: 1, variableArgs: false },
  17139. q: { id: OPS.save, numArgs: 0, variableArgs: false },
  17140. Q: { id: OPS.restore, numArgs: 0, variableArgs: false },
  17141. cm: { id: OPS.transform, numArgs: 6, variableArgs: false },
  17142. // Path
  17143. m: { id: OPS.moveTo, numArgs: 2, variableArgs: false },
  17144. l: { id: OPS.lineTo, numArgs: 2, variableArgs: false },
  17145. c: { id: OPS.curveTo, numArgs: 6, variableArgs: false },
  17146. v: { id: OPS.curveTo2, numArgs: 4, variableArgs: false },
  17147. y: { id: OPS.curveTo3, numArgs: 4, variableArgs: false },
  17148. h: { id: OPS.closePath, numArgs: 0, variableArgs: false },
  17149. re: { id: OPS.rectangle, numArgs: 4, variableArgs: false },
  17150. S: { id: OPS.stroke, numArgs: 0, variableArgs: false },
  17151. s: { id: OPS.closeStroke, numArgs: 0, variableArgs: false },
  17152. f: { id: OPS.fill, numArgs: 0, variableArgs: false },
  17153. F: { id: OPS.fill, numArgs: 0, variableArgs: false },
  17154. 'f*': { id: OPS.eoFill, numArgs: 0, variableArgs: false },
  17155. B: { id: OPS.fillStroke, numArgs: 0, variableArgs: false },
  17156. 'B*': { id: OPS.eoFillStroke, numArgs: 0, variableArgs: false },
  17157. b: { id: OPS.closeFillStroke, numArgs: 0, variableArgs: false },
  17158. 'b*': { id: OPS.closeEOFillStroke, numArgs: 0, variableArgs: false },
  17159. n: { id: OPS.endPath, numArgs: 0, variableArgs: false },
  17160. // Clipping
  17161. W: { id: OPS.clip, numArgs: 0, variableArgs: false },
  17162. 'W*': { id: OPS.eoClip, numArgs: 0, variableArgs: false },
  17163. // Text
  17164. BT: { id: OPS.beginText, numArgs: 0, variableArgs: false },
  17165. ET: { id: OPS.endText, numArgs: 0, variableArgs: false },
  17166. Tc: { id: OPS.setCharSpacing, numArgs: 1, variableArgs: false },
  17167. Tw: { id: OPS.setWordSpacing, numArgs: 1, variableArgs: false },
  17168. Tz: { id: OPS.setHScale, numArgs: 1, variableArgs: false },
  17169. TL: { id: OPS.setLeading, numArgs: 1, variableArgs: false },
  17170. Tf: { id: OPS.setFont, numArgs: 2, variableArgs: false },
  17171. Tr: { id: OPS.setTextRenderingMode, numArgs: 1, variableArgs: false },
  17172. Ts: { id: OPS.setTextRise, numArgs: 1, variableArgs: false },
  17173. Td: { id: OPS.moveText, numArgs: 2, variableArgs: false },
  17174. TD: { id: OPS.setLeadingMoveText, numArgs: 2, variableArgs: false },
  17175. Tm: { id: OPS.setTextMatrix, numArgs: 6, variableArgs: false },
  17176. 'T*': { id: OPS.nextLine, numArgs: 0, variableArgs: false },
  17177. Tj: { id: OPS.showText, numArgs: 1, variableArgs: false },
  17178. TJ: { id: OPS.showSpacedText, numArgs: 1, variableArgs: false },
  17179. '\'': { id: OPS.nextLineShowText, numArgs: 1, variableArgs: false },
  17180. '"': { id: OPS.nextLineSetSpacingShowText, numArgs: 3,
  17181. variableArgs: false },
  17182. // Type3 fonts
  17183. d0: { id: OPS.setCharWidth, numArgs: 2, variableArgs: false },
  17184. d1: { id: OPS.setCharWidthAndBounds, numArgs: 6, variableArgs: false },
  17185. // Color
  17186. CS: { id: OPS.setStrokeColorSpace, numArgs: 1, variableArgs: false },
  17187. cs: { id: OPS.setFillColorSpace, numArgs: 1, variableArgs: false },
  17188. SC: { id: OPS.setStrokeColor, numArgs: 4, variableArgs: true },
  17189. SCN: { id: OPS.setStrokeColorN, numArgs: 33, variableArgs: true },
  17190. sc: { id: OPS.setFillColor, numArgs: 4, variableArgs: true },
  17191. scn: { id: OPS.setFillColorN, numArgs: 33, variableArgs: true },
  17192. G: { id: OPS.setStrokeGray, numArgs: 1, variableArgs: false },
  17193. g: { id: OPS.setFillGray, numArgs: 1, variableArgs: false },
  17194. RG: { id: OPS.setStrokeRGBColor, numArgs: 3, variableArgs: false },
  17195. rg: { id: OPS.setFillRGBColor, numArgs: 3, variableArgs: false },
  17196. K: { id: OPS.setStrokeCMYKColor, numArgs: 4, variableArgs: false },
  17197. k: { id: OPS.setFillCMYKColor, numArgs: 4, variableArgs: false },
  17198. // Shading
  17199. sh: { id: OPS.shadingFill, numArgs: 1, variableArgs: false },
  17200. // Images
  17201. BI: { id: OPS.beginInlineImage, numArgs: 0, variableArgs: false },
  17202. ID: { id: OPS.beginImageData, numArgs: 0, variableArgs: false },
  17203. EI: { id: OPS.endInlineImage, numArgs: 1, variableArgs: false },
  17204. // XObjects
  17205. Do: { id: OPS.paintXObject, numArgs: 1, variableArgs: false },
  17206. MP: { id: OPS.markPoint, numArgs: 1, variableArgs: false },
  17207. DP: { id: OPS.markPointProps, numArgs: 2, variableArgs: false },
  17208. BMC: { id: OPS.beginMarkedContent, numArgs: 1, variableArgs: false },
  17209. BDC: { id: OPS.beginMarkedContentProps, numArgs: 2,
  17210. variableArgs: false },
  17211. EMC: { id: OPS.endMarkedContent, numArgs: 0, variableArgs: false },
  17212. // Compatibility
  17213. BX: { id: OPS.beginCompat, numArgs: 0, variableArgs: false },
  17214. EX: { id: OPS.endCompat, numArgs: 0, variableArgs: false },
  17215. // (reserved partial commands for the lexer)
  17216. BM: null,
  17217. BD: null,
  17218. 'true': null,
  17219. fa: null,
  17220. fal: null,
  17221. fals: null,
  17222. 'false': null,
  17223. nu: null,
  17224. nul: null,
  17225. 'null': null
  17226. };
  17227. function EvaluatorPreprocessor(stream, xref, stateManager) {
  17228. // TODO(mduan): pass array of knownCommands rather than OP_MAP
  17229. // dictionary
  17230. this.parser = new Parser(new Lexer(stream, OP_MAP), false, xref);
  17231. this.stateManager = stateManager;
  17232. this.nonProcessedArgs = [];
  17233. }
  17234. EvaluatorPreprocessor.prototype = {
  17235. get savedStatesDepth() {
  17236. return this.stateManager.stateStack.length;
  17237. },
  17238. // |operation| is an object with two fields:
  17239. //
  17240. // - |fn| is an out param.
  17241. //
  17242. // - |args| is an inout param. On entry, it should have one of two values.
  17243. //
  17244. // - An empty array. This indicates that the caller is providing the
  17245. // array in which the args will be stored in. The caller should use
  17246. // this value if it can reuse a single array for each call to read().
  17247. //
  17248. // - |null|. This indicates that the caller needs this function to create
  17249. // the array in which any args are stored in. If there are zero args,
  17250. // this function will leave |operation.args| as |null| (thus avoiding
  17251. // allocations that would occur if we used an empty array to represent
  17252. // zero arguments). Otherwise, it will replace |null| with a new array
  17253. // containing the arguments. The caller should use this value if it
  17254. // cannot reuse an array for each call to read().
  17255. //
  17256. // These two modes are present because this function is very hot and so
  17257. // avoiding allocations where possible is worthwhile.
  17258. //
  17259. read: function EvaluatorPreprocessor_read(operation) {
  17260. var args = operation.args;
  17261. while (true) {
  17262. var obj = this.parser.getObj();
  17263. if (isCmd(obj)) {
  17264. var cmd = obj.cmd;
  17265. // Check that the command is valid
  17266. var opSpec = OP_MAP[cmd];
  17267. if (!opSpec) {
  17268. warn('Unknown command "' + cmd + '"');
  17269. continue;
  17270. }
  17271. var fn = opSpec.id;
  17272. var numArgs = opSpec.numArgs;
  17273. var argsLength = args !== null ? args.length : 0;
  17274. if (!opSpec.variableArgs) {
  17275. // Postscript commands can be nested, e.g. /F2 /GS2 gs 5.711 Tf
  17276. if (argsLength !== numArgs) {
  17277. var nonProcessedArgs = this.nonProcessedArgs;
  17278. while (argsLength > numArgs) {
  17279. nonProcessedArgs.push(args.shift());
  17280. argsLength--;
  17281. }
  17282. while (argsLength < numArgs && nonProcessedArgs.length !== 0) {
  17283. if (!args) {
  17284. args = [];
  17285. }
  17286. args.unshift(nonProcessedArgs.pop());
  17287. argsLength++;
  17288. }
  17289. }
  17290. if (argsLength < numArgs) {
  17291. // If we receive too few args, it's not possible to possible
  17292. // to execute the command, so skip the command
  17293. info('Command ' + fn + ': because expected ' +
  17294. numArgs + ' args, but received ' + argsLength +
  17295. ' args; skipping');
  17296. args = null;
  17297. continue;
  17298. }
  17299. } else if (argsLength > numArgs) {
  17300. info('Command ' + fn + ': expected [0,' + numArgs +
  17301. '] args, but received ' + argsLength + ' args');
  17302. }
  17303. // TODO figure out how to type-check vararg functions
  17304. this.preprocessCommand(fn, args);
  17305. operation.fn = fn;
  17306. operation.args = args;
  17307. return true;
  17308. } else {
  17309. if (isEOF(obj)) {
  17310. return false; // no more commands
  17311. }
  17312. // argument
  17313. if (obj !== null) {
  17314. if (!args) {
  17315. args = [];
  17316. }
  17317. args.push((obj instanceof Dict ? obj.getAll() : obj));
  17318. assert(args.length <= 33, 'Too many arguments');
  17319. }
  17320. }
  17321. }
  17322. },
  17323. preprocessCommand:
  17324. function EvaluatorPreprocessor_preprocessCommand(fn, args) {
  17325. switch (fn | 0) {
  17326. case OPS.save:
  17327. this.stateManager.save();
  17328. break;
  17329. case OPS.restore:
  17330. this.stateManager.restore();
  17331. break;
  17332. case OPS.transform:
  17333. this.stateManager.transform(args);
  17334. break;
  17335. }
  17336. }
  17337. };
  17338. return EvaluatorPreprocessor;
  17339. })();
  17340. var QueueOptimizer = (function QueueOptimizerClosure() {
  17341. function addState(parentState, pattern, fn) {
  17342. var state = parentState;
  17343. for (var i = 0, ii = pattern.length - 1; i < ii; i++) {
  17344. var item = pattern[i];
  17345. state = (state[item] || (state[item] = []));
  17346. }
  17347. state[pattern[pattern.length - 1]] = fn;
  17348. }
  17349. function handlePaintSolidColorImageMask(iFirstSave, count, fnArray,
  17350. argsArray) {
  17351. // Handles special case of mainly LaTeX documents which use image masks to
  17352. // draw lines with the current fill style.
  17353. // 'count' groups of (save, transform, paintImageMaskXObject, restore)+
  17354. // have been found at iFirstSave.
  17355. var iFirstPIMXO = iFirstSave + 2;
  17356. for (var i = 0; i < count; i++) {
  17357. var arg = argsArray[iFirstPIMXO + 4 * i];
  17358. var imageMask = arg.length === 1 && arg[0];
  17359. if (imageMask && imageMask.width === 1 && imageMask.height === 1 &&
  17360. (!imageMask.data.length ||
  17361. (imageMask.data.length === 1 && imageMask.data[0] === 0))) {
  17362. fnArray[iFirstPIMXO + 4 * i] = OPS.paintSolidColorImageMask;
  17363. continue;
  17364. }
  17365. break;
  17366. }
  17367. return count - i;
  17368. }
  17369. var InitialState = [];
  17370. // This replaces (save, transform, paintInlineImageXObject, restore)+
  17371. // sequences with one |paintInlineImageXObjectGroup| operation.
  17372. addState(InitialState,
  17373. [OPS.save, OPS.transform, OPS.paintInlineImageXObject, OPS.restore],
  17374. function foundInlineImageGroup(context) {
  17375. var MIN_IMAGES_IN_INLINE_IMAGES_BLOCK = 10;
  17376. var MAX_IMAGES_IN_INLINE_IMAGES_BLOCK = 200;
  17377. var MAX_WIDTH = 1000;
  17378. var IMAGE_PADDING = 1;
  17379. var fnArray = context.fnArray, argsArray = context.argsArray;
  17380. var curr = context.iCurr;
  17381. var iFirstSave = curr - 3;
  17382. var iFirstTransform = curr - 2;
  17383. var iFirstPIIXO = curr - 1;
  17384. // Look for the quartets.
  17385. var i = iFirstSave + 4;
  17386. var ii = fnArray.length;
  17387. while (i + 3 < ii) {
  17388. if (fnArray[i] !== OPS.save ||
  17389. fnArray[i + 1] !== OPS.transform ||
  17390. fnArray[i + 2] !== OPS.paintInlineImageXObject ||
  17391. fnArray[i + 3] !== OPS.restore) {
  17392. break; // ops don't match
  17393. }
  17394. i += 4;
  17395. }
  17396. // At this point, i is the index of the first op past the last valid
  17397. // quartet.
  17398. var count = Math.min((i - iFirstSave) / 4,
  17399. MAX_IMAGES_IN_INLINE_IMAGES_BLOCK);
  17400. if (count < MIN_IMAGES_IN_INLINE_IMAGES_BLOCK) {
  17401. return i;
  17402. }
  17403. // assuming that heights of those image is too small (~1 pixel)
  17404. // packing as much as possible by lines
  17405. var maxX = 0;
  17406. var map = [], maxLineHeight = 0;
  17407. var currentX = IMAGE_PADDING, currentY = IMAGE_PADDING;
  17408. var q;
  17409. for (q = 0; q < count; q++) {
  17410. var transform = argsArray[iFirstTransform + (q << 2)];
  17411. var img = argsArray[iFirstPIIXO + (q << 2)][0];
  17412. if (currentX + img.width > MAX_WIDTH) {
  17413. // starting new line
  17414. maxX = Math.max(maxX, currentX);
  17415. currentY += maxLineHeight + 2 * IMAGE_PADDING;
  17416. currentX = 0;
  17417. maxLineHeight = 0;
  17418. }
  17419. map.push({
  17420. transform: transform,
  17421. x: currentX, y: currentY,
  17422. w: img.width, h: img.height
  17423. });
  17424. currentX += img.width + 2 * IMAGE_PADDING;
  17425. maxLineHeight = Math.max(maxLineHeight, img.height);
  17426. }
  17427. var imgWidth = Math.max(maxX, currentX) + IMAGE_PADDING;
  17428. var imgHeight = currentY + maxLineHeight + IMAGE_PADDING;
  17429. var imgData = new Uint8Array(imgWidth * imgHeight * 4);
  17430. var imgRowSize = imgWidth << 2;
  17431. for (q = 0; q < count; q++) {
  17432. var data = argsArray[iFirstPIIXO + (q << 2)][0].data;
  17433. // Copy image by lines and extends pixels into padding.
  17434. var rowSize = map[q].w << 2;
  17435. var dataOffset = 0;
  17436. var offset = (map[q].x + map[q].y * imgWidth) << 2;
  17437. imgData.set(data.subarray(0, rowSize), offset - imgRowSize);
  17438. for (var k = 0, kk = map[q].h; k < kk; k++) {
  17439. imgData.set(data.subarray(dataOffset, dataOffset + rowSize), offset);
  17440. dataOffset += rowSize;
  17441. offset += imgRowSize;
  17442. }
  17443. imgData.set(data.subarray(dataOffset - rowSize, dataOffset), offset);
  17444. while (offset >= 0) {
  17445. data[offset - 4] = data[offset];
  17446. data[offset - 3] = data[offset + 1];
  17447. data[offset - 2] = data[offset + 2];
  17448. data[offset - 1] = data[offset + 3];
  17449. data[offset + rowSize] = data[offset + rowSize - 4];
  17450. data[offset + rowSize + 1] = data[offset + rowSize - 3];
  17451. data[offset + rowSize + 2] = data[offset + rowSize - 2];
  17452. data[offset + rowSize + 3] = data[offset + rowSize - 1];
  17453. offset -= imgRowSize;
  17454. }
  17455. }
  17456. // Replace queue items.
  17457. fnArray.splice(iFirstSave, count * 4, OPS.paintInlineImageXObjectGroup);
  17458. argsArray.splice(iFirstSave, count * 4,
  17459. [{ width: imgWidth, height: imgHeight, kind: ImageKind.RGBA_32BPP,
  17460. data: imgData }, map]);
  17461. return iFirstSave + 1;
  17462. });
  17463. // This replaces (save, transform, paintImageMaskXObject, restore)+
  17464. // sequences with one |paintImageMaskXObjectGroup| or one
  17465. // |paintImageMaskXObjectRepeat| operation.
  17466. addState(InitialState,
  17467. [OPS.save, OPS.transform, OPS.paintImageMaskXObject, OPS.restore],
  17468. function foundImageMaskGroup(context) {
  17469. var MIN_IMAGES_IN_MASKS_BLOCK = 10;
  17470. var MAX_IMAGES_IN_MASKS_BLOCK = 100;
  17471. var MAX_SAME_IMAGES_IN_MASKS_BLOCK = 1000;
  17472. var fnArray = context.fnArray, argsArray = context.argsArray;
  17473. var curr = context.iCurr;
  17474. var iFirstSave = curr - 3;
  17475. var iFirstTransform = curr - 2;
  17476. var iFirstPIMXO = curr - 1;
  17477. // Look for the quartets.
  17478. var i = iFirstSave + 4;
  17479. var ii = fnArray.length;
  17480. while (i + 3 < ii) {
  17481. if (fnArray[i] !== OPS.save ||
  17482. fnArray[i + 1] !== OPS.transform ||
  17483. fnArray[i + 2] !== OPS.paintImageMaskXObject ||
  17484. fnArray[i + 3] !== OPS.restore) {
  17485. break; // ops don't match
  17486. }
  17487. i += 4;
  17488. }
  17489. // At this point, i is the index of the first op past the last valid
  17490. // quartet.
  17491. var count = (i - iFirstSave) / 4;
  17492. count = handlePaintSolidColorImageMask(iFirstSave, count, fnArray,
  17493. argsArray);
  17494. if (count < MIN_IMAGES_IN_MASKS_BLOCK) {
  17495. return i;
  17496. }
  17497. var q;
  17498. var isSameImage = false;
  17499. var iTransform, transformArgs;
  17500. var firstPIMXOArg0 = argsArray[iFirstPIMXO][0];
  17501. if (argsArray[iFirstTransform][1] === 0 &&
  17502. argsArray[iFirstTransform][2] === 0) {
  17503. isSameImage = true;
  17504. var firstTransformArg0 = argsArray[iFirstTransform][0];
  17505. var firstTransformArg3 = argsArray[iFirstTransform][3];
  17506. iTransform = iFirstTransform + 4;
  17507. var iPIMXO = iFirstPIMXO + 4;
  17508. for (q = 1; q < count; q++, iTransform += 4, iPIMXO += 4) {
  17509. transformArgs = argsArray[iTransform];
  17510. if (argsArray[iPIMXO][0] !== firstPIMXOArg0 ||
  17511. transformArgs[0] !== firstTransformArg0 ||
  17512. transformArgs[1] !== 0 ||
  17513. transformArgs[2] !== 0 ||
  17514. transformArgs[3] !== firstTransformArg3) {
  17515. if (q < MIN_IMAGES_IN_MASKS_BLOCK) {
  17516. isSameImage = false;
  17517. } else {
  17518. count = q;
  17519. }
  17520. break; // different image or transform
  17521. }
  17522. }
  17523. }
  17524. if (isSameImage) {
  17525. count = Math.min(count, MAX_SAME_IMAGES_IN_MASKS_BLOCK);
  17526. var positions = new Float32Array(count * 2);
  17527. iTransform = iFirstTransform;
  17528. for (q = 0; q < count; q++, iTransform += 4) {
  17529. transformArgs = argsArray[iTransform];
  17530. positions[(q << 1)] = transformArgs[4];
  17531. positions[(q << 1) + 1] = transformArgs[5];
  17532. }
  17533. // Replace queue items.
  17534. fnArray.splice(iFirstSave, count * 4, OPS.paintImageMaskXObjectRepeat);
  17535. argsArray.splice(iFirstSave, count * 4,
  17536. [firstPIMXOArg0, firstTransformArg0, firstTransformArg3, positions]);
  17537. } else {
  17538. count = Math.min(count, MAX_IMAGES_IN_MASKS_BLOCK);
  17539. var images = [];
  17540. for (q = 0; q < count; q++) {
  17541. transformArgs = argsArray[iFirstTransform + (q << 2)];
  17542. var maskParams = argsArray[iFirstPIMXO + (q << 2)][0];
  17543. images.push({ data: maskParams.data, width: maskParams.width,
  17544. height: maskParams.height,
  17545. transform: transformArgs });
  17546. }
  17547. // Replace queue items.
  17548. fnArray.splice(iFirstSave, count * 4, OPS.paintImageMaskXObjectGroup);
  17549. argsArray.splice(iFirstSave, count * 4, [images]);
  17550. }
  17551. return iFirstSave + 1;
  17552. });
  17553. // This replaces (save, transform, paintImageXObject, restore)+ sequences
  17554. // with one paintImageXObjectRepeat operation, if the |transform| and
  17555. // |paintImageXObjectRepeat| ops are appropriate.
  17556. addState(InitialState,
  17557. [OPS.save, OPS.transform, OPS.paintImageXObject, OPS.restore],
  17558. function (context) {
  17559. var MIN_IMAGES_IN_BLOCK = 3;
  17560. var MAX_IMAGES_IN_BLOCK = 1000;
  17561. var fnArray = context.fnArray, argsArray = context.argsArray;
  17562. var curr = context.iCurr;
  17563. var iFirstSave = curr - 3;
  17564. var iFirstTransform = curr - 2;
  17565. var iFirstPIXO = curr - 1;
  17566. var iFirstRestore = curr;
  17567. if (argsArray[iFirstTransform][1] !== 0 ||
  17568. argsArray[iFirstTransform][2] !== 0) {
  17569. return iFirstRestore + 1; // transform has the wrong form
  17570. }
  17571. // Look for the quartets.
  17572. var firstPIXOArg0 = argsArray[iFirstPIXO][0];
  17573. var firstTransformArg0 = argsArray[iFirstTransform][0];
  17574. var firstTransformArg3 = argsArray[iFirstTransform][3];
  17575. var i = iFirstSave + 4;
  17576. var ii = fnArray.length;
  17577. while (i + 3 < ii) {
  17578. if (fnArray[i] !== OPS.save ||
  17579. fnArray[i + 1] !== OPS.transform ||
  17580. fnArray[i + 2] !== OPS.paintImageXObject ||
  17581. fnArray[i + 3] !== OPS.restore) {
  17582. break; // ops don't match
  17583. }
  17584. if (argsArray[i + 1][0] !== firstTransformArg0 ||
  17585. argsArray[i + 1][1] !== 0 ||
  17586. argsArray[i + 1][2] !== 0 ||
  17587. argsArray[i + 1][3] !== firstTransformArg3) {
  17588. break; // transforms don't match
  17589. }
  17590. if (argsArray[i + 2][0] !== firstPIXOArg0) {
  17591. break; // images don't match
  17592. }
  17593. i += 4;
  17594. }
  17595. // At this point, i is the index of the first op past the last valid
  17596. // quartet.
  17597. var count = Math.min((i - iFirstSave) / 4, MAX_IMAGES_IN_BLOCK);
  17598. if (count < MIN_IMAGES_IN_BLOCK) {
  17599. return i;
  17600. }
  17601. // Extract the (x,y) positions from all of the matching transforms.
  17602. var positions = new Float32Array(count * 2);
  17603. var iTransform = iFirstTransform;
  17604. for (var q = 0; q < count; q++, iTransform += 4) {
  17605. var transformArgs = argsArray[iTransform];
  17606. positions[(q << 1)] = transformArgs[4];
  17607. positions[(q << 1) + 1] = transformArgs[5];
  17608. }
  17609. // Replace queue items.
  17610. var args = [firstPIXOArg0, firstTransformArg0, firstTransformArg3,
  17611. positions];
  17612. fnArray.splice(iFirstSave, count * 4, OPS.paintImageXObjectRepeat);
  17613. argsArray.splice(iFirstSave, count * 4, args);
  17614. return iFirstSave + 1;
  17615. });
  17616. // This replaces (beginText, setFont, setTextMatrix, showText, endText)+
  17617. // sequences with (beginText, setFont, (setTextMatrix, showText)+, endText)+
  17618. // sequences, if the font for each one is the same.
  17619. addState(InitialState,
  17620. [OPS.beginText, OPS.setFont, OPS.setTextMatrix, OPS.showText, OPS.endText],
  17621. function (context) {
  17622. var MIN_CHARS_IN_BLOCK = 3;
  17623. var MAX_CHARS_IN_BLOCK = 1000;
  17624. var fnArray = context.fnArray, argsArray = context.argsArray;
  17625. var curr = context.iCurr;
  17626. var iFirstBeginText = curr - 4;
  17627. var iFirstSetFont = curr - 3;
  17628. var iFirstSetTextMatrix = curr - 2;
  17629. var iFirstShowText = curr - 1;
  17630. var iFirstEndText = curr;
  17631. // Look for the quintets.
  17632. var firstSetFontArg0 = argsArray[iFirstSetFont][0];
  17633. var firstSetFontArg1 = argsArray[iFirstSetFont][1];
  17634. var i = iFirstBeginText + 5;
  17635. var ii = fnArray.length;
  17636. while (i + 4 < ii) {
  17637. if (fnArray[i] !== OPS.beginText ||
  17638. fnArray[i + 1] !== OPS.setFont ||
  17639. fnArray[i + 2] !== OPS.setTextMatrix ||
  17640. fnArray[i + 3] !== OPS.showText ||
  17641. fnArray[i + 4] !== OPS.endText) {
  17642. break; // ops don't match
  17643. }
  17644. if (argsArray[i + 1][0] !== firstSetFontArg0 ||
  17645. argsArray[i + 1][1] !== firstSetFontArg1) {
  17646. break; // fonts don't match
  17647. }
  17648. i += 5;
  17649. }
  17650. // At this point, i is the index of the first op past the last valid
  17651. // quintet.
  17652. var count = Math.min(((i - iFirstBeginText) / 5), MAX_CHARS_IN_BLOCK);
  17653. if (count < MIN_CHARS_IN_BLOCK) {
  17654. return i;
  17655. }
  17656. // If the preceding quintet is (<something>, setFont, setTextMatrix,
  17657. // showText, endText), include that as well. (E.g. <something> might be
  17658. // |dependency|.)
  17659. var iFirst = iFirstBeginText;
  17660. if (iFirstBeginText >= 4 &&
  17661. fnArray[iFirstBeginText - 4] === fnArray[iFirstSetFont] &&
  17662. fnArray[iFirstBeginText - 3] === fnArray[iFirstSetTextMatrix] &&
  17663. fnArray[iFirstBeginText - 2] === fnArray[iFirstShowText] &&
  17664. fnArray[iFirstBeginText - 1] === fnArray[iFirstEndText] &&
  17665. argsArray[iFirstBeginText - 4][0] === firstSetFontArg0 &&
  17666. argsArray[iFirstBeginText - 4][1] === firstSetFontArg1) {
  17667. count++;
  17668. iFirst -= 5;
  17669. }
  17670. // Remove (endText, beginText, setFont) trios.
  17671. var iEndText = iFirst + 4;
  17672. for (var q = 1; q < count; q++) {
  17673. fnArray.splice(iEndText, 3);
  17674. argsArray.splice(iEndText, 3);
  17675. iEndText += 2;
  17676. }
  17677. return iEndText + 1;
  17678. });
  17679. function QueueOptimizer() {}
  17680. QueueOptimizer.prototype = {
  17681. optimize: function QueueOptimizer_optimize(queue) {
  17682. var fnArray = queue.fnArray, argsArray = queue.argsArray;
  17683. var context = {
  17684. iCurr: 0,
  17685. fnArray: fnArray,
  17686. argsArray: argsArray
  17687. };
  17688. var state;
  17689. var i = 0, ii = fnArray.length;
  17690. while (i < ii) {
  17691. state = (state || InitialState)[fnArray[i]];
  17692. if (typeof state === 'function') { // we found some handler
  17693. context.iCurr = i;
  17694. // state() returns the index of the first non-matching op (if we
  17695. // didn't match) or the first op past the modified ops (if we did
  17696. // match and replace).
  17697. i = state(context);
  17698. state = undefined; // reset the state machine
  17699. ii = context.fnArray.length;
  17700. } else {
  17701. i++;
  17702. }
  17703. }
  17704. }
  17705. };
  17706. return QueueOptimizer;
  17707. })();
  17708. var BUILT_IN_CMAPS = [
  17709. // << Start unicode maps.
  17710. 'Adobe-GB1-UCS2',
  17711. 'Adobe-CNS1-UCS2',
  17712. 'Adobe-Japan1-UCS2',
  17713. 'Adobe-Korea1-UCS2',
  17714. // >> End unicode maps.
  17715. '78-EUC-H',
  17716. '78-EUC-V',
  17717. '78-H',
  17718. '78-RKSJ-H',
  17719. '78-RKSJ-V',
  17720. '78-V',
  17721. '78ms-RKSJ-H',
  17722. '78ms-RKSJ-V',
  17723. '83pv-RKSJ-H',
  17724. '90ms-RKSJ-H',
  17725. '90ms-RKSJ-V',
  17726. '90msp-RKSJ-H',
  17727. '90msp-RKSJ-V',
  17728. '90pv-RKSJ-H',
  17729. '90pv-RKSJ-V',
  17730. 'Add-H',
  17731. 'Add-RKSJ-H',
  17732. 'Add-RKSJ-V',
  17733. 'Add-V',
  17734. 'Adobe-CNS1-0',
  17735. 'Adobe-CNS1-1',
  17736. 'Adobe-CNS1-2',
  17737. 'Adobe-CNS1-3',
  17738. 'Adobe-CNS1-4',
  17739. 'Adobe-CNS1-5',
  17740. 'Adobe-CNS1-6',
  17741. 'Adobe-GB1-0',
  17742. 'Adobe-GB1-1',
  17743. 'Adobe-GB1-2',
  17744. 'Adobe-GB1-3',
  17745. 'Adobe-GB1-4',
  17746. 'Adobe-GB1-5',
  17747. 'Adobe-Japan1-0',
  17748. 'Adobe-Japan1-1',
  17749. 'Adobe-Japan1-2',
  17750. 'Adobe-Japan1-3',
  17751. 'Adobe-Japan1-4',
  17752. 'Adobe-Japan1-5',
  17753. 'Adobe-Japan1-6',
  17754. 'Adobe-Korea1-0',
  17755. 'Adobe-Korea1-1',
  17756. 'Adobe-Korea1-2',
  17757. 'B5-H',
  17758. 'B5-V',
  17759. 'B5pc-H',
  17760. 'B5pc-V',
  17761. 'CNS-EUC-H',
  17762. 'CNS-EUC-V',
  17763. 'CNS1-H',
  17764. 'CNS1-V',
  17765. 'CNS2-H',
  17766. 'CNS2-V',
  17767. 'ETHK-B5-H',
  17768. 'ETHK-B5-V',
  17769. 'ETen-B5-H',
  17770. 'ETen-B5-V',
  17771. 'ETenms-B5-H',
  17772. 'ETenms-B5-V',
  17773. 'EUC-H',
  17774. 'EUC-V',
  17775. 'Ext-H',
  17776. 'Ext-RKSJ-H',
  17777. 'Ext-RKSJ-V',
  17778. 'Ext-V',
  17779. 'GB-EUC-H',
  17780. 'GB-EUC-V',
  17781. 'GB-H',
  17782. 'GB-V',
  17783. 'GBK-EUC-H',
  17784. 'GBK-EUC-V',
  17785. 'GBK2K-H',
  17786. 'GBK2K-V',
  17787. 'GBKp-EUC-H',
  17788. 'GBKp-EUC-V',
  17789. 'GBT-EUC-H',
  17790. 'GBT-EUC-V',
  17791. 'GBT-H',
  17792. 'GBT-V',
  17793. 'GBTpc-EUC-H',
  17794. 'GBTpc-EUC-V',
  17795. 'GBpc-EUC-H',
  17796. 'GBpc-EUC-V',
  17797. 'H',
  17798. 'HKdla-B5-H',
  17799. 'HKdla-B5-V',
  17800. 'HKdlb-B5-H',
  17801. 'HKdlb-B5-V',
  17802. 'HKgccs-B5-H',
  17803. 'HKgccs-B5-V',
  17804. 'HKm314-B5-H',
  17805. 'HKm314-B5-V',
  17806. 'HKm471-B5-H',
  17807. 'HKm471-B5-V',
  17808. 'HKscs-B5-H',
  17809. 'HKscs-B5-V',
  17810. 'Hankaku',
  17811. 'Hiragana',
  17812. 'KSC-EUC-H',
  17813. 'KSC-EUC-V',
  17814. 'KSC-H',
  17815. 'KSC-Johab-H',
  17816. 'KSC-Johab-V',
  17817. 'KSC-V',
  17818. 'KSCms-UHC-H',
  17819. 'KSCms-UHC-HW-H',
  17820. 'KSCms-UHC-HW-V',
  17821. 'KSCms-UHC-V',
  17822. 'KSCpc-EUC-H',
  17823. 'KSCpc-EUC-V',
  17824. 'Katakana',
  17825. 'NWP-H',
  17826. 'NWP-V',
  17827. 'RKSJ-H',
  17828. 'RKSJ-V',
  17829. 'Roman',
  17830. 'UniCNS-UCS2-H',
  17831. 'UniCNS-UCS2-V',
  17832. 'UniCNS-UTF16-H',
  17833. 'UniCNS-UTF16-V',
  17834. 'UniCNS-UTF32-H',
  17835. 'UniCNS-UTF32-V',
  17836. 'UniCNS-UTF8-H',
  17837. 'UniCNS-UTF8-V',
  17838. 'UniGB-UCS2-H',
  17839. 'UniGB-UCS2-V',
  17840. 'UniGB-UTF16-H',
  17841. 'UniGB-UTF16-V',
  17842. 'UniGB-UTF32-H',
  17843. 'UniGB-UTF32-V',
  17844. 'UniGB-UTF8-H',
  17845. 'UniGB-UTF8-V',
  17846. 'UniJIS-UCS2-H',
  17847. 'UniJIS-UCS2-HW-H',
  17848. 'UniJIS-UCS2-HW-V',
  17849. 'UniJIS-UCS2-V',
  17850. 'UniJIS-UTF16-H',
  17851. 'UniJIS-UTF16-V',
  17852. 'UniJIS-UTF32-H',
  17853. 'UniJIS-UTF32-V',
  17854. 'UniJIS-UTF8-H',
  17855. 'UniJIS-UTF8-V',
  17856. 'UniJIS2004-UTF16-H',
  17857. 'UniJIS2004-UTF16-V',
  17858. 'UniJIS2004-UTF32-H',
  17859. 'UniJIS2004-UTF32-V',
  17860. 'UniJIS2004-UTF8-H',
  17861. 'UniJIS2004-UTF8-V',
  17862. 'UniJISPro-UCS2-HW-V',
  17863. 'UniJISPro-UCS2-V',
  17864. 'UniJISPro-UTF8-V',
  17865. 'UniJISX0213-UTF32-H',
  17866. 'UniJISX0213-UTF32-V',
  17867. 'UniJISX02132004-UTF32-H',
  17868. 'UniJISX02132004-UTF32-V',
  17869. 'UniKS-UCS2-H',
  17870. 'UniKS-UCS2-V',
  17871. 'UniKS-UTF16-H',
  17872. 'UniKS-UTF16-V',
  17873. 'UniKS-UTF32-H',
  17874. 'UniKS-UTF32-V',
  17875. 'UniKS-UTF8-H',
  17876. 'UniKS-UTF8-V',
  17877. 'V',
  17878. 'WP-Symbol'];
  17879. // CMap, not to be confused with TrueType's cmap.
  17880. var CMap = (function CMapClosure() {
  17881. function CMap(builtInCMap) {
  17882. // Codespace ranges are stored as follows:
  17883. // [[1BytePairs], [2BytePairs], [3BytePairs], [4BytePairs]]
  17884. // where nBytePairs are ranges e.g. [low1, high1, low2, high2, ...]
  17885. this.codespaceRanges = [[], [], [], []];
  17886. this.numCodespaceRanges = 0;
  17887. // Map entries have one of two forms.
  17888. // - cid chars are 16-bit unsigned integers, stored as integers.
  17889. // - bf chars are variable-length byte sequences, stored as strings, with
  17890. // one byte per character.
  17891. this._map = [];
  17892. this.name = '';
  17893. this.vertical = false;
  17894. this.useCMap = null;
  17895. this.builtInCMap = builtInCMap;
  17896. }
  17897. CMap.prototype = {
  17898. addCodespaceRange: function(n, low, high) {
  17899. this.codespaceRanges[n - 1].push(low, high);
  17900. this.numCodespaceRanges++;
  17901. },
  17902. mapCidRange: function(low, high, dstLow) {
  17903. while (low <= high) {
  17904. this._map[low++] = dstLow++;
  17905. }
  17906. },
  17907. mapBfRange: function(low, high, dstLow) {
  17908. var lastByte = dstLow.length - 1;
  17909. while (low <= high) {
  17910. this._map[low++] = dstLow;
  17911. // Only the last byte has to be incremented.
  17912. dstLow = dstLow.substr(0, lastByte) +
  17913. String.fromCharCode(dstLow.charCodeAt(lastByte) + 1);
  17914. }
  17915. },
  17916. mapBfRangeToArray: function(low, high, array) {
  17917. var i = 0, ii = array.length;
  17918. while (low <= high && i < ii) {
  17919. this._map[low] = array[i++];
  17920. ++low;
  17921. }
  17922. },
  17923. // This is used for both bf and cid chars.
  17924. mapOne: function(src, dst) {
  17925. this._map[src] = dst;
  17926. },
  17927. lookup: function(code) {
  17928. return this._map[code];
  17929. },
  17930. contains: function(code) {
  17931. return this._map[code] !== undefined;
  17932. },
  17933. forEach: function(callback) {
  17934. // Most maps have fewer than 65536 entries, and for those we use normal
  17935. // array iteration. But really sparse tables are possible -- e.g. with
  17936. // indices in the *billions*. For such tables we use for..in, which isn't
  17937. // ideal because it stringifies the indices for all present elements, but
  17938. // it does avoid iterating over every undefined entry.
  17939. var map = this._map;
  17940. var length = map.length;
  17941. var i;
  17942. if (length <= 0x10000) {
  17943. for (i = 0; i < length; i++) {
  17944. if (map[i] !== undefined) {
  17945. callback(i, map[i]);
  17946. }
  17947. }
  17948. } else {
  17949. for (i in this._map) {
  17950. callback(i, map[i]);
  17951. }
  17952. }
  17953. },
  17954. charCodeOf: function(value) {
  17955. return this._map.indexOf(value);
  17956. },
  17957. getMap: function() {
  17958. return this._map;
  17959. },
  17960. readCharCode: function(str, offset, out) {
  17961. var c = 0;
  17962. var codespaceRanges = this.codespaceRanges;
  17963. var codespaceRangesLen = this.codespaceRanges.length;
  17964. // 9.7.6.2 CMap Mapping
  17965. // The code length is at most 4.
  17966. for (var n = 0; n < codespaceRangesLen; n++) {
  17967. c = ((c << 8) | str.charCodeAt(offset + n)) >>> 0;
  17968. // Check each codespace range to see if it falls within.
  17969. var codespaceRange = codespaceRanges[n];
  17970. for (var k = 0, kk = codespaceRange.length; k < kk;) {
  17971. var low = codespaceRange[k++];
  17972. var high = codespaceRange[k++];
  17973. if (c >= low && c <= high) {
  17974. out.charcode = c;
  17975. out.length = n + 1;
  17976. return;
  17977. }
  17978. }
  17979. }
  17980. out.charcode = 0;
  17981. out.length = 1;
  17982. },
  17983. get isIdentityCMap() {
  17984. if (!(this.name === 'Identity-H' || this.name === 'Identity-V')) {
  17985. return false;
  17986. }
  17987. if (this._map.length !== 0x10000) {
  17988. return false;
  17989. }
  17990. for (var i = 0; i < 0x10000; i++) {
  17991. if (this._map[i] !== i) {
  17992. return false;
  17993. }
  17994. }
  17995. return true;
  17996. }
  17997. };
  17998. return CMap;
  17999. })();
  18000. // A special case of CMap, where the _map array implicitly has a length of
  18001. // 65536 and each element is equal to its index.
  18002. var IdentityCMap = (function IdentityCMapClosure() {
  18003. function IdentityCMap(vertical, n) {
  18004. CMap.call(this);
  18005. this.vertical = vertical;
  18006. this.addCodespaceRange(n, 0, 0xffff);
  18007. }
  18008. Util.inherit(IdentityCMap, CMap, {});
  18009. IdentityCMap.prototype = {
  18010. addCodespaceRange: CMap.prototype.addCodespaceRange,
  18011. mapCidRange: function(low, high, dstLow) {
  18012. error('should not call mapCidRange');
  18013. },
  18014. mapBfRange: function(low, high, dstLow) {
  18015. error('should not call mapBfRange');
  18016. },
  18017. mapBfRangeToArray: function(low, high, array) {
  18018. error('should not call mapBfRangeToArray');
  18019. },
  18020. mapOne: function(src, dst) {
  18021. error('should not call mapCidOne');
  18022. },
  18023. lookup: function(code) {
  18024. return (isInt(code) && code <= 0xffff) ? code : undefined;
  18025. },
  18026. contains: function(code) {
  18027. return isInt(code) && code <= 0xffff;
  18028. },
  18029. forEach: function(callback) {
  18030. for (var i = 0; i <= 0xffff; i++) {
  18031. callback(i, i);
  18032. }
  18033. },
  18034. charCodeOf: function(value) {
  18035. return (isInt(value) && value <= 0xffff) ? value : -1;
  18036. },
  18037. getMap: function() {
  18038. // Sometimes identity maps must be instantiated, but it's rare.
  18039. var map = new Array(0x10000);
  18040. for (var i = 0; i <= 0xffff; i++) {
  18041. map[i] = i;
  18042. }
  18043. return map;
  18044. },
  18045. readCharCode: CMap.prototype.readCharCode,
  18046. get isIdentityCMap() {
  18047. error('should not access .isIdentityCMap');
  18048. }
  18049. };
  18050. return IdentityCMap;
  18051. })();
  18052. var BinaryCMapReader = (function BinaryCMapReaderClosure() {
  18053. function fetchBinaryData(url) {
  18054. var nonBinaryRequest = PDFJS.disableWorker;
  18055. var request = new XMLHttpRequest();
  18056. request.open('GET', url, false);
  18057. if (!nonBinaryRequest) {
  18058. try {
  18059. request.responseType = 'arraybuffer';
  18060. nonBinaryRequest = request.responseType !== 'arraybuffer';
  18061. } catch (e) {
  18062. nonBinaryRequest = true;
  18063. }
  18064. }
  18065. if (nonBinaryRequest && request.overrideMimeType) {
  18066. request.overrideMimeType('text/plain; charset=x-user-defined');
  18067. }
  18068. request.send(null);
  18069. if (nonBinaryRequest ? !request.responseText : !request.response) {
  18070. error('Unable to get binary cMap at: ' + url);
  18071. }
  18072. if (nonBinaryRequest) {
  18073. var data = Array.prototype.map.call(request.responseText, function (ch) {
  18074. return ch.charCodeAt(0) & 255;
  18075. });
  18076. return new Uint8Array(data);
  18077. }
  18078. return new Uint8Array(request.response);
  18079. }
  18080. function hexToInt(a, size) {
  18081. var n = 0;
  18082. for (var i = 0; i <= size; i++) {
  18083. n = (n << 8) | a[i];
  18084. }
  18085. return n >>> 0;
  18086. }
  18087. function hexToStr(a, size) {
  18088. // This code is hot. Special-case some common values to avoid creating an
  18089. // object with subarray().
  18090. if (size === 1) {
  18091. return String.fromCharCode(a[0], a[1]);
  18092. }
  18093. if (size === 3) {
  18094. return String.fromCharCode(a[0], a[1], a[2], a[3]);
  18095. }
  18096. return String.fromCharCode.apply(null, a.subarray(0, size + 1));
  18097. }
  18098. function addHex(a, b, size) {
  18099. var c = 0;
  18100. for (var i = size; i >= 0; i--) {
  18101. c += a[i] + b[i];
  18102. a[i] = c & 255;
  18103. c >>= 8;
  18104. }
  18105. }
  18106. function incHex(a, size) {
  18107. var c = 1;
  18108. for (var i = size; i >= 0 && c > 0; i--) {
  18109. c += a[i];
  18110. a[i] = c & 255;
  18111. c >>= 8;
  18112. }
  18113. }
  18114. var MAX_NUM_SIZE = 16;
  18115. var MAX_ENCODED_NUM_SIZE = 19; // ceil(MAX_NUM_SIZE * 7 / 8)
  18116. function BinaryCMapStream(data) {
  18117. this.buffer = data;
  18118. this.pos = 0;
  18119. this.end = data.length;
  18120. this.tmpBuf = new Uint8Array(MAX_ENCODED_NUM_SIZE);
  18121. }
  18122. BinaryCMapStream.prototype = {
  18123. readByte: function () {
  18124. if (this.pos >= this.end) {
  18125. return -1;
  18126. }
  18127. return this.buffer[this.pos++];
  18128. },
  18129. readNumber: function () {
  18130. var n = 0;
  18131. var last;
  18132. do {
  18133. var b = this.readByte();
  18134. if (b < 0) {
  18135. error('unexpected EOF in bcmap');
  18136. }
  18137. last = !(b & 0x80);
  18138. n = (n << 7) | (b & 0x7F);
  18139. } while (!last);
  18140. return n;
  18141. },
  18142. readSigned: function () {
  18143. var n = this.readNumber();
  18144. return (n & 1) ? ~(n >>> 1) : n >>> 1;
  18145. },
  18146. readHex: function (num, size) {
  18147. num.set(this.buffer.subarray(this.pos,
  18148. this.pos + size + 1));
  18149. this.pos += size + 1;
  18150. },
  18151. readHexNumber: function (num, size) {
  18152. var last;
  18153. var stack = this.tmpBuf, sp = 0;
  18154. do {
  18155. var b = this.readByte();
  18156. if (b < 0) {
  18157. error('unexpected EOF in bcmap');
  18158. }
  18159. last = !(b & 0x80);
  18160. stack[sp++] = b & 0x7F;
  18161. } while (!last);
  18162. var i = size, buffer = 0, bufferSize = 0;
  18163. while (i >= 0) {
  18164. while (bufferSize < 8 && stack.length > 0) {
  18165. buffer = (stack[--sp] << bufferSize) | buffer;
  18166. bufferSize += 7;
  18167. }
  18168. num[i] = buffer & 255;
  18169. i--;
  18170. buffer >>= 8;
  18171. bufferSize -= 8;
  18172. }
  18173. },
  18174. readHexSigned: function (num, size) {
  18175. this.readHexNumber(num, size);
  18176. var sign = num[size] & 1 ? 255 : 0;
  18177. var c = 0;
  18178. for (var i = 0; i <= size; i++) {
  18179. c = ((c & 1) << 8) | num[i];
  18180. num[i] = (c >> 1) ^ sign;
  18181. }
  18182. },
  18183. readString: function () {
  18184. var len = this.readNumber();
  18185. var s = '';
  18186. for (var i = 0; i < len; i++) {
  18187. s += String.fromCharCode(this.readNumber());
  18188. }
  18189. return s;
  18190. }
  18191. };
  18192. function processBinaryCMap(url, cMap, extend) {
  18193. var data = fetchBinaryData(url);
  18194. var stream = new BinaryCMapStream(data);
  18195. var header = stream.readByte();
  18196. cMap.vertical = !!(header & 1);
  18197. var useCMap = null;
  18198. var start = new Uint8Array(MAX_NUM_SIZE);
  18199. var end = new Uint8Array(MAX_NUM_SIZE);
  18200. var char = new Uint8Array(MAX_NUM_SIZE);
  18201. var charCode = new Uint8Array(MAX_NUM_SIZE);
  18202. var tmp = new Uint8Array(MAX_NUM_SIZE);
  18203. var code;
  18204. var b;
  18205. while ((b = stream.readByte()) >= 0) {
  18206. var type = b >> 5;
  18207. if (type === 7) { // metadata, e.g. comment or usecmap
  18208. switch (b & 0x1F) {
  18209. case 0:
  18210. stream.readString(); // skipping comment
  18211. break;
  18212. case 1:
  18213. useCMap = stream.readString();
  18214. break;
  18215. }
  18216. continue;
  18217. }
  18218. var sequence = !!(b & 0x10);
  18219. var dataSize = b & 15;
  18220. assert(dataSize + 1 <= MAX_NUM_SIZE);
  18221. var ucs2DataSize = 1;
  18222. var subitemsCount = stream.readNumber();
  18223. var i;
  18224. switch (type) {
  18225. case 0: // codespacerange
  18226. stream.readHex(start, dataSize);
  18227. stream.readHexNumber(end, dataSize);
  18228. addHex(end, start, dataSize);
  18229. cMap.addCodespaceRange(dataSize + 1, hexToInt(start, dataSize),
  18230. hexToInt(end, dataSize));
  18231. for (i = 1; i < subitemsCount; i++) {
  18232. incHex(end, dataSize);
  18233. stream.readHexNumber(start, dataSize);
  18234. addHex(start, end, dataSize);
  18235. stream.readHexNumber(end, dataSize);
  18236. addHex(end, start, dataSize);
  18237. cMap.addCodespaceRange(dataSize + 1, hexToInt(start, dataSize),
  18238. hexToInt(end, dataSize));
  18239. }
  18240. break;
  18241. case 1: // notdefrange
  18242. stream.readHex(start, dataSize);
  18243. stream.readHexNumber(end, dataSize);
  18244. addHex(end, start, dataSize);
  18245. code = stream.readNumber();
  18246. // undefined range, skipping
  18247. for (i = 1; i < subitemsCount; i++) {
  18248. incHex(end, dataSize);
  18249. stream.readHexNumber(start, dataSize);
  18250. addHex(start, end, dataSize);
  18251. stream.readHexNumber(end, dataSize);
  18252. addHex(end, start, dataSize);
  18253. code = stream.readNumber();
  18254. // nop
  18255. }
  18256. break;
  18257. case 2: // cidchar
  18258. stream.readHex(char, dataSize);
  18259. code = stream.readNumber();
  18260. cMap.mapOne(hexToInt(char, dataSize), code);
  18261. for (i = 1; i < subitemsCount; i++) {
  18262. incHex(char, dataSize);
  18263. if (!sequence) {
  18264. stream.readHexNumber(tmp, dataSize);
  18265. addHex(char, tmp, dataSize);
  18266. }
  18267. code = stream.readSigned() + (code + 1);
  18268. cMap.mapOne(hexToInt(char, dataSize), code);
  18269. }
  18270. break;
  18271. case 3: // cidrange
  18272. stream.readHex(start, dataSize);
  18273. stream.readHexNumber(end, dataSize);
  18274. addHex(end, start, dataSize);
  18275. code = stream.readNumber();
  18276. cMap.mapCidRange(hexToInt(start, dataSize), hexToInt(end, dataSize),
  18277. code);
  18278. for (i = 1; i < subitemsCount; i++) {
  18279. incHex(end, dataSize);
  18280. if (!sequence) {
  18281. stream.readHexNumber(start, dataSize);
  18282. addHex(start, end, dataSize);
  18283. } else {
  18284. start.set(end);
  18285. }
  18286. stream.readHexNumber(end, dataSize);
  18287. addHex(end, start, dataSize);
  18288. code = stream.readNumber();
  18289. cMap.mapCidRange(hexToInt(start, dataSize), hexToInt(end, dataSize),
  18290. code);
  18291. }
  18292. break;
  18293. case 4: // bfchar
  18294. stream.readHex(char, ucs2DataSize);
  18295. stream.readHex(charCode, dataSize);
  18296. cMap.mapOne(hexToInt(char, ucs2DataSize),
  18297. hexToStr(charCode, dataSize));
  18298. for (i = 1; i < subitemsCount; i++) {
  18299. incHex(char, ucs2DataSize);
  18300. if (!sequence) {
  18301. stream.readHexNumber(tmp, ucs2DataSize);
  18302. addHex(char, tmp, ucs2DataSize);
  18303. }
  18304. incHex(charCode, dataSize);
  18305. stream.readHexSigned(tmp, dataSize);
  18306. addHex(charCode, tmp, dataSize);
  18307. cMap.mapOne(hexToInt(char, ucs2DataSize),
  18308. hexToStr(charCode, dataSize));
  18309. }
  18310. break;
  18311. case 5: // bfrange
  18312. stream.readHex(start, ucs2DataSize);
  18313. stream.readHexNumber(end, ucs2DataSize);
  18314. addHex(end, start, ucs2DataSize);
  18315. stream.readHex(charCode, dataSize);
  18316. cMap.mapBfRange(hexToInt(start, ucs2DataSize),
  18317. hexToInt(end, ucs2DataSize),
  18318. hexToStr(charCode, dataSize));
  18319. for (i = 1; i < subitemsCount; i++) {
  18320. incHex(end, ucs2DataSize);
  18321. if (!sequence) {
  18322. stream.readHexNumber(start, ucs2DataSize);
  18323. addHex(start, end, ucs2DataSize);
  18324. } else {
  18325. start.set(end);
  18326. }
  18327. stream.readHexNumber(end, ucs2DataSize);
  18328. addHex(end, start, ucs2DataSize);
  18329. stream.readHex(charCode, dataSize);
  18330. cMap.mapBfRange(hexToInt(start, ucs2DataSize),
  18331. hexToInt(end, ucs2DataSize),
  18332. hexToStr(charCode, dataSize));
  18333. }
  18334. break;
  18335. default:
  18336. error('Unknown type: ' + type);
  18337. break;
  18338. }
  18339. }
  18340. if (useCMap) {
  18341. extend(useCMap);
  18342. }
  18343. return cMap;
  18344. }
  18345. function BinaryCMapReader() {}
  18346. BinaryCMapReader.prototype = {
  18347. read: processBinaryCMap
  18348. };
  18349. return BinaryCMapReader;
  18350. })();
  18351. var CMapFactory = (function CMapFactoryClosure() {
  18352. function strToInt(str) {
  18353. var a = 0;
  18354. for (var i = 0; i < str.length; i++) {
  18355. a = (a << 8) | str.charCodeAt(i);
  18356. }
  18357. return a >>> 0;
  18358. }
  18359. function expectString(obj) {
  18360. if (!isString(obj)) {
  18361. error('Malformed CMap: expected string.');
  18362. }
  18363. }
  18364. function expectInt(obj) {
  18365. if (!isInt(obj)) {
  18366. error('Malformed CMap: expected int.');
  18367. }
  18368. }
  18369. function parseBfChar(cMap, lexer) {
  18370. while (true) {
  18371. var obj = lexer.getObj();
  18372. if (isEOF(obj)) {
  18373. break;
  18374. }
  18375. if (isCmd(obj, 'endbfchar')) {
  18376. return;
  18377. }
  18378. expectString(obj);
  18379. var src = strToInt(obj);
  18380. obj = lexer.getObj();
  18381. // TODO are /dstName used?
  18382. expectString(obj);
  18383. var dst = obj;
  18384. cMap.mapOne(src, dst);
  18385. }
  18386. }
  18387. function parseBfRange(cMap, lexer) {
  18388. while (true) {
  18389. var obj = lexer.getObj();
  18390. if (isEOF(obj)) {
  18391. break;
  18392. }
  18393. if (isCmd(obj, 'endbfrange')) {
  18394. return;
  18395. }
  18396. expectString(obj);
  18397. var low = strToInt(obj);
  18398. obj = lexer.getObj();
  18399. expectString(obj);
  18400. var high = strToInt(obj);
  18401. obj = lexer.getObj();
  18402. if (isInt(obj) || isString(obj)) {
  18403. var dstLow = isInt(obj) ? String.fromCharCode(obj) : obj;
  18404. cMap.mapBfRange(low, high, dstLow);
  18405. } else if (isCmd(obj, '[')) {
  18406. obj = lexer.getObj();
  18407. var array = [];
  18408. while (!isCmd(obj, ']') && !isEOF(obj)) {
  18409. array.push(obj);
  18410. obj = lexer.getObj();
  18411. }
  18412. cMap.mapBfRangeToArray(low, high, array);
  18413. } else {
  18414. break;
  18415. }
  18416. }
  18417. error('Invalid bf range.');
  18418. }
  18419. function parseCidChar(cMap, lexer) {
  18420. while (true) {
  18421. var obj = lexer.getObj();
  18422. if (isEOF(obj)) {
  18423. break;
  18424. }
  18425. if (isCmd(obj, 'endcidchar')) {
  18426. return;
  18427. }
  18428. expectString(obj);
  18429. var src = strToInt(obj);
  18430. obj = lexer.getObj();
  18431. expectInt(obj);
  18432. var dst = obj;
  18433. cMap.mapOne(src, dst);
  18434. }
  18435. }
  18436. function parseCidRange(cMap, lexer) {
  18437. while (true) {
  18438. var obj = lexer.getObj();
  18439. if (isEOF(obj)) {
  18440. break;
  18441. }
  18442. if (isCmd(obj, 'endcidrange')) {
  18443. return;
  18444. }
  18445. expectString(obj);
  18446. var low = strToInt(obj);
  18447. obj = lexer.getObj();
  18448. expectString(obj);
  18449. var high = strToInt(obj);
  18450. obj = lexer.getObj();
  18451. expectInt(obj);
  18452. var dstLow = obj;
  18453. cMap.mapCidRange(low, high, dstLow);
  18454. }
  18455. }
  18456. function parseCodespaceRange(cMap, lexer) {
  18457. while (true) {
  18458. var obj = lexer.getObj();
  18459. if (isEOF(obj)) {
  18460. break;
  18461. }
  18462. if (isCmd(obj, 'endcodespacerange')) {
  18463. return;
  18464. }
  18465. if (!isString(obj)) {
  18466. break;
  18467. }
  18468. var low = strToInt(obj);
  18469. obj = lexer.getObj();
  18470. if (!isString(obj)) {
  18471. break;
  18472. }
  18473. var high = strToInt(obj);
  18474. cMap.addCodespaceRange(obj.length, low, high);
  18475. }
  18476. error('Invalid codespace range.');
  18477. }
  18478. function parseWMode(cMap, lexer) {
  18479. var obj = lexer.getObj();
  18480. if (isInt(obj)) {
  18481. cMap.vertical = !!obj;
  18482. }
  18483. }
  18484. function parseCMapName(cMap, lexer) {
  18485. var obj = lexer.getObj();
  18486. if (isName(obj) && isString(obj.name)) {
  18487. cMap.name = obj.name;
  18488. }
  18489. }
  18490. function parseCMap(cMap, lexer, builtInCMapParams, useCMap) {
  18491. var previous;
  18492. var embededUseCMap;
  18493. objLoop: while (true) {
  18494. var obj = lexer.getObj();
  18495. if (isEOF(obj)) {
  18496. break;
  18497. } else if (isName(obj)) {
  18498. if (obj.name === 'WMode') {
  18499. parseWMode(cMap, lexer);
  18500. } else if (obj.name === 'CMapName') {
  18501. parseCMapName(cMap, lexer);
  18502. }
  18503. previous = obj;
  18504. } else if (isCmd(obj)) {
  18505. switch (obj.cmd) {
  18506. case 'endcmap':
  18507. break objLoop;
  18508. case 'usecmap':
  18509. if (isName(previous)) {
  18510. embededUseCMap = previous.name;
  18511. }
  18512. break;
  18513. case 'begincodespacerange':
  18514. parseCodespaceRange(cMap, lexer);
  18515. break;
  18516. case 'beginbfchar':
  18517. parseBfChar(cMap, lexer);
  18518. break;
  18519. case 'begincidchar':
  18520. parseCidChar(cMap, lexer);
  18521. break;
  18522. case 'beginbfrange':
  18523. parseBfRange(cMap, lexer);
  18524. break;
  18525. case 'begincidrange':
  18526. parseCidRange(cMap, lexer);
  18527. break;
  18528. }
  18529. }
  18530. }
  18531. if (!useCMap && embededUseCMap) {
  18532. // Load the usecmap definition from the file only if there wasn't one
  18533. // specified.
  18534. useCMap = embededUseCMap;
  18535. }
  18536. if (useCMap) {
  18537. extendCMap(cMap, builtInCMapParams, useCMap);
  18538. }
  18539. }
  18540. function extendCMap(cMap, builtInCMapParams, useCMap) {
  18541. cMap.useCMap = createBuiltInCMap(useCMap, builtInCMapParams);
  18542. // If there aren't any code space ranges defined clone all the parent ones
  18543. // into this cMap.
  18544. if (cMap.numCodespaceRanges === 0) {
  18545. var useCodespaceRanges = cMap.useCMap.codespaceRanges;
  18546. for (var i = 0; i < useCodespaceRanges.length; i++) {
  18547. cMap.codespaceRanges[i] = useCodespaceRanges[i].slice();
  18548. }
  18549. cMap.numCodespaceRanges = cMap.useCMap.numCodespaceRanges;
  18550. }
  18551. // Merge the map into the current one, making sure not to override
  18552. // any previously defined entries.
  18553. cMap.useCMap.forEach(function(key, value) {
  18554. if (!cMap.contains(key)) {
  18555. cMap.mapOne(key, cMap.useCMap.lookup(key));
  18556. }
  18557. });
  18558. }
  18559. function parseBinaryCMap(name, builtInCMapParams) {
  18560. var url = builtInCMapParams.url + name + '.bcmap';
  18561. var cMap = new CMap(true);
  18562. new BinaryCMapReader().read(url, cMap, function (useCMap) {
  18563. extendCMap(cMap, builtInCMapParams, useCMap);
  18564. });
  18565. return cMap;
  18566. }
  18567. function createBuiltInCMap(name, builtInCMapParams) {
  18568. if (name === 'Identity-H') {
  18569. return new IdentityCMap(false, 2);
  18570. } else if (name === 'Identity-V') {
  18571. return new IdentityCMap(true, 2);
  18572. }
  18573. if (BUILT_IN_CMAPS.indexOf(name) === -1) {
  18574. error('Unknown cMap name: ' + name);
  18575. }
  18576. assert(builtInCMapParams, 'built-in cMap parameters are not provided');
  18577. if (builtInCMapParams.packed) {
  18578. return parseBinaryCMap(name, builtInCMapParams);
  18579. }
  18580. var request = new XMLHttpRequest();
  18581. var url = builtInCMapParams.url + name;
  18582. request.open('GET', url, false);
  18583. request.send(null);
  18584. if (!request.responseText) {
  18585. error('Unable to get cMap at: ' + url);
  18586. }
  18587. var cMap = new CMap(true);
  18588. var lexer = new Lexer(new StringStream(request.responseText));
  18589. parseCMap(cMap, lexer, builtInCMapParams, null);
  18590. return cMap;
  18591. }
  18592. return {
  18593. create: function (encoding, builtInCMapParams, useCMap) {
  18594. if (isName(encoding)) {
  18595. return createBuiltInCMap(encoding.name, builtInCMapParams);
  18596. } else if (isStream(encoding)) {
  18597. var cMap = new CMap();
  18598. var lexer = new Lexer(encoding);
  18599. try {
  18600. parseCMap(cMap, lexer, builtInCMapParams, useCMap);
  18601. } catch (e) {
  18602. warn('Invalid CMap data. ' + e);
  18603. }
  18604. if (cMap.isIdentityCMap) {
  18605. return createBuiltInCMap(cMap.name, builtInCMapParams);
  18606. }
  18607. return cMap;
  18608. }
  18609. error('Encoding required.');
  18610. }
  18611. };
  18612. })();
  18613. // Unicode Private Use Area
  18614. var PRIVATE_USE_OFFSET_START = 0xE000;
  18615. var PRIVATE_USE_OFFSET_END = 0xF8FF;
  18616. var SKIP_PRIVATE_USE_RANGE_F000_TO_F01F = false;
  18617. // PDF Glyph Space Units are one Thousandth of a TextSpace Unit
  18618. // except for Type 3 fonts
  18619. var PDF_GLYPH_SPACE_UNITS = 1000;
  18620. // Hinting is currently disabled due to unknown problems on windows
  18621. // in tracemonkey and various other pdfs with type1 fonts.
  18622. var HINTING_ENABLED = false;
  18623. // Accented charactars are not displayed properly on windows, using this flag
  18624. // to control analysis of seac charstrings.
  18625. var SEAC_ANALYSIS_ENABLED = false;
  18626. var FontFlags = {
  18627. FixedPitch: 1,
  18628. Serif: 2,
  18629. Symbolic: 4,
  18630. Script: 8,
  18631. Nonsymbolic: 32,
  18632. Italic: 64,
  18633. AllCap: 65536,
  18634. SmallCap: 131072,
  18635. ForceBold: 262144
  18636. };
  18637. var Encodings = {
  18638. ExpertEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18639. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18640. 'space', 'exclamsmall', 'Hungarumlautsmall', '', 'dollaroldstyle',
  18641. 'dollarsuperior', 'ampersandsmall', 'Acutesmall', 'parenleftsuperior',
  18642. 'parenrightsuperior', 'twodotenleader', 'onedotenleader', 'comma',
  18643. 'hyphen', 'period', 'fraction', 'zerooldstyle', 'oneoldstyle',
  18644. 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle',
  18645. 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'colon',
  18646. 'semicolon', 'commasuperior', 'threequartersemdash', 'periodsuperior',
  18647. 'questionsmall', '', 'asuperior', 'bsuperior', 'centsuperior', 'dsuperior',
  18648. 'esuperior', '', '', 'isuperior', '', '', 'lsuperior', 'msuperior',
  18649. 'nsuperior', 'osuperior', '', '', 'rsuperior', 'ssuperior', 'tsuperior',
  18650. '', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior', '',
  18651. 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall',
  18652. 'Asmall', 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall',
  18653. 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall',
  18654. 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall',
  18655. 'Vsmall', 'Wsmall', 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary',
  18656. 'onefitted', 'rupiah', 'Tildesmall', '', '', '', '', '', '', '', '', '',
  18657. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18658. '', '', '', '', '', '', 'exclamdownsmall', 'centoldstyle', 'Lslashsmall',
  18659. '', '', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall',
  18660. 'Caronsmall', '', 'Dotaccentsmall', '', '', 'Macronsmall', '', '',
  18661. 'figuredash', 'hypheninferior', '', '', 'Ogoneksmall', 'Ringsmall',
  18662. 'Cedillasmall', '', '', '', 'onequarter', 'onehalf', 'threequarters',
  18663. 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths',
  18664. 'seveneighths', 'onethird', 'twothirds', '', '', 'zerosuperior',
  18665. 'onesuperior', 'twosuperior', 'threesuperior', 'foursuperior',
  18666. 'fivesuperior', 'sixsuperior', 'sevensuperior', 'eightsuperior',
  18667. 'ninesuperior', 'zeroinferior', 'oneinferior', 'twoinferior',
  18668. 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior',
  18669. 'seveninferior', 'eightinferior', 'nineinferior', 'centinferior',
  18670. 'dollarinferior', 'periodinferior', 'commainferior', 'Agravesmall',
  18671. 'Aacutesmall', 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall',
  18672. 'Aringsmall', 'AEsmall', 'Ccedillasmall', 'Egravesmall', 'Eacutesmall',
  18673. 'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall',
  18674. 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall',
  18675. 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall',
  18676. 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall',
  18677. 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall',
  18678. 'Ydieresissmall'],
  18679. MacExpertEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18680. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18681. 'space', 'exclamsmall', 'Hungarumlautsmall', 'centoldstyle',
  18682. 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall', 'Acutesmall',
  18683. 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader',
  18684. 'onedotenleader', 'comma', 'hyphen', 'period', 'fraction', 'zerooldstyle',
  18685. 'oneoldstyle', 'twooldstyle', 'threeoldstyle', 'fouroldstyle',
  18686. 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle',
  18687. 'nineoldstyle', 'colon', 'semicolon', '', 'threequartersemdash', '',
  18688. 'questionsmall', '', '', '', '', 'Ethsmall', '', '', 'onequarter',
  18689. 'onehalf', 'threequarters', 'oneeighth', 'threeeighths', 'fiveeighths',
  18690. 'seveneighths', 'onethird', 'twothirds', '', '', '', '', '', '', 'ff',
  18691. 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior', '', 'parenrightinferior',
  18692. 'Circumflexsmall', 'hypheninferior', 'Gravesmall', 'Asmall', 'Bsmall',
  18693. 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall',
  18694. 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', 'Osmall', 'Psmall',
  18695. 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall',
  18696. 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah',
  18697. 'Tildesmall', '', '', 'asuperior', 'centsuperior', '', '', '', '',
  18698. 'Aacutesmall', 'Agravesmall', 'Acircumflexsmall', 'Adieresissmall',
  18699. 'Atildesmall', 'Aringsmall', 'Ccedillasmall', 'Eacutesmall', 'Egravesmall',
  18700. 'Ecircumflexsmall', 'Edieresissmall', 'Iacutesmall', 'Igravesmall',
  18701. 'Icircumflexsmall', 'Idieresissmall', 'Ntildesmall', 'Oacutesmall',
  18702. 'Ogravesmall', 'Ocircumflexsmall', 'Odieresissmall', 'Otildesmall',
  18703. 'Uacutesmall', 'Ugravesmall', 'Ucircumflexsmall', 'Udieresissmall', '',
  18704. 'eightsuperior', 'fourinferior', 'threeinferior', 'sixinferior',
  18705. 'eightinferior', 'seveninferior', 'Scaronsmall', '', 'centinferior',
  18706. 'twoinferior', '', 'Dieresissmall', '', 'Caronsmall', 'osuperior',
  18707. 'fiveinferior', '', 'commainferior', 'periodinferior', 'Yacutesmall', '',
  18708. 'dollarinferior', '', 'Thornsmall', '', 'nineinferior', 'zeroinferior',
  18709. 'Zcaronsmall', 'AEsmall', 'Oslashsmall', 'questiondownsmall',
  18710. 'oneinferior', 'Lslashsmall', '', '', '', '', '', '', 'Cedillasmall', '',
  18711. '', '', '', '', 'OEsmall', 'figuredash', 'hyphensuperior', '', '', '', '',
  18712. 'exclamdownsmall', '', 'Ydieresissmall', '', 'onesuperior', 'twosuperior',
  18713. 'threesuperior', 'foursuperior', 'fivesuperior', 'sixsuperior',
  18714. 'sevensuperior', 'ninesuperior', 'zerosuperior', '', 'esuperior',
  18715. 'rsuperior', 'tsuperior', '', '', 'isuperior', 'ssuperior', 'dsuperior',
  18716. '', '', '', '', '', 'lsuperior', 'Ogoneksmall', 'Brevesmall',
  18717. 'Macronsmall', 'bsuperior', 'nsuperior', 'msuperior', 'commasuperior',
  18718. 'periodsuperior', 'Dotaccentsmall', 'Ringsmall'],
  18719. MacRomanEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18720. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18721. 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent',
  18722. 'ampersand', 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus',
  18723. 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three',
  18724. 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon',
  18725. 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F',
  18726. 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
  18727. 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright',
  18728. 'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
  18729. 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
  18730. 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', '',
  18731. 'Adieresis', 'Aring', 'Ccedilla', 'Eacute', 'Ntilde', 'Odieresis',
  18732. 'Udieresis', 'aacute', 'agrave', 'acircumflex', 'adieresis', 'atilde',
  18733. 'aring', 'ccedilla', 'eacute', 'egrave', 'ecircumflex', 'edieresis',
  18734. 'iacute', 'igrave', 'icircumflex', 'idieresis', 'ntilde', 'oacute',
  18735. 'ograve', 'ocircumflex', 'odieresis', 'otilde', 'uacute', 'ugrave',
  18736. 'ucircumflex', 'udieresis', 'dagger', 'degree', 'cent', 'sterling',
  18737. 'section', 'bullet', 'paragraph', 'germandbls', 'registered', 'copyright',
  18738. 'trademark', 'acute', 'dieresis', 'notequal', 'AE', 'Oslash', 'infinity',
  18739. 'plusminus', 'lessequal', 'greaterequal', 'yen', 'mu', 'partialdiff',
  18740. 'summation', 'product', 'pi', 'integral', 'ordfeminine', 'ordmasculine',
  18741. 'Omega', 'ae', 'oslash', 'questiondown', 'exclamdown', 'logicalnot',
  18742. 'radical', 'florin', 'approxequal', 'Delta', 'guillemotleft',
  18743. 'guillemotright', 'ellipsis', 'space', 'Agrave', 'Atilde', 'Otilde', 'OE',
  18744. 'oe', 'endash', 'emdash', 'quotedblleft', 'quotedblright', 'quoteleft',
  18745. 'quoteright', 'divide', 'lozenge', 'ydieresis', 'Ydieresis', 'fraction',
  18746. 'currency', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'daggerdbl',
  18747. 'periodcentered', 'quotesinglbase', 'quotedblbase', 'perthousand',
  18748. 'Acircumflex', 'Ecircumflex', 'Aacute', 'Edieresis', 'Egrave', 'Iacute',
  18749. 'Icircumflex', 'Idieresis', 'Igrave', 'Oacute', 'Ocircumflex', 'apple',
  18750. 'Ograve', 'Uacute', 'Ucircumflex', 'Ugrave', 'dotlessi', 'circumflex',
  18751. 'tilde', 'macron', 'breve', 'dotaccent', 'ring', 'cedilla', 'hungarumlaut',
  18752. 'ogonek', 'caron'],
  18753. StandardEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18754. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18755. 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent',
  18756. 'ampersand', 'quoteright', 'parenleft', 'parenright', 'asterisk', 'plus',
  18757. 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three',
  18758. 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon',
  18759. 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F',
  18760. 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
  18761. 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright',
  18762. 'asciicircum', 'underscore', 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f',
  18763. 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
  18764. 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde',
  18765. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18766. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'exclamdown',
  18767. 'cent', 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency',
  18768. 'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft',
  18769. 'guilsinglright', 'fi', 'fl', '', 'endash', 'dagger', 'daggerdbl',
  18770. 'periodcentered', '', 'paragraph', 'bullet', 'quotesinglbase',
  18771. 'quotedblbase', 'quotedblright', 'guillemotright', 'ellipsis',
  18772. 'perthousand', '', 'questiondown', '', 'grave', 'acute', 'circumflex',
  18773. 'tilde', 'macron', 'breve', 'dotaccent', 'dieresis', '', 'ring', 'cedilla',
  18774. '', 'hungarumlaut', 'ogonek', 'caron', 'emdash', '', '', '', '', '', '',
  18775. '', '', '', '', '', '', '', '', '', '', 'AE', '', 'ordfeminine', '', '',
  18776. '', '', 'Lslash', 'Oslash', 'OE', 'ordmasculine', '', '', '', '', '', 'ae',
  18777. '', '', '', 'dotlessi', '', '', 'lslash', 'oslash', 'oe', 'germandbls'],
  18778. WinAnsiEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18779. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18780. 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent',
  18781. 'ampersand', 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus',
  18782. 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three',
  18783. 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon',
  18784. 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F',
  18785. 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
  18786. 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright',
  18787. 'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
  18788. 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
  18789. 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde',
  18790. 'bullet', 'Euro', 'bullet', 'quotesinglbase', 'florin', 'quotedblbase',
  18791. 'ellipsis', 'dagger', 'daggerdbl', 'circumflex', 'perthousand', 'Scaron',
  18792. 'guilsinglleft', 'OE', 'bullet', 'Zcaron', 'bullet', 'bullet', 'quoteleft',
  18793. 'quoteright', 'quotedblleft', 'quotedblright', 'bullet', 'endash',
  18794. 'emdash', 'tilde', 'trademark', 'scaron', 'guilsinglright', 'oe', 'bullet',
  18795. 'zcaron', 'Ydieresis', 'space', 'exclamdown', 'cent', 'sterling',
  18796. 'currency', 'yen', 'brokenbar', 'section', 'dieresis', 'copyright',
  18797. 'ordfeminine', 'guillemotleft', 'logicalnot', 'hyphen', 'registered',
  18798. 'macron', 'degree', 'plusminus', 'twosuperior', 'threesuperior', 'acute',
  18799. 'mu', 'paragraph', 'periodcentered', 'cedilla', 'onesuperior',
  18800. 'ordmasculine', 'guillemotright', 'onequarter', 'onehalf', 'threequarters',
  18801. 'questiondown', 'Agrave', 'Aacute', 'Acircumflex', 'Atilde', 'Adieresis',
  18802. 'Aring', 'AE', 'Ccedilla', 'Egrave', 'Eacute', 'Ecircumflex', 'Edieresis',
  18803. 'Igrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Eth', 'Ntilde', 'Ograve',
  18804. 'Oacute', 'Ocircumflex', 'Otilde', 'Odieresis', 'multiply', 'Oslash',
  18805. 'Ugrave', 'Uacute', 'Ucircumflex', 'Udieresis', 'Yacute', 'Thorn',
  18806. 'germandbls', 'agrave', 'aacute', 'acircumflex', 'atilde', 'adieresis',
  18807. 'aring', 'ae', 'ccedilla', 'egrave', 'eacute', 'ecircumflex', 'edieresis',
  18808. 'igrave', 'iacute', 'icircumflex', 'idieresis', 'eth', 'ntilde', 'ograve',
  18809. 'oacute', 'ocircumflex', 'otilde', 'odieresis', 'divide', 'oslash',
  18810. 'ugrave', 'uacute', 'ucircumflex', 'udieresis', 'yacute', 'thorn',
  18811. 'ydieresis'],
  18812. SymbolSetEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18813. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18814. 'space', 'exclam', 'universal', 'numbersign', 'existential', 'percent',
  18815. 'ampersand', 'suchthat', 'parenleft', 'parenright', 'asteriskmath', 'plus',
  18816. 'comma', 'minus', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four',
  18817. 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less',
  18818. 'equal', 'greater', 'question', 'congruent', 'Alpha', 'Beta', 'Chi',
  18819. 'Delta', 'Epsilon', 'Phi', 'Gamma', 'Eta', 'Iota', 'theta1', 'Kappa',
  18820. 'Lambda', 'Mu', 'Nu', 'Omicron', 'Pi', 'Theta', 'Rho', 'Sigma', 'Tau',
  18821. 'Upsilon', 'sigma1', 'Omega', 'Xi', 'Psi', 'Zeta', 'bracketleft',
  18822. 'therefore', 'bracketright', 'perpendicular', 'underscore', 'radicalex',
  18823. 'alpha', 'beta', 'chi', 'delta', 'epsilon', 'phi', 'gamma', 'eta', 'iota',
  18824. 'phi1', 'kappa', 'lambda', 'mu', 'nu', 'omicron', 'pi', 'theta', 'rho',
  18825. 'sigma', 'tau', 'upsilon', 'omega1', 'omega', 'xi', 'psi', 'zeta',
  18826. 'braceleft', 'bar', 'braceright', 'similar', '', '', '', '', '', '', '',
  18827. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18828. '', '', '', '', '', '', '', 'Euro', 'Upsilon1', 'minute', 'lessequal',
  18829. 'fraction', 'infinity', 'florin', 'club', 'diamond', 'heart', 'spade',
  18830. 'arrowboth', 'arrowleft', 'arrowup', 'arrowright', 'arrowdown', 'degree',
  18831. 'plusminus', 'second', 'greaterequal', 'multiply', 'proportional',
  18832. 'partialdiff', 'bullet', 'divide', 'notequal', 'equivalence',
  18833. 'approxequal', 'ellipsis', 'arrowvertex', 'arrowhorizex', 'carriagereturn',
  18834. 'aleph', 'Ifraktur', 'Rfraktur', 'weierstrass', 'circlemultiply',
  18835. 'circleplus', 'emptyset', 'intersection', 'union', 'propersuperset',
  18836. 'reflexsuperset', 'notsubset', 'propersubset', 'reflexsubset', 'element',
  18837. 'notelement', 'angle', 'gradient', 'registerserif', 'copyrightserif',
  18838. 'trademarkserif', 'product', 'radical', 'dotmath', 'logicalnot',
  18839. 'logicaland', 'logicalor', 'arrowdblboth', 'arrowdblleft', 'arrowdblup',
  18840. 'arrowdblright', 'arrowdbldown', 'lozenge', 'angleleft', 'registersans',
  18841. 'copyrightsans', 'trademarksans', 'summation', 'parenlefttp',
  18842. 'parenleftex', 'parenleftbt', 'bracketlefttp', 'bracketleftex',
  18843. 'bracketleftbt', 'bracelefttp', 'braceleftmid', 'braceleftbt', 'braceex',
  18844. '', 'angleright', 'integral', 'integraltp', 'integralex', 'integralbt',
  18845. 'parenrighttp', 'parenrightex', 'parenrightbt', 'bracketrighttp',
  18846. 'bracketrightex', 'bracketrightbt', 'bracerighttp', 'bracerightmid',
  18847. 'bracerightbt'],
  18848. ZapfDingbatsEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18849. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18850. 'space', 'a1', 'a2', 'a202', 'a3', 'a4', 'a5', 'a119', 'a118', 'a117',
  18851. 'a11', 'a12', 'a13', 'a14', 'a15', 'a16', 'a105', 'a17', 'a18', 'a19',
  18852. 'a20', 'a21', 'a22', 'a23', 'a24', 'a25', 'a26', 'a27', 'a28', 'a6', 'a7',
  18853. 'a8', 'a9', 'a10', 'a29', 'a30', 'a31', 'a32', 'a33', 'a34', 'a35', 'a36',
  18854. 'a37', 'a38', 'a39', 'a40', 'a41', 'a42', 'a43', 'a44', 'a45', 'a46',
  18855. 'a47', 'a48', 'a49', 'a50', 'a51', 'a52', 'a53', 'a54', 'a55', 'a56',
  18856. 'a57', 'a58', 'a59', 'a60', 'a61', 'a62', 'a63', 'a64', 'a65', 'a66',
  18857. 'a67', 'a68', 'a69', 'a70', 'a71', 'a72', 'a73', 'a74', 'a203', 'a75',
  18858. 'a204', 'a76', 'a77', 'a78', 'a79', 'a81', 'a82', 'a83', 'a84', 'a97',
  18859. 'a98', 'a99', 'a100', '', 'a89', 'a90', 'a93', 'a94', 'a91', 'a92', 'a205',
  18860. 'a85', 'a206', 'a86', 'a87', 'a88', 'a95', 'a96', '', '', '', '', '', '',
  18861. '', '', '', '', '', '', '', '', '', '', '', '', '', 'a101', 'a102', 'a103',
  18862. 'a104', 'a106', 'a107', 'a108', 'a112', 'a111', 'a110', 'a109', 'a120',
  18863. 'a121', 'a122', 'a123', 'a124', 'a125', 'a126', 'a127', 'a128', 'a129',
  18864. 'a130', 'a131', 'a132', 'a133', 'a134', 'a135', 'a136', 'a137', 'a138',
  18865. 'a139', 'a140', 'a141', 'a142', 'a143', 'a144', 'a145', 'a146', 'a147',
  18866. 'a148', 'a149', 'a150', 'a151', 'a152', 'a153', 'a154', 'a155', 'a156',
  18867. 'a157', 'a158', 'a159', 'a160', 'a161', 'a163', 'a164', 'a196', 'a165',
  18868. 'a192', 'a166', 'a167', 'a168', 'a169', 'a170', 'a171', 'a172', 'a173',
  18869. 'a162', 'a174', 'a175', 'a176', 'a177', 'a178', 'a179', 'a193', 'a180',
  18870. 'a199', 'a181', 'a200', 'a182', '', 'a201', 'a183', 'a184', 'a197', 'a185',
  18871. 'a194', 'a198', 'a186', 'a195', 'a187', 'a188', 'a189', 'a190', 'a191']
  18872. };
  18873. /**
  18874. * Hold a map of decoded fonts and of the standard fourteen Type1
  18875. * fonts and their acronyms.
  18876. */
  18877. var stdFontMap = {
  18878. 'ArialNarrow': 'Helvetica',
  18879. 'ArialNarrow-Bold': 'Helvetica-Bold',
  18880. 'ArialNarrow-BoldItalic': 'Helvetica-BoldOblique',
  18881. 'ArialNarrow-Italic': 'Helvetica-Oblique',
  18882. 'ArialBlack': 'Helvetica',
  18883. 'ArialBlack-Bold': 'Helvetica-Bold',
  18884. 'ArialBlack-BoldItalic': 'Helvetica-BoldOblique',
  18885. 'ArialBlack-Italic': 'Helvetica-Oblique',
  18886. 'Arial': 'Helvetica',
  18887. 'Arial-Bold': 'Helvetica-Bold',
  18888. 'Arial-BoldItalic': 'Helvetica-BoldOblique',
  18889. 'Arial-Italic': 'Helvetica-Oblique',
  18890. 'Arial-BoldItalicMT': 'Helvetica-BoldOblique',
  18891. 'Arial-BoldMT': 'Helvetica-Bold',
  18892. 'Arial-ItalicMT': 'Helvetica-Oblique',
  18893. 'ArialMT': 'Helvetica',
  18894. 'Courier-Bold': 'Courier-Bold',
  18895. 'Courier-BoldItalic': 'Courier-BoldOblique',
  18896. 'Courier-Italic': 'Courier-Oblique',
  18897. 'CourierNew': 'Courier',
  18898. 'CourierNew-Bold': 'Courier-Bold',
  18899. 'CourierNew-BoldItalic': 'Courier-BoldOblique',
  18900. 'CourierNew-Italic': 'Courier-Oblique',
  18901. 'CourierNewPS-BoldItalicMT': 'Courier-BoldOblique',
  18902. 'CourierNewPS-BoldMT': 'Courier-Bold',
  18903. 'CourierNewPS-ItalicMT': 'Courier-Oblique',
  18904. 'CourierNewPSMT': 'Courier',
  18905. 'Helvetica': 'Helvetica',
  18906. 'Helvetica-Bold': 'Helvetica-Bold',
  18907. 'Helvetica-BoldItalic': 'Helvetica-BoldOblique',
  18908. 'Helvetica-BoldOblique': 'Helvetica-BoldOblique',
  18909. 'Helvetica-Italic': 'Helvetica-Oblique',
  18910. 'Helvetica-Oblique':'Helvetica-Oblique',
  18911. 'Symbol-Bold': 'Symbol',
  18912. 'Symbol-BoldItalic': 'Symbol',
  18913. 'Symbol-Italic': 'Symbol',
  18914. 'TimesNewRoman': 'Times-Roman',
  18915. 'TimesNewRoman-Bold': 'Times-Bold',
  18916. 'TimesNewRoman-BoldItalic': 'Times-BoldItalic',
  18917. 'TimesNewRoman-Italic': 'Times-Italic',
  18918. 'TimesNewRomanPS': 'Times-Roman',
  18919. 'TimesNewRomanPS-Bold': 'Times-Bold',
  18920. 'TimesNewRomanPS-BoldItalic': 'Times-BoldItalic',
  18921. 'TimesNewRomanPS-BoldItalicMT': 'Times-BoldItalic',
  18922. 'TimesNewRomanPS-BoldMT': 'Times-Bold',
  18923. 'TimesNewRomanPS-Italic': 'Times-Italic',
  18924. 'TimesNewRomanPS-ItalicMT': 'Times-Italic',
  18925. 'TimesNewRomanPSMT': 'Times-Roman',
  18926. 'TimesNewRomanPSMT-Bold': 'Times-Bold',
  18927. 'TimesNewRomanPSMT-BoldItalic': 'Times-BoldItalic',
  18928. 'TimesNewRomanPSMT-Italic': 'Times-Italic'
  18929. };
  18930. /**
  18931. * Holds the map of the non-standard fonts that might be included as a standard
  18932. * fonts without glyph data.
  18933. */
  18934. var nonStdFontMap = {
  18935. 'CenturyGothic': 'Helvetica',
  18936. 'CenturyGothic-Bold': 'Helvetica-Bold',
  18937. 'CenturyGothic-BoldItalic': 'Helvetica-BoldOblique',
  18938. 'CenturyGothic-Italic': 'Helvetica-Oblique',
  18939. 'ComicSansMS': 'Comic Sans MS',
  18940. 'ComicSansMS-Bold': 'Comic Sans MS-Bold',
  18941. 'ComicSansMS-BoldItalic': 'Comic Sans MS-BoldItalic',
  18942. 'ComicSansMS-Italic': 'Comic Sans MS-Italic',
  18943. 'LucidaConsole': 'Courier',
  18944. 'LucidaConsole-Bold': 'Courier-Bold',
  18945. 'LucidaConsole-BoldItalic': 'Courier-BoldOblique',
  18946. 'LucidaConsole-Italic': 'Courier-Oblique',
  18947. 'MS-Gothic': 'MS Gothic',
  18948. 'MS-Gothic-Bold': 'MS Gothic-Bold',
  18949. 'MS-Gothic-BoldItalic': 'MS Gothic-BoldItalic',
  18950. 'MS-Gothic-Italic': 'MS Gothic-Italic',
  18951. 'MS-Mincho': 'MS Mincho',
  18952. 'MS-Mincho-Bold': 'MS Mincho-Bold',
  18953. 'MS-Mincho-BoldItalic': 'MS Mincho-BoldItalic',
  18954. 'MS-Mincho-Italic': 'MS Mincho-Italic',
  18955. 'MS-PGothic': 'MS PGothic',
  18956. 'MS-PGothic-Bold': 'MS PGothic-Bold',
  18957. 'MS-PGothic-BoldItalic': 'MS PGothic-BoldItalic',
  18958. 'MS-PGothic-Italic': 'MS PGothic-Italic',
  18959. 'MS-PMincho': 'MS PMincho',
  18960. 'MS-PMincho-Bold': 'MS PMincho-Bold',
  18961. 'MS-PMincho-BoldItalic': 'MS PMincho-BoldItalic',
  18962. 'MS-PMincho-Italic': 'MS PMincho-Italic',
  18963. 'Wingdings': 'ZapfDingbats'
  18964. };
  18965. var serifFonts = {
  18966. 'Adobe Jenson': true, 'Adobe Text': true, 'Albertus': true,
  18967. 'Aldus': true, 'Alexandria': true, 'Algerian': true,
  18968. 'American Typewriter': true, 'Antiqua': true, 'Apex': true,
  18969. 'Arno': true, 'Aster': true, 'Aurora': true,
  18970. 'Baskerville': true, 'Bell': true, 'Bembo': true,
  18971. 'Bembo Schoolbook': true, 'Benguiat': true, 'Berkeley Old Style': true,
  18972. 'Bernhard Modern': true, 'Berthold City': true, 'Bodoni': true,
  18973. 'Bauer Bodoni': true, 'Book Antiqua': true, 'Bookman': true,
  18974. 'Bordeaux Roman': true, 'Californian FB': true, 'Calisto': true,
  18975. 'Calvert': true, 'Capitals': true, 'Cambria': true,
  18976. 'Cartier': true, 'Caslon': true, 'Catull': true,
  18977. 'Centaur': true, 'Century Old Style': true, 'Century Schoolbook': true,
  18978. 'Chaparral': true, 'Charis SIL': true, 'Cheltenham': true,
  18979. 'Cholla Slab': true, 'Clarendon': true, 'Clearface': true,
  18980. 'Cochin': true, 'Colonna': true, 'Computer Modern': true,
  18981. 'Concrete Roman': true, 'Constantia': true, 'Cooper Black': true,
  18982. 'Corona': true, 'Ecotype': true, 'Egyptienne': true,
  18983. 'Elephant': true, 'Excelsior': true, 'Fairfield': true,
  18984. 'FF Scala': true, 'Folkard': true, 'Footlight': true,
  18985. 'FreeSerif': true, 'Friz Quadrata': true, 'Garamond': true,
  18986. 'Gentium': true, 'Georgia': true, 'Gloucester': true,
  18987. 'Goudy Old Style': true, 'Goudy Schoolbook': true, 'Goudy Pro Font': true,
  18988. 'Granjon': true, 'Guardian Egyptian': true, 'Heather': true,
  18989. 'Hercules': true, 'High Tower Text': true, 'Hiroshige': true,
  18990. 'Hoefler Text': true, 'Humana Serif': true, 'Imprint': true,
  18991. 'Ionic No. 5': true, 'Janson': true, 'Joanna': true,
  18992. 'Korinna': true, 'Lexicon': true, 'Liberation Serif': true,
  18993. 'Linux Libertine': true, 'Literaturnaya': true, 'Lucida': true,
  18994. 'Lucida Bright': true, 'Melior': true, 'Memphis': true,
  18995. 'Miller': true, 'Minion': true, 'Modern': true,
  18996. 'Mona Lisa': true, 'Mrs Eaves': true, 'MS Serif': true,
  18997. 'Museo Slab': true, 'New York': true, 'Nimbus Roman': true,
  18998. 'NPS Rawlinson Roadway': true, 'Palatino': true, 'Perpetua': true,
  18999. 'Plantin': true, 'Plantin Schoolbook': true, 'Playbill': true,
  19000. 'Poor Richard': true, 'Rawlinson Roadway': true, 'Renault': true,
  19001. 'Requiem': true, 'Rockwell': true, 'Roman': true,
  19002. 'Rotis Serif': true, 'Sabon': true, 'Scala': true,
  19003. 'Seagull': true, 'Sistina': true, 'Souvenir': true,
  19004. 'STIX': true, 'Stone Informal': true, 'Stone Serif': true,
  19005. 'Sylfaen': true, 'Times': true, 'Trajan': true,
  19006. 'Trinité': true, 'Trump Mediaeval': true, 'Utopia': true,
  19007. 'Vale Type': true, 'Bitstream Vera': true, 'Vera Serif': true,
  19008. 'Versailles': true, 'Wanted': true, 'Weiss': true,
  19009. 'Wide Latin': true, 'Windsor': true, 'XITS': true
  19010. };
  19011. var symbolsFonts = {
  19012. 'Dingbats': true, 'Symbol': true, 'ZapfDingbats': true
  19013. };
  19014. // Glyph map for well-known standard fonts. Sometimes Ghostscript uses CID fonts
  19015. // but does not embed the CID to GID mapping. The mapping is incomplete for all
  19016. // glyphs, but common for some set of the standard fonts.
  19017. var GlyphMapForStandardFonts = {
  19018. '2': 10, '3': 32, '4': 33, '5': 34, '6': 35, '7': 36, '8': 37, '9': 38,
  19019. '10': 39, '11': 40, '12': 41, '13': 42, '14': 43, '15': 44, '16': 45,
  19020. '17': 46, '18': 47, '19': 48, '20': 49, '21': 50, '22': 51, '23': 52,
  19021. '24': 53, '25': 54, '26': 55, '27': 56, '28': 57, '29': 58, '30': 894,
  19022. '31': 60, '32': 61, '33': 62, '34': 63, '35': 64, '36': 65, '37': 66,
  19023. '38': 67, '39': 68, '40': 69, '41': 70, '42': 71, '43': 72, '44': 73,
  19024. '45': 74, '46': 75, '47': 76, '48': 77, '49': 78, '50': 79, '51': 80,
  19025. '52': 81, '53': 82, '54': 83, '55': 84, '56': 85, '57': 86, '58': 87,
  19026. '59': 88, '60': 89, '61': 90, '62': 91, '63': 92, '64': 93, '65': 94,
  19027. '66': 95, '67': 96, '68': 97, '69': 98, '70': 99, '71': 100, '72': 101,
  19028. '73': 102, '74': 103, '75': 104, '76': 105, '77': 106, '78': 107, '79': 108,
  19029. '80': 109, '81': 110, '82': 111, '83': 112, '84': 113, '85': 114, '86': 115,
  19030. '87': 116, '88': 117, '89': 118, '90': 119, '91': 120, '92': 121, '93': 122,
  19031. '94': 123, '95': 124, '96': 125, '97': 126, '98': 196, '99': 197, '100': 199,
  19032. '101': 201, '102': 209, '103': 214, '104': 220, '105': 225, '106': 224,
  19033. '107': 226, '108': 228, '109': 227, '110': 229, '111': 231, '112': 233,
  19034. '113': 232, '114': 234, '115': 235, '116': 237, '117': 236, '118': 238,
  19035. '119': 239, '120': 241, '121': 243, '122': 242, '123': 244, '124': 246,
  19036. '125': 245, '126': 250, '127': 249, '128': 251, '129': 252, '130': 8224,
  19037. '131': 176, '132': 162, '133': 163, '134': 167, '135': 8226, '136': 182,
  19038. '137': 223, '138': 174, '139': 169, '140': 8482, '141': 180, '142': 168,
  19039. '143': 8800, '144': 198, '145': 216, '146': 8734, '147': 177, '148': 8804,
  19040. '149': 8805, '150': 165, '151': 181, '152': 8706, '153': 8721, '154': 8719,
  19041. '156': 8747, '157': 170, '158': 186, '159': 8486, '160': 230, '161': 248,
  19042. '162': 191, '163': 161, '164': 172, '165': 8730, '166': 402, '167': 8776,
  19043. '168': 8710, '169': 171, '170': 187, '171': 8230, '210': 218, '223': 711,
  19044. '224': 321, '225': 322, '227': 353, '229': 382, '234': 253, '252': 263,
  19045. '253': 268, '254': 269, '258': 258, '260': 260, '261': 261, '265': 280,
  19046. '266': 281, '268': 283, '269': 313, '275': 323, '276': 324, '278': 328,
  19047. '284': 345, '285': 346, '286': 347, '292': 367, '295': 377, '296': 378,
  19048. '298': 380, '305': 963,
  19049. '306': 964, '307': 966, '308': 8215, '309': 8252, '310': 8319, '311': 8359,
  19050. '312': 8592, '313': 8593, '337': 9552, '493': 1039, '494': 1040, '705': 1524,
  19051. '706': 8362, '710': 64288, '711': 64298, '759': 1617, '761': 1776,
  19052. '763': 1778, '775': 1652, '777': 1764, '778': 1780, '779': 1781, '780': 1782,
  19053. '782': 771, '783': 64726, '786': 8363, '788': 8532, '790': 768, '791': 769,
  19054. '792': 768, '795': 803, '797': 64336, '798': 64337, '799': 64342,
  19055. '800': 64343, '801': 64344, '802': 64345, '803': 64362, '804': 64363,
  19056. '805': 64364, '2424': 7821, '2425': 7822, '2426': 7823, '2427': 7824,
  19057. '2428': 7825, '2429': 7826, '2430': 7827, '2433': 7682, '2678': 8045,
  19058. '2679': 8046, '2830': 1552, '2838': 686, '2840': 751, '2842': 753,
  19059. '2843': 754, '2844': 755, '2846': 757, '2856': 767, '2857': 848, '2858': 849,
  19060. '2862': 853, '2863': 854, '2864': 855, '2865': 861, '2866': 862, '2906': 7460,
  19061. '2908': 7462, '2909': 7463, '2910': 7464, '2912': 7466, '2913': 7467,
  19062. '2914': 7468, '2916': 7470, '2917': 7471, '2918': 7472, '2920': 7474,
  19063. '2921': 7475, '2922': 7476, '2924': 7478, '2925': 7479, '2926': 7480,
  19064. '2928': 7482, '2929': 7483, '2930': 7484, '2932': 7486, '2933': 7487,
  19065. '2934': 7488, '2936': 7490, '2937': 7491, '2938': 7492, '2940': 7494,
  19066. '2941': 7495, '2942': 7496, '2944': 7498, '2946': 7500, '2948': 7502,
  19067. '2950': 7504, '2951': 7505, '2952': 7506, '2954': 7508, '2955': 7509,
  19068. '2956': 7510, '2958': 7512, '2959': 7513, '2960': 7514, '2962': 7516,
  19069. '2963': 7517, '2964': 7518, '2966': 7520, '2967': 7521, '2968': 7522,
  19070. '2970': 7524, '2971': 7525, '2972': 7526, '2974': 7528, '2975': 7529,
  19071. '2976': 7530, '2978': 1537, '2979': 1538, '2980': 1539, '2982': 1549,
  19072. '2983': 1551, '2984': 1552, '2986': 1554, '2987': 1555, '2988': 1556,
  19073. '2990': 1623, '2991': 1624, '2995': 1775, '2999': 1791, '3002': 64290,
  19074. '3003': 64291, '3004': 64292, '3006': 64294, '3007': 64295, '3008': 64296,
  19075. '3011': 1900, '3014': 8223, '3015': 8244, '3017': 7532, '3018': 7533,
  19076. '3019': 7534, '3075': 7590, '3076': 7591, '3079': 7594, '3080': 7595,
  19077. '3083': 7598, '3084': 7599, '3087': 7602, '3088': 7603, '3091': 7606,
  19078. '3092': 7607, '3095': 7610, '3096': 7611, '3099': 7614, '3100': 7615,
  19079. '3103': 7618, '3104': 7619, '3107': 8337, '3108': 8338, '3116': 1884,
  19080. '3119': 1885, '3120': 1885, '3123': 1886, '3124': 1886, '3127': 1887,
  19081. '3128': 1887, '3131': 1888, '3132': 1888, '3135': 1889, '3136': 1889,
  19082. '3139': 1890, '3140': 1890, '3143': 1891, '3144': 1891, '3147': 1892,
  19083. '3148': 1892, '3153': 580, '3154': 581, '3157': 584, '3158': 585, '3161': 588,
  19084. '3162': 589, '3165': 891, '3166': 892, '3169': 1274, '3170': 1275,
  19085. '3173': 1278, '3174': 1279, '3181': 7622, '3182': 7623, '3282': 11799,
  19086. '3316': 578, '3379': 42785, '3393': 1159, '3416': 8377
  19087. };
  19088. // Some characters, e.g. copyrightserif, are mapped to the private use area and
  19089. // might not be displayed using standard fonts. Mapping/hacking well-known chars
  19090. // to the similar equivalents in the normal characters range.
  19091. var SpecialPUASymbols = {
  19092. '63721': 0x00A9, // copyrightsans (0xF8E9) => copyright
  19093. '63193': 0x00A9, // copyrightserif (0xF6D9) => copyright
  19094. '63720': 0x00AE, // registersans (0xF8E8) => registered
  19095. '63194': 0x00AE, // registerserif (0xF6DA) => registered
  19096. '63722': 0x2122, // trademarksans (0xF8EA) => trademark
  19097. '63195': 0x2122, // trademarkserif (0xF6DB) => trademark
  19098. '63729': 0x23A7, // bracelefttp (0xF8F1)
  19099. '63730': 0x23A8, // braceleftmid (0xF8F2)
  19100. '63731': 0x23A9, // braceleftbt (0xF8F3)
  19101. '63740': 0x23AB, // bracerighttp (0xF8FC)
  19102. '63741': 0x23AC, // bracerightmid (0xF8FD)
  19103. '63742': 0x23AD, // bracerightbt (0xF8FE)
  19104. '63726': 0x23A1, // bracketlefttp (0xF8EE)
  19105. '63727': 0x23A2, // bracketleftex (0xF8EF)
  19106. '63728': 0x23A3, // bracketleftbt (0xF8F0)
  19107. '63737': 0x23A4, // bracketrighttp (0xF8F9)
  19108. '63738': 0x23A5, // bracketrightex (0xF8FA)
  19109. '63739': 0x23A6, // bracketrightbt (0xF8FB)
  19110. '63723': 0x239B, // parenlefttp (0xF8EB)
  19111. '63724': 0x239C, // parenleftex (0xF8EC)
  19112. '63725': 0x239D, // parenleftbt (0xF8ED)
  19113. '63734': 0x239E, // parenrighttp (0xF8F6)
  19114. '63735': 0x239F, // parenrightex (0xF8F7)
  19115. '63736': 0x23A0, // parenrightbt (0xF8F8)
  19116. };
  19117. function mapSpecialUnicodeValues(code) {
  19118. if (code >= 0xFFF0 && code <= 0xFFFF) { // Specials unicode block.
  19119. return 0;
  19120. } else if (code >= 0xF600 && code <= 0xF8FF) {
  19121. return (SpecialPUASymbols[code] || code);
  19122. }
  19123. return code;
  19124. }
  19125. var UnicodeRanges = [
  19126. { 'begin': 0x0000, 'end': 0x007F }, // Basic Latin
  19127. { 'begin': 0x0080, 'end': 0x00FF }, // Latin-1 Supplement
  19128. { 'begin': 0x0100, 'end': 0x017F }, // Latin Extended-A
  19129. { 'begin': 0x0180, 'end': 0x024F }, // Latin Extended-B
  19130. { 'begin': 0x0250, 'end': 0x02AF }, // IPA Extensions
  19131. { 'begin': 0x02B0, 'end': 0x02FF }, // Spacing Modifier Letters
  19132. { 'begin': 0x0300, 'end': 0x036F }, // Combining Diacritical Marks
  19133. { 'begin': 0x0370, 'end': 0x03FF }, // Greek and Coptic
  19134. { 'begin': 0x2C80, 'end': 0x2CFF }, // Coptic
  19135. { 'begin': 0x0400, 'end': 0x04FF }, // Cyrillic
  19136. { 'begin': 0x0530, 'end': 0x058F }, // Armenian
  19137. { 'begin': 0x0590, 'end': 0x05FF }, // Hebrew
  19138. { 'begin': 0xA500, 'end': 0xA63F }, // Vai
  19139. { 'begin': 0x0600, 'end': 0x06FF }, // Arabic
  19140. { 'begin': 0x07C0, 'end': 0x07FF }, // NKo
  19141. { 'begin': 0x0900, 'end': 0x097F }, // Devanagari
  19142. { 'begin': 0x0980, 'end': 0x09FF }, // Bengali
  19143. { 'begin': 0x0A00, 'end': 0x0A7F }, // Gurmukhi
  19144. { 'begin': 0x0A80, 'end': 0x0AFF }, // Gujarati
  19145. { 'begin': 0x0B00, 'end': 0x0B7F }, // Oriya
  19146. { 'begin': 0x0B80, 'end': 0x0BFF }, // Tamil
  19147. { 'begin': 0x0C00, 'end': 0x0C7F }, // Telugu
  19148. { 'begin': 0x0C80, 'end': 0x0CFF }, // Kannada
  19149. { 'begin': 0x0D00, 'end': 0x0D7F }, // Malayalam
  19150. { 'begin': 0x0E00, 'end': 0x0E7F }, // Thai
  19151. { 'begin': 0x0E80, 'end': 0x0EFF }, // Lao
  19152. { 'begin': 0x10A0, 'end': 0x10FF }, // Georgian
  19153. { 'begin': 0x1B00, 'end': 0x1B7F }, // Balinese
  19154. { 'begin': 0x1100, 'end': 0x11FF }, // Hangul Jamo
  19155. { 'begin': 0x1E00, 'end': 0x1EFF }, // Latin Extended Additional
  19156. { 'begin': 0x1F00, 'end': 0x1FFF }, // Greek Extended
  19157. { 'begin': 0x2000, 'end': 0x206F }, // General Punctuation
  19158. { 'begin': 0x2070, 'end': 0x209F }, // Superscripts And Subscripts
  19159. { 'begin': 0x20A0, 'end': 0x20CF }, // Currency Symbol
  19160. { 'begin': 0x20D0, 'end': 0x20FF }, // Combining Diacritical Marks For Symbols
  19161. { 'begin': 0x2100, 'end': 0x214F }, // Letterlike Symbols
  19162. { 'begin': 0x2150, 'end': 0x218F }, // Number Forms
  19163. { 'begin': 0x2190, 'end': 0x21FF }, // Arrows
  19164. { 'begin': 0x2200, 'end': 0x22FF }, // Mathematical Operators
  19165. { 'begin': 0x2300, 'end': 0x23FF }, // Miscellaneous Technical
  19166. { 'begin': 0x2400, 'end': 0x243F }, // Control Pictures
  19167. { 'begin': 0x2440, 'end': 0x245F }, // Optical Character Recognition
  19168. { 'begin': 0x2460, 'end': 0x24FF }, // Enclosed Alphanumerics
  19169. { 'begin': 0x2500, 'end': 0x257F }, // Box Drawing
  19170. { 'begin': 0x2580, 'end': 0x259F }, // Block Elements
  19171. { 'begin': 0x25A0, 'end': 0x25FF }, // Geometric Shapes
  19172. { 'begin': 0x2600, 'end': 0x26FF }, // Miscellaneous Symbols
  19173. { 'begin': 0x2700, 'end': 0x27BF }, // Dingbats
  19174. { 'begin': 0x3000, 'end': 0x303F }, // CJK Symbols And Punctuation
  19175. { 'begin': 0x3040, 'end': 0x309F }, // Hiragana
  19176. { 'begin': 0x30A0, 'end': 0x30FF }, // Katakana
  19177. { 'begin': 0x3100, 'end': 0x312F }, // Bopomofo
  19178. { 'begin': 0x3130, 'end': 0x318F }, // Hangul Compatibility Jamo
  19179. { 'begin': 0xA840, 'end': 0xA87F }, // Phags-pa
  19180. { 'begin': 0x3200, 'end': 0x32FF }, // Enclosed CJK Letters And Months
  19181. { 'begin': 0x3300, 'end': 0x33FF }, // CJK Compatibility
  19182. { 'begin': 0xAC00, 'end': 0xD7AF }, // Hangul Syllables
  19183. { 'begin': 0xD800, 'end': 0xDFFF }, // Non-Plane 0 *
  19184. { 'begin': 0x10900, 'end': 0x1091F }, // Phoenicia
  19185. { 'begin': 0x4E00, 'end': 0x9FFF }, // CJK Unified Ideographs
  19186. { 'begin': 0xE000, 'end': 0xF8FF }, // Private Use Area (plane 0)
  19187. { 'begin': 0x31C0, 'end': 0x31EF }, // CJK Strokes
  19188. { 'begin': 0xFB00, 'end': 0xFB4F }, // Alphabetic Presentation Forms
  19189. { 'begin': 0xFB50, 'end': 0xFDFF }, // Arabic Presentation Forms-A
  19190. { 'begin': 0xFE20, 'end': 0xFE2F }, // Combining Half Marks
  19191. { 'begin': 0xFE10, 'end': 0xFE1F }, // Vertical Forms
  19192. { 'begin': 0xFE50, 'end': 0xFE6F }, // Small Form Variants
  19193. { 'begin': 0xFE70, 'end': 0xFEFF }, // Arabic Presentation Forms-B
  19194. { 'begin': 0xFF00, 'end': 0xFFEF }, // Halfwidth And Fullwidth Forms
  19195. { 'begin': 0xFFF0, 'end': 0xFFFF }, // Specials
  19196. { 'begin': 0x0F00, 'end': 0x0FFF }, // Tibetan
  19197. { 'begin': 0x0700, 'end': 0x074F }, // Syriac
  19198. { 'begin': 0x0780, 'end': 0x07BF }, // Thaana
  19199. { 'begin': 0x0D80, 'end': 0x0DFF }, // Sinhala
  19200. { 'begin': 0x1000, 'end': 0x109F }, // Myanmar
  19201. { 'begin': 0x1200, 'end': 0x137F }, // Ethiopic
  19202. { 'begin': 0x13A0, 'end': 0x13FF }, // Cherokee
  19203. { 'begin': 0x1400, 'end': 0x167F }, // Unified Canadian Aboriginal Syllabics
  19204. { 'begin': 0x1680, 'end': 0x169F }, // Ogham
  19205. { 'begin': 0x16A0, 'end': 0x16FF }, // Runic
  19206. { 'begin': 0x1780, 'end': 0x17FF }, // Khmer
  19207. { 'begin': 0x1800, 'end': 0x18AF }, // Mongolian
  19208. { 'begin': 0x2800, 'end': 0x28FF }, // Braille Patterns
  19209. { 'begin': 0xA000, 'end': 0xA48F }, // Yi Syllables
  19210. { 'begin': 0x1700, 'end': 0x171F }, // Tagalog
  19211. { 'begin': 0x10300, 'end': 0x1032F }, // Old Italic
  19212. { 'begin': 0x10330, 'end': 0x1034F }, // Gothic
  19213. { 'begin': 0x10400, 'end': 0x1044F }, // Deseret
  19214. { 'begin': 0x1D000, 'end': 0x1D0FF }, // Byzantine Musical Symbols
  19215. { 'begin': 0x1D400, 'end': 0x1D7FF }, // Mathematical Alphanumeric Symbols
  19216. { 'begin': 0xFF000, 'end': 0xFFFFD }, // Private Use (plane 15)
  19217. { 'begin': 0xFE00, 'end': 0xFE0F }, // Variation Selectors
  19218. { 'begin': 0xE0000, 'end': 0xE007F }, // Tags
  19219. { 'begin': 0x1900, 'end': 0x194F }, // Limbu
  19220. { 'begin': 0x1950, 'end': 0x197F }, // Tai Le
  19221. { 'begin': 0x1980, 'end': 0x19DF }, // New Tai Lue
  19222. { 'begin': 0x1A00, 'end': 0x1A1F }, // Buginese
  19223. { 'begin': 0x2C00, 'end': 0x2C5F }, // Glagolitic
  19224. { 'begin': 0x2D30, 'end': 0x2D7F }, // Tifinagh
  19225. { 'begin': 0x4DC0, 'end': 0x4DFF }, // Yijing Hexagram Symbols
  19226. { 'begin': 0xA800, 'end': 0xA82F }, // Syloti Nagri
  19227. { 'begin': 0x10000, 'end': 0x1007F }, // Linear B Syllabary
  19228. { 'begin': 0x10140, 'end': 0x1018F }, // Ancient Greek Numbers
  19229. { 'begin': 0x10380, 'end': 0x1039F }, // Ugaritic
  19230. { 'begin': 0x103A0, 'end': 0x103DF }, // Old Persian
  19231. { 'begin': 0x10450, 'end': 0x1047F }, // Shavian
  19232. { 'begin': 0x10480, 'end': 0x104AF }, // Osmanya
  19233. { 'begin': 0x10800, 'end': 0x1083F }, // Cypriot Syllabary
  19234. { 'begin': 0x10A00, 'end': 0x10A5F }, // Kharoshthi
  19235. { 'begin': 0x1D300, 'end': 0x1D35F }, // Tai Xuan Jing Symbols
  19236. { 'begin': 0x12000, 'end': 0x123FF }, // Cuneiform
  19237. { 'begin': 0x1D360, 'end': 0x1D37F }, // Counting Rod Numerals
  19238. { 'begin': 0x1B80, 'end': 0x1BBF }, // Sundanese
  19239. { 'begin': 0x1C00, 'end': 0x1C4F }, // Lepcha
  19240. { 'begin': 0x1C50, 'end': 0x1C7F }, // Ol Chiki
  19241. { 'begin': 0xA880, 'end': 0xA8DF }, // Saurashtra
  19242. { 'begin': 0xA900, 'end': 0xA92F }, // Kayah Li
  19243. { 'begin': 0xA930, 'end': 0xA95F }, // Rejang
  19244. { 'begin': 0xAA00, 'end': 0xAA5F }, // Cham
  19245. { 'begin': 0x10190, 'end': 0x101CF }, // Ancient Symbols
  19246. { 'begin': 0x101D0, 'end': 0x101FF }, // Phaistos Disc
  19247. { 'begin': 0x102A0, 'end': 0x102DF }, // Carian
  19248. { 'begin': 0x1F030, 'end': 0x1F09F } // Domino Tiles
  19249. ];
  19250. var MacStandardGlyphOrdering = [
  19251. '.notdef', '.null', 'nonmarkingreturn', 'space', 'exclam', 'quotedbl',
  19252. 'numbersign', 'dollar', 'percent', 'ampersand', 'quotesingle', 'parenleft',
  19253. 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash',
  19254. 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
  19255. 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', 'at',
  19256. 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
  19257. 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft',
  19258. 'backslash', 'bracketright', 'asciicircum', 'underscore', 'grave', 'a', 'b',
  19259. 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
  19260. 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright',
  19261. 'asciitilde', 'Adieresis', 'Aring', 'Ccedilla', 'Eacute', 'Ntilde',
  19262. 'Odieresis', 'Udieresis', 'aacute', 'agrave', 'acircumflex', 'adieresis',
  19263. 'atilde', 'aring', 'ccedilla', 'eacute', 'egrave', 'ecircumflex', 'edieresis',
  19264. 'iacute', 'igrave', 'icircumflex', 'idieresis', 'ntilde', 'oacute', 'ograve',
  19265. 'ocircumflex', 'odieresis', 'otilde', 'uacute', 'ugrave', 'ucircumflex',
  19266. 'udieresis', 'dagger', 'degree', 'cent', 'sterling', 'section', 'bullet',
  19267. 'paragraph', 'germandbls', 'registered', 'copyright', 'trademark', 'acute',
  19268. 'dieresis', 'notequal', 'AE', 'Oslash', 'infinity', 'plusminus', 'lessequal',
  19269. 'greaterequal', 'yen', 'mu', 'partialdiff', 'summation', 'product', 'pi',
  19270. 'integral', 'ordfeminine', 'ordmasculine', 'Omega', 'ae', 'oslash',
  19271. 'questiondown', 'exclamdown', 'logicalnot', 'radical', 'florin',
  19272. 'approxequal', 'Delta', 'guillemotleft', 'guillemotright', 'ellipsis',
  19273. 'nonbreakingspace', 'Agrave', 'Atilde', 'Otilde', 'OE', 'oe', 'endash',
  19274. 'emdash', 'quotedblleft', 'quotedblright', 'quoteleft', 'quoteright',
  19275. 'divide', 'lozenge', 'ydieresis', 'Ydieresis', 'fraction', 'currency',
  19276. 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'daggerdbl', 'periodcentered',
  19277. 'quotesinglbase', 'quotedblbase', 'perthousand', 'Acircumflex',
  19278. 'Ecircumflex', 'Aacute', 'Edieresis', 'Egrave', 'Iacute', 'Icircumflex',
  19279. 'Idieresis', 'Igrave', 'Oacute', 'Ocircumflex', 'apple', 'Ograve', 'Uacute',
  19280. 'Ucircumflex', 'Ugrave', 'dotlessi', 'circumflex', 'tilde', 'macron',
  19281. 'breve', 'dotaccent', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron',
  19282. 'Lslash', 'lslash', 'Scaron', 'scaron', 'Zcaron', 'zcaron', 'brokenbar',
  19283. 'Eth', 'eth', 'Yacute', 'yacute', 'Thorn', 'thorn', 'minus', 'multiply',
  19284. 'onesuperior', 'twosuperior', 'threesuperior', 'onehalf', 'onequarter',
  19285. 'threequarters', 'franc', 'Gbreve', 'gbreve', 'Idotaccent', 'Scedilla',
  19286. 'scedilla', 'Cacute', 'cacute', 'Ccaron', 'ccaron', 'dcroat'];
  19287. function getUnicodeRangeFor(value) {
  19288. for (var i = 0, ii = UnicodeRanges.length; i < ii; i++) {
  19289. var range = UnicodeRanges[i];
  19290. if (value >= range.begin && value < range.end) {
  19291. return i;
  19292. }
  19293. }
  19294. return -1;
  19295. }
  19296. function isRTLRangeFor(value) {
  19297. var range = UnicodeRanges[13];
  19298. if (value >= range.begin && value < range.end) {
  19299. return true;
  19300. }
  19301. range = UnicodeRanges[11];
  19302. if (value >= range.begin && value < range.end) {
  19303. return true;
  19304. }
  19305. return false;
  19306. }
  19307. // The normalization table is obtained by filtering the Unicode characters
  19308. // database with <compat> entries.
  19309. var NormalizedUnicodes = {
  19310. '\u00A8': '\u0020\u0308',
  19311. '\u00AF': '\u0020\u0304',
  19312. '\u00B4': '\u0020\u0301',
  19313. '\u00B5': '\u03BC',
  19314. '\u00B8': '\u0020\u0327',
  19315. '\u0132': '\u0049\u004A',
  19316. '\u0133': '\u0069\u006A',
  19317. '\u013F': '\u004C\u00B7',
  19318. '\u0140': '\u006C\u00B7',
  19319. '\u0149': '\u02BC\u006E',
  19320. '\u017F': '\u0073',
  19321. '\u01C4': '\u0044\u017D',
  19322. '\u01C5': '\u0044\u017E',
  19323. '\u01C6': '\u0064\u017E',
  19324. '\u01C7': '\u004C\u004A',
  19325. '\u01C8': '\u004C\u006A',
  19326. '\u01C9': '\u006C\u006A',
  19327. '\u01CA': '\u004E\u004A',
  19328. '\u01CB': '\u004E\u006A',
  19329. '\u01CC': '\u006E\u006A',
  19330. '\u01F1': '\u0044\u005A',
  19331. '\u01F2': '\u0044\u007A',
  19332. '\u01F3': '\u0064\u007A',
  19333. '\u02D8': '\u0020\u0306',
  19334. '\u02D9': '\u0020\u0307',
  19335. '\u02DA': '\u0020\u030A',
  19336. '\u02DB': '\u0020\u0328',
  19337. '\u02DC': '\u0020\u0303',
  19338. '\u02DD': '\u0020\u030B',
  19339. '\u037A': '\u0020\u0345',
  19340. '\u0384': '\u0020\u0301',
  19341. '\u03D0': '\u03B2',
  19342. '\u03D1': '\u03B8',
  19343. '\u03D2': '\u03A5',
  19344. '\u03D5': '\u03C6',
  19345. '\u03D6': '\u03C0',
  19346. '\u03F0': '\u03BA',
  19347. '\u03F1': '\u03C1',
  19348. '\u03F2': '\u03C2',
  19349. '\u03F4': '\u0398',
  19350. '\u03F5': '\u03B5',
  19351. '\u03F9': '\u03A3',
  19352. '\u0587': '\u0565\u0582',
  19353. '\u0675': '\u0627\u0674',
  19354. '\u0676': '\u0648\u0674',
  19355. '\u0677': '\u06C7\u0674',
  19356. '\u0678': '\u064A\u0674',
  19357. '\u0E33': '\u0E4D\u0E32',
  19358. '\u0EB3': '\u0ECD\u0EB2',
  19359. '\u0EDC': '\u0EAB\u0E99',
  19360. '\u0EDD': '\u0EAB\u0EA1',
  19361. '\u0F77': '\u0FB2\u0F81',
  19362. '\u0F79': '\u0FB3\u0F81',
  19363. '\u1E9A': '\u0061\u02BE',
  19364. '\u1FBD': '\u0020\u0313',
  19365. '\u1FBF': '\u0020\u0313',
  19366. '\u1FC0': '\u0020\u0342',
  19367. '\u1FFE': '\u0020\u0314',
  19368. '\u2002': '\u0020',
  19369. '\u2003': '\u0020',
  19370. '\u2004': '\u0020',
  19371. '\u2005': '\u0020',
  19372. '\u2006': '\u0020',
  19373. '\u2008': '\u0020',
  19374. '\u2009': '\u0020',
  19375. '\u200A': '\u0020',
  19376. '\u2017': '\u0020\u0333',
  19377. '\u2024': '\u002E',
  19378. '\u2025': '\u002E\u002E',
  19379. '\u2026': '\u002E\u002E\u002E',
  19380. '\u2033': '\u2032\u2032',
  19381. '\u2034': '\u2032\u2032\u2032',
  19382. '\u2036': '\u2035\u2035',
  19383. '\u2037': '\u2035\u2035\u2035',
  19384. '\u203C': '\u0021\u0021',
  19385. '\u203E': '\u0020\u0305',
  19386. '\u2047': '\u003F\u003F',
  19387. '\u2048': '\u003F\u0021',
  19388. '\u2049': '\u0021\u003F',
  19389. '\u2057': '\u2032\u2032\u2032\u2032',
  19390. '\u205F': '\u0020',
  19391. '\u20A8': '\u0052\u0073',
  19392. '\u2100': '\u0061\u002F\u0063',
  19393. '\u2101': '\u0061\u002F\u0073',
  19394. '\u2103': '\u00B0\u0043',
  19395. '\u2105': '\u0063\u002F\u006F',
  19396. '\u2106': '\u0063\u002F\u0075',
  19397. '\u2107': '\u0190',
  19398. '\u2109': '\u00B0\u0046',
  19399. '\u2116': '\u004E\u006F',
  19400. '\u2121': '\u0054\u0045\u004C',
  19401. '\u2135': '\u05D0',
  19402. '\u2136': '\u05D1',
  19403. '\u2137': '\u05D2',
  19404. '\u2138': '\u05D3',
  19405. '\u213B': '\u0046\u0041\u0058',
  19406. '\u2160': '\u0049',
  19407. '\u2161': '\u0049\u0049',
  19408. '\u2162': '\u0049\u0049\u0049',
  19409. '\u2163': '\u0049\u0056',
  19410. '\u2164': '\u0056',
  19411. '\u2165': '\u0056\u0049',
  19412. '\u2166': '\u0056\u0049\u0049',
  19413. '\u2167': '\u0056\u0049\u0049\u0049',
  19414. '\u2168': '\u0049\u0058',
  19415. '\u2169': '\u0058',
  19416. '\u216A': '\u0058\u0049',
  19417. '\u216B': '\u0058\u0049\u0049',
  19418. '\u216C': '\u004C',
  19419. '\u216D': '\u0043',
  19420. '\u216E': '\u0044',
  19421. '\u216F': '\u004D',
  19422. '\u2170': '\u0069',
  19423. '\u2171': '\u0069\u0069',
  19424. '\u2172': '\u0069\u0069\u0069',
  19425. '\u2173': '\u0069\u0076',
  19426. '\u2174': '\u0076',
  19427. '\u2175': '\u0076\u0069',
  19428. '\u2176': '\u0076\u0069\u0069',
  19429. '\u2177': '\u0076\u0069\u0069\u0069',
  19430. '\u2178': '\u0069\u0078',
  19431. '\u2179': '\u0078',
  19432. '\u217A': '\u0078\u0069',
  19433. '\u217B': '\u0078\u0069\u0069',
  19434. '\u217C': '\u006C',
  19435. '\u217D': '\u0063',
  19436. '\u217E': '\u0064',
  19437. '\u217F': '\u006D',
  19438. '\u222C': '\u222B\u222B',
  19439. '\u222D': '\u222B\u222B\u222B',
  19440. '\u222F': '\u222E\u222E',
  19441. '\u2230': '\u222E\u222E\u222E',
  19442. '\u2474': '\u0028\u0031\u0029',
  19443. '\u2475': '\u0028\u0032\u0029',
  19444. '\u2476': '\u0028\u0033\u0029',
  19445. '\u2477': '\u0028\u0034\u0029',
  19446. '\u2478': '\u0028\u0035\u0029',
  19447. '\u2479': '\u0028\u0036\u0029',
  19448. '\u247A': '\u0028\u0037\u0029',
  19449. '\u247B': '\u0028\u0038\u0029',
  19450. '\u247C': '\u0028\u0039\u0029',
  19451. '\u247D': '\u0028\u0031\u0030\u0029',
  19452. '\u247E': '\u0028\u0031\u0031\u0029',
  19453. '\u247F': '\u0028\u0031\u0032\u0029',
  19454. '\u2480': '\u0028\u0031\u0033\u0029',
  19455. '\u2481': '\u0028\u0031\u0034\u0029',
  19456. '\u2482': '\u0028\u0031\u0035\u0029',
  19457. '\u2483': '\u0028\u0031\u0036\u0029',
  19458. '\u2484': '\u0028\u0031\u0037\u0029',
  19459. '\u2485': '\u0028\u0031\u0038\u0029',
  19460. '\u2486': '\u0028\u0031\u0039\u0029',
  19461. '\u2487': '\u0028\u0032\u0030\u0029',
  19462. '\u2488': '\u0031\u002E',
  19463. '\u2489': '\u0032\u002E',
  19464. '\u248A': '\u0033\u002E',
  19465. '\u248B': '\u0034\u002E',
  19466. '\u248C': '\u0035\u002E',
  19467. '\u248D': '\u0036\u002E',
  19468. '\u248E': '\u0037\u002E',
  19469. '\u248F': '\u0038\u002E',
  19470. '\u2490': '\u0039\u002E',
  19471. '\u2491': '\u0031\u0030\u002E',
  19472. '\u2492': '\u0031\u0031\u002E',
  19473. '\u2493': '\u0031\u0032\u002E',
  19474. '\u2494': '\u0031\u0033\u002E',
  19475. '\u2495': '\u0031\u0034\u002E',
  19476. '\u2496': '\u0031\u0035\u002E',
  19477. '\u2497': '\u0031\u0036\u002E',
  19478. '\u2498': '\u0031\u0037\u002E',
  19479. '\u2499': '\u0031\u0038\u002E',
  19480. '\u249A': '\u0031\u0039\u002E',
  19481. '\u249B': '\u0032\u0030\u002E',
  19482. '\u249C': '\u0028\u0061\u0029',
  19483. '\u249D': '\u0028\u0062\u0029',
  19484. '\u249E': '\u0028\u0063\u0029',
  19485. '\u249F': '\u0028\u0064\u0029',
  19486. '\u24A0': '\u0028\u0065\u0029',
  19487. '\u24A1': '\u0028\u0066\u0029',
  19488. '\u24A2': '\u0028\u0067\u0029',
  19489. '\u24A3': '\u0028\u0068\u0029',
  19490. '\u24A4': '\u0028\u0069\u0029',
  19491. '\u24A5': '\u0028\u006A\u0029',
  19492. '\u24A6': '\u0028\u006B\u0029',
  19493. '\u24A7': '\u0028\u006C\u0029',
  19494. '\u24A8': '\u0028\u006D\u0029',
  19495. '\u24A9': '\u0028\u006E\u0029',
  19496. '\u24AA': '\u0028\u006F\u0029',
  19497. '\u24AB': '\u0028\u0070\u0029',
  19498. '\u24AC': '\u0028\u0071\u0029',
  19499. '\u24AD': '\u0028\u0072\u0029',
  19500. '\u24AE': '\u0028\u0073\u0029',
  19501. '\u24AF': '\u0028\u0074\u0029',
  19502. '\u24B0': '\u0028\u0075\u0029',
  19503. '\u24B1': '\u0028\u0076\u0029',
  19504. '\u24B2': '\u0028\u0077\u0029',
  19505. '\u24B3': '\u0028\u0078\u0029',
  19506. '\u24B4': '\u0028\u0079\u0029',
  19507. '\u24B5': '\u0028\u007A\u0029',
  19508. '\u2A0C': '\u222B\u222B\u222B\u222B',
  19509. '\u2A74': '\u003A\u003A\u003D',
  19510. '\u2A75': '\u003D\u003D',
  19511. '\u2A76': '\u003D\u003D\u003D',
  19512. '\u2E9F': '\u6BCD',
  19513. '\u2EF3': '\u9F9F',
  19514. '\u2F00': '\u4E00',
  19515. '\u2F01': '\u4E28',
  19516. '\u2F02': '\u4E36',
  19517. '\u2F03': '\u4E3F',
  19518. '\u2F04': '\u4E59',
  19519. '\u2F05': '\u4E85',
  19520. '\u2F06': '\u4E8C',
  19521. '\u2F07': '\u4EA0',
  19522. '\u2F08': '\u4EBA',
  19523. '\u2F09': '\u513F',
  19524. '\u2F0A': '\u5165',
  19525. '\u2F0B': '\u516B',
  19526. '\u2F0C': '\u5182',
  19527. '\u2F0D': '\u5196',
  19528. '\u2F0E': '\u51AB',
  19529. '\u2F0F': '\u51E0',
  19530. '\u2F10': '\u51F5',
  19531. '\u2F11': '\u5200',
  19532. '\u2F12': '\u529B',
  19533. '\u2F13': '\u52F9',
  19534. '\u2F14': '\u5315',
  19535. '\u2F15': '\u531A',
  19536. '\u2F16': '\u5338',
  19537. '\u2F17': '\u5341',
  19538. '\u2F18': '\u535C',
  19539. '\u2F19': '\u5369',
  19540. '\u2F1A': '\u5382',
  19541. '\u2F1B': '\u53B6',
  19542. '\u2F1C': '\u53C8',
  19543. '\u2F1D': '\u53E3',
  19544. '\u2F1E': '\u56D7',
  19545. '\u2F1F': '\u571F',
  19546. '\u2F20': '\u58EB',
  19547. '\u2F21': '\u5902',
  19548. '\u2F22': '\u590A',
  19549. '\u2F23': '\u5915',
  19550. '\u2F24': '\u5927',
  19551. '\u2F25': '\u5973',
  19552. '\u2F26': '\u5B50',
  19553. '\u2F27': '\u5B80',
  19554. '\u2F28': '\u5BF8',
  19555. '\u2F29': '\u5C0F',
  19556. '\u2F2A': '\u5C22',
  19557. '\u2F2B': '\u5C38',
  19558. '\u2F2C': '\u5C6E',
  19559. '\u2F2D': '\u5C71',
  19560. '\u2F2E': '\u5DDB',
  19561. '\u2F2F': '\u5DE5',
  19562. '\u2F30': '\u5DF1',
  19563. '\u2F31': '\u5DFE',
  19564. '\u2F32': '\u5E72',
  19565. '\u2F33': '\u5E7A',
  19566. '\u2F34': '\u5E7F',
  19567. '\u2F35': '\u5EF4',
  19568. '\u2F36': '\u5EFE',
  19569. '\u2F37': '\u5F0B',
  19570. '\u2F38': '\u5F13',
  19571. '\u2F39': '\u5F50',
  19572. '\u2F3A': '\u5F61',
  19573. '\u2F3B': '\u5F73',
  19574. '\u2F3C': '\u5FC3',
  19575. '\u2F3D': '\u6208',
  19576. '\u2F3E': '\u6236',
  19577. '\u2F3F': '\u624B',
  19578. '\u2F40': '\u652F',
  19579. '\u2F41': '\u6534',
  19580. '\u2F42': '\u6587',
  19581. '\u2F43': '\u6597',
  19582. '\u2F44': '\u65A4',
  19583. '\u2F45': '\u65B9',
  19584. '\u2F46': '\u65E0',
  19585. '\u2F47': '\u65E5',
  19586. '\u2F48': '\u66F0',
  19587. '\u2F49': '\u6708',
  19588. '\u2F4A': '\u6728',
  19589. '\u2F4B': '\u6B20',
  19590. '\u2F4C': '\u6B62',
  19591. '\u2F4D': '\u6B79',
  19592. '\u2F4E': '\u6BB3',
  19593. '\u2F4F': '\u6BCB',
  19594. '\u2F50': '\u6BD4',
  19595. '\u2F51': '\u6BDB',
  19596. '\u2F52': '\u6C0F',
  19597. '\u2F53': '\u6C14',
  19598. '\u2F54': '\u6C34',
  19599. '\u2F55': '\u706B',
  19600. '\u2F56': '\u722A',
  19601. '\u2F57': '\u7236',
  19602. '\u2F58': '\u723B',
  19603. '\u2F59': '\u723F',
  19604. '\u2F5A': '\u7247',
  19605. '\u2F5B': '\u7259',
  19606. '\u2F5C': '\u725B',
  19607. '\u2F5D': '\u72AC',
  19608. '\u2F5E': '\u7384',
  19609. '\u2F5F': '\u7389',
  19610. '\u2F60': '\u74DC',
  19611. '\u2F61': '\u74E6',
  19612. '\u2F62': '\u7518',
  19613. '\u2F63': '\u751F',
  19614. '\u2F64': '\u7528',
  19615. '\u2F65': '\u7530',
  19616. '\u2F66': '\u758B',
  19617. '\u2F67': '\u7592',
  19618. '\u2F68': '\u7676',
  19619. '\u2F69': '\u767D',
  19620. '\u2F6A': '\u76AE',
  19621. '\u2F6B': '\u76BF',
  19622. '\u2F6C': '\u76EE',
  19623. '\u2F6D': '\u77DB',
  19624. '\u2F6E': '\u77E2',
  19625. '\u2F6F': '\u77F3',
  19626. '\u2F70': '\u793A',
  19627. '\u2F71': '\u79B8',
  19628. '\u2F72': '\u79BE',
  19629. '\u2F73': '\u7A74',
  19630. '\u2F74': '\u7ACB',
  19631. '\u2F75': '\u7AF9',
  19632. '\u2F76': '\u7C73',
  19633. '\u2F77': '\u7CF8',
  19634. '\u2F78': '\u7F36',
  19635. '\u2F79': '\u7F51',
  19636. '\u2F7A': '\u7F8A',
  19637. '\u2F7B': '\u7FBD',
  19638. '\u2F7C': '\u8001',
  19639. '\u2F7D': '\u800C',
  19640. '\u2F7E': '\u8012',
  19641. '\u2F7F': '\u8033',
  19642. '\u2F80': '\u807F',
  19643. '\u2F81': '\u8089',
  19644. '\u2F82': '\u81E3',
  19645. '\u2F83': '\u81EA',
  19646. '\u2F84': '\u81F3',
  19647. '\u2F85': '\u81FC',
  19648. '\u2F86': '\u820C',
  19649. '\u2F87': '\u821B',
  19650. '\u2F88': '\u821F',
  19651. '\u2F89': '\u826E',
  19652. '\u2F8A': '\u8272',
  19653. '\u2F8B': '\u8278',
  19654. '\u2F8C': '\u864D',
  19655. '\u2F8D': '\u866B',
  19656. '\u2F8E': '\u8840',
  19657. '\u2F8F': '\u884C',
  19658. '\u2F90': '\u8863',
  19659. '\u2F91': '\u897E',
  19660. '\u2F92': '\u898B',
  19661. '\u2F93': '\u89D2',
  19662. '\u2F94': '\u8A00',
  19663. '\u2F95': '\u8C37',
  19664. '\u2F96': '\u8C46',
  19665. '\u2F97': '\u8C55',
  19666. '\u2F98': '\u8C78',
  19667. '\u2F99': '\u8C9D',
  19668. '\u2F9A': '\u8D64',
  19669. '\u2F9B': '\u8D70',
  19670. '\u2F9C': '\u8DB3',
  19671. '\u2F9D': '\u8EAB',
  19672. '\u2F9E': '\u8ECA',
  19673. '\u2F9F': '\u8F9B',
  19674. '\u2FA0': '\u8FB0',
  19675. '\u2FA1': '\u8FB5',
  19676. '\u2FA2': '\u9091',
  19677. '\u2FA3': '\u9149',
  19678. '\u2FA4': '\u91C6',
  19679. '\u2FA5': '\u91CC',
  19680. '\u2FA6': '\u91D1',
  19681. '\u2FA7': '\u9577',
  19682. '\u2FA8': '\u9580',
  19683. '\u2FA9': '\u961C',
  19684. '\u2FAA': '\u96B6',
  19685. '\u2FAB': '\u96B9',
  19686. '\u2FAC': '\u96E8',
  19687. '\u2FAD': '\u9751',
  19688. '\u2FAE': '\u975E',
  19689. '\u2FAF': '\u9762',
  19690. '\u2FB0': '\u9769',
  19691. '\u2FB1': '\u97CB',
  19692. '\u2FB2': '\u97ED',
  19693. '\u2FB3': '\u97F3',
  19694. '\u2FB4': '\u9801',
  19695. '\u2FB5': '\u98A8',
  19696. '\u2FB6': '\u98DB',
  19697. '\u2FB7': '\u98DF',
  19698. '\u2FB8': '\u9996',
  19699. '\u2FB9': '\u9999',
  19700. '\u2FBA': '\u99AC',
  19701. '\u2FBB': '\u9AA8',
  19702. '\u2FBC': '\u9AD8',
  19703. '\u2FBD': '\u9ADF',
  19704. '\u2FBE': '\u9B25',
  19705. '\u2FBF': '\u9B2F',
  19706. '\u2FC0': '\u9B32',
  19707. '\u2FC1': '\u9B3C',
  19708. '\u2FC2': '\u9B5A',
  19709. '\u2FC3': '\u9CE5',
  19710. '\u2FC4': '\u9E75',
  19711. '\u2FC5': '\u9E7F',
  19712. '\u2FC6': '\u9EA5',
  19713. '\u2FC7': '\u9EBB',
  19714. '\u2FC8': '\u9EC3',
  19715. '\u2FC9': '\u9ECD',
  19716. '\u2FCA': '\u9ED1',
  19717. '\u2FCB': '\u9EF9',
  19718. '\u2FCC': '\u9EFD',
  19719. '\u2FCD': '\u9F0E',
  19720. '\u2FCE': '\u9F13',
  19721. '\u2FCF': '\u9F20',
  19722. '\u2FD0': '\u9F3B',
  19723. '\u2FD1': '\u9F4A',
  19724. '\u2FD2': '\u9F52',
  19725. '\u2FD3': '\u9F8D',
  19726. '\u2FD4': '\u9F9C',
  19727. '\u2FD5': '\u9FA0',
  19728. '\u3036': '\u3012',
  19729. '\u3038': '\u5341',
  19730. '\u3039': '\u5344',
  19731. '\u303A': '\u5345',
  19732. '\u309B': '\u0020\u3099',
  19733. '\u309C': '\u0020\u309A',
  19734. '\u3131': '\u1100',
  19735. '\u3132': '\u1101',
  19736. '\u3133': '\u11AA',
  19737. '\u3134': '\u1102',
  19738. '\u3135': '\u11AC',
  19739. '\u3136': '\u11AD',
  19740. '\u3137': '\u1103',
  19741. '\u3138': '\u1104',
  19742. '\u3139': '\u1105',
  19743. '\u313A': '\u11B0',
  19744. '\u313B': '\u11B1',
  19745. '\u313C': '\u11B2',
  19746. '\u313D': '\u11B3',
  19747. '\u313E': '\u11B4',
  19748. '\u313F': '\u11B5',
  19749. '\u3140': '\u111A',
  19750. '\u3141': '\u1106',
  19751. '\u3142': '\u1107',
  19752. '\u3143': '\u1108',
  19753. '\u3144': '\u1121',
  19754. '\u3145': '\u1109',
  19755. '\u3146': '\u110A',
  19756. '\u3147': '\u110B',
  19757. '\u3148': '\u110C',
  19758. '\u3149': '\u110D',
  19759. '\u314A': '\u110E',
  19760. '\u314B': '\u110F',
  19761. '\u314C': '\u1110',
  19762. '\u314D': '\u1111',
  19763. '\u314E': '\u1112',
  19764. '\u314F': '\u1161',
  19765. '\u3150': '\u1162',
  19766. '\u3151': '\u1163',
  19767. '\u3152': '\u1164',
  19768. '\u3153': '\u1165',
  19769. '\u3154': '\u1166',
  19770. '\u3155': '\u1167',
  19771. '\u3156': '\u1168',
  19772. '\u3157': '\u1169',
  19773. '\u3158': '\u116A',
  19774. '\u3159': '\u116B',
  19775. '\u315A': '\u116C',
  19776. '\u315B': '\u116D',
  19777. '\u315C': '\u116E',
  19778. '\u315D': '\u116F',
  19779. '\u315E': '\u1170',
  19780. '\u315F': '\u1171',
  19781. '\u3160': '\u1172',
  19782. '\u3161': '\u1173',
  19783. '\u3162': '\u1174',
  19784. '\u3163': '\u1175',
  19785. '\u3164': '\u1160',
  19786. '\u3165': '\u1114',
  19787. '\u3166': '\u1115',
  19788. '\u3167': '\u11C7',
  19789. '\u3168': '\u11C8',
  19790. '\u3169': '\u11CC',
  19791. '\u316A': '\u11CE',
  19792. '\u316B': '\u11D3',
  19793. '\u316C': '\u11D7',
  19794. '\u316D': '\u11D9',
  19795. '\u316E': '\u111C',
  19796. '\u316F': '\u11DD',
  19797. '\u3170': '\u11DF',
  19798. '\u3171': '\u111D',
  19799. '\u3172': '\u111E',
  19800. '\u3173': '\u1120',
  19801. '\u3174': '\u1122',
  19802. '\u3175': '\u1123',
  19803. '\u3176': '\u1127',
  19804. '\u3177': '\u1129',
  19805. '\u3178': '\u112B',
  19806. '\u3179': '\u112C',
  19807. '\u317A': '\u112D',
  19808. '\u317B': '\u112E',
  19809. '\u317C': '\u112F',
  19810. '\u317D': '\u1132',
  19811. '\u317E': '\u1136',
  19812. '\u317F': '\u1140',
  19813. '\u3180': '\u1147',
  19814. '\u3181': '\u114C',
  19815. '\u3182': '\u11F1',
  19816. '\u3183': '\u11F2',
  19817. '\u3184': '\u1157',
  19818. '\u3185': '\u1158',
  19819. '\u3186': '\u1159',
  19820. '\u3187': '\u1184',
  19821. '\u3188': '\u1185',
  19822. '\u3189': '\u1188',
  19823. '\u318A': '\u1191',
  19824. '\u318B': '\u1192',
  19825. '\u318C': '\u1194',
  19826. '\u318D': '\u119E',
  19827. '\u318E': '\u11A1',
  19828. '\u3200': '\u0028\u1100\u0029',
  19829. '\u3201': '\u0028\u1102\u0029',
  19830. '\u3202': '\u0028\u1103\u0029',
  19831. '\u3203': '\u0028\u1105\u0029',
  19832. '\u3204': '\u0028\u1106\u0029',
  19833. '\u3205': '\u0028\u1107\u0029',
  19834. '\u3206': '\u0028\u1109\u0029',
  19835. '\u3207': '\u0028\u110B\u0029',
  19836. '\u3208': '\u0028\u110C\u0029',
  19837. '\u3209': '\u0028\u110E\u0029',
  19838. '\u320A': '\u0028\u110F\u0029',
  19839. '\u320B': '\u0028\u1110\u0029',
  19840. '\u320C': '\u0028\u1111\u0029',
  19841. '\u320D': '\u0028\u1112\u0029',
  19842. '\u320E': '\u0028\u1100\u1161\u0029',
  19843. '\u320F': '\u0028\u1102\u1161\u0029',
  19844. '\u3210': '\u0028\u1103\u1161\u0029',
  19845. '\u3211': '\u0028\u1105\u1161\u0029',
  19846. '\u3212': '\u0028\u1106\u1161\u0029',
  19847. '\u3213': '\u0028\u1107\u1161\u0029',
  19848. '\u3214': '\u0028\u1109\u1161\u0029',
  19849. '\u3215': '\u0028\u110B\u1161\u0029',
  19850. '\u3216': '\u0028\u110C\u1161\u0029',
  19851. '\u3217': '\u0028\u110E\u1161\u0029',
  19852. '\u3218': '\u0028\u110F\u1161\u0029',
  19853. '\u3219': '\u0028\u1110\u1161\u0029',
  19854. '\u321A': '\u0028\u1111\u1161\u0029',
  19855. '\u321B': '\u0028\u1112\u1161\u0029',
  19856. '\u321C': '\u0028\u110C\u116E\u0029',
  19857. '\u321D': '\u0028\u110B\u1169\u110C\u1165\u11AB\u0029',
  19858. '\u321E': '\u0028\u110B\u1169\u1112\u116E\u0029',
  19859. '\u3220': '\u0028\u4E00\u0029',
  19860. '\u3221': '\u0028\u4E8C\u0029',
  19861. '\u3222': '\u0028\u4E09\u0029',
  19862. '\u3223': '\u0028\u56DB\u0029',
  19863. '\u3224': '\u0028\u4E94\u0029',
  19864. '\u3225': '\u0028\u516D\u0029',
  19865. '\u3226': '\u0028\u4E03\u0029',
  19866. '\u3227': '\u0028\u516B\u0029',
  19867. '\u3228': '\u0028\u4E5D\u0029',
  19868. '\u3229': '\u0028\u5341\u0029',
  19869. '\u322A': '\u0028\u6708\u0029',
  19870. '\u322B': '\u0028\u706B\u0029',
  19871. '\u322C': '\u0028\u6C34\u0029',
  19872. '\u322D': '\u0028\u6728\u0029',
  19873. '\u322E': '\u0028\u91D1\u0029',
  19874. '\u322F': '\u0028\u571F\u0029',
  19875. '\u3230': '\u0028\u65E5\u0029',
  19876. '\u3231': '\u0028\u682A\u0029',
  19877. '\u3232': '\u0028\u6709\u0029',
  19878. '\u3233': '\u0028\u793E\u0029',
  19879. '\u3234': '\u0028\u540D\u0029',
  19880. '\u3235': '\u0028\u7279\u0029',
  19881. '\u3236': '\u0028\u8CA1\u0029',
  19882. '\u3237': '\u0028\u795D\u0029',
  19883. '\u3238': '\u0028\u52B4\u0029',
  19884. '\u3239': '\u0028\u4EE3\u0029',
  19885. '\u323A': '\u0028\u547C\u0029',
  19886. '\u323B': '\u0028\u5B66\u0029',
  19887. '\u323C': '\u0028\u76E3\u0029',
  19888. '\u323D': '\u0028\u4F01\u0029',
  19889. '\u323E': '\u0028\u8CC7\u0029',
  19890. '\u323F': '\u0028\u5354\u0029',
  19891. '\u3240': '\u0028\u796D\u0029',
  19892. '\u3241': '\u0028\u4F11\u0029',
  19893. '\u3242': '\u0028\u81EA\u0029',
  19894. '\u3243': '\u0028\u81F3\u0029',
  19895. '\u32C0': '\u0031\u6708',
  19896. '\u32C1': '\u0032\u6708',
  19897. '\u32C2': '\u0033\u6708',
  19898. '\u32C3': '\u0034\u6708',
  19899. '\u32C4': '\u0035\u6708',
  19900. '\u32C5': '\u0036\u6708',
  19901. '\u32C6': '\u0037\u6708',
  19902. '\u32C7': '\u0038\u6708',
  19903. '\u32C8': '\u0039\u6708',
  19904. '\u32C9': '\u0031\u0030\u6708',
  19905. '\u32CA': '\u0031\u0031\u6708',
  19906. '\u32CB': '\u0031\u0032\u6708',
  19907. '\u3358': '\u0030\u70B9',
  19908. '\u3359': '\u0031\u70B9',
  19909. '\u335A': '\u0032\u70B9',
  19910. '\u335B': '\u0033\u70B9',
  19911. '\u335C': '\u0034\u70B9',
  19912. '\u335D': '\u0035\u70B9',
  19913. '\u335E': '\u0036\u70B9',
  19914. '\u335F': '\u0037\u70B9',
  19915. '\u3360': '\u0038\u70B9',
  19916. '\u3361': '\u0039\u70B9',
  19917. '\u3362': '\u0031\u0030\u70B9',
  19918. '\u3363': '\u0031\u0031\u70B9',
  19919. '\u3364': '\u0031\u0032\u70B9',
  19920. '\u3365': '\u0031\u0033\u70B9',
  19921. '\u3366': '\u0031\u0034\u70B9',
  19922. '\u3367': '\u0031\u0035\u70B9',
  19923. '\u3368': '\u0031\u0036\u70B9',
  19924. '\u3369': '\u0031\u0037\u70B9',
  19925. '\u336A': '\u0031\u0038\u70B9',
  19926. '\u336B': '\u0031\u0039\u70B9',
  19927. '\u336C': '\u0032\u0030\u70B9',
  19928. '\u336D': '\u0032\u0031\u70B9',
  19929. '\u336E': '\u0032\u0032\u70B9',
  19930. '\u336F': '\u0032\u0033\u70B9',
  19931. '\u3370': '\u0032\u0034\u70B9',
  19932. '\u33E0': '\u0031\u65E5',
  19933. '\u33E1': '\u0032\u65E5',
  19934. '\u33E2': '\u0033\u65E5',
  19935. '\u33E3': '\u0034\u65E5',
  19936. '\u33E4': '\u0035\u65E5',
  19937. '\u33E5': '\u0036\u65E5',
  19938. '\u33E6': '\u0037\u65E5',
  19939. '\u33E7': '\u0038\u65E5',
  19940. '\u33E8': '\u0039\u65E5',
  19941. '\u33E9': '\u0031\u0030\u65E5',
  19942. '\u33EA': '\u0031\u0031\u65E5',
  19943. '\u33EB': '\u0031\u0032\u65E5',
  19944. '\u33EC': '\u0031\u0033\u65E5',
  19945. '\u33ED': '\u0031\u0034\u65E5',
  19946. '\u33EE': '\u0031\u0035\u65E5',
  19947. '\u33EF': '\u0031\u0036\u65E5',
  19948. '\u33F0': '\u0031\u0037\u65E5',
  19949. '\u33F1': '\u0031\u0038\u65E5',
  19950. '\u33F2': '\u0031\u0039\u65E5',
  19951. '\u33F3': '\u0032\u0030\u65E5',
  19952. '\u33F4': '\u0032\u0031\u65E5',
  19953. '\u33F5': '\u0032\u0032\u65E5',
  19954. '\u33F6': '\u0032\u0033\u65E5',
  19955. '\u33F7': '\u0032\u0034\u65E5',
  19956. '\u33F8': '\u0032\u0035\u65E5',
  19957. '\u33F9': '\u0032\u0036\u65E5',
  19958. '\u33FA': '\u0032\u0037\u65E5',
  19959. '\u33FB': '\u0032\u0038\u65E5',
  19960. '\u33FC': '\u0032\u0039\u65E5',
  19961. '\u33FD': '\u0033\u0030\u65E5',
  19962. '\u33FE': '\u0033\u0031\u65E5',
  19963. '\uFB00': '\u0066\u0066',
  19964. '\uFB01': '\u0066\u0069',
  19965. '\uFB02': '\u0066\u006C',
  19966. '\uFB03': '\u0066\u0066\u0069',
  19967. '\uFB04': '\u0066\u0066\u006C',
  19968. '\uFB05': '\u017F\u0074',
  19969. '\uFB06': '\u0073\u0074',
  19970. '\uFB13': '\u0574\u0576',
  19971. '\uFB14': '\u0574\u0565',
  19972. '\uFB15': '\u0574\u056B',
  19973. '\uFB16': '\u057E\u0576',
  19974. '\uFB17': '\u0574\u056D',
  19975. '\uFB4F': '\u05D0\u05DC',
  19976. '\uFB50': '\u0671',
  19977. '\uFB51': '\u0671',
  19978. '\uFB52': '\u067B',
  19979. '\uFB53': '\u067B',
  19980. '\uFB54': '\u067B',
  19981. '\uFB55': '\u067B',
  19982. '\uFB56': '\u067E',
  19983. '\uFB57': '\u067E',
  19984. '\uFB58': '\u067E',
  19985. '\uFB59': '\u067E',
  19986. '\uFB5A': '\u0680',
  19987. '\uFB5B': '\u0680',
  19988. '\uFB5C': '\u0680',
  19989. '\uFB5D': '\u0680',
  19990. '\uFB5E': '\u067A',
  19991. '\uFB5F': '\u067A',
  19992. '\uFB60': '\u067A',
  19993. '\uFB61': '\u067A',
  19994. '\uFB62': '\u067F',
  19995. '\uFB63': '\u067F',
  19996. '\uFB64': '\u067F',
  19997. '\uFB65': '\u067F',
  19998. '\uFB66': '\u0679',
  19999. '\uFB67': '\u0679',
  20000. '\uFB68': '\u0679',
  20001. '\uFB69': '\u0679',
  20002. '\uFB6A': '\u06A4',
  20003. '\uFB6B': '\u06A4',
  20004. '\uFB6C': '\u06A4',
  20005. '\uFB6D': '\u06A4',
  20006. '\uFB6E': '\u06A6',
  20007. '\uFB6F': '\u06A6',
  20008. '\uFB70': '\u06A6',
  20009. '\uFB71': '\u06A6',
  20010. '\uFB72': '\u0684',
  20011. '\uFB73': '\u0684',
  20012. '\uFB74': '\u0684',
  20013. '\uFB75': '\u0684',
  20014. '\uFB76': '\u0683',
  20015. '\uFB77': '\u0683',
  20016. '\uFB78': '\u0683',
  20017. '\uFB79': '\u0683',
  20018. '\uFB7A': '\u0686',
  20019. '\uFB7B': '\u0686',
  20020. '\uFB7C': '\u0686',
  20021. '\uFB7D': '\u0686',
  20022. '\uFB7E': '\u0687',
  20023. '\uFB7F': '\u0687',
  20024. '\uFB80': '\u0687',
  20025. '\uFB81': '\u0687',
  20026. '\uFB82': '\u068D',
  20027. '\uFB83': '\u068D',
  20028. '\uFB84': '\u068C',
  20029. '\uFB85': '\u068C',
  20030. '\uFB86': '\u068E',
  20031. '\uFB87': '\u068E',
  20032. '\uFB88': '\u0688',
  20033. '\uFB89': '\u0688',
  20034. '\uFB8A': '\u0698',
  20035. '\uFB8B': '\u0698',
  20036. '\uFB8C': '\u0691',
  20037. '\uFB8D': '\u0691',
  20038. '\uFB8E': '\u06A9',
  20039. '\uFB8F': '\u06A9',
  20040. '\uFB90': '\u06A9',
  20041. '\uFB91': '\u06A9',
  20042. '\uFB92': '\u06AF',
  20043. '\uFB93': '\u06AF',
  20044. '\uFB94': '\u06AF',
  20045. '\uFB95': '\u06AF',
  20046. '\uFB96': '\u06B3',
  20047. '\uFB97': '\u06B3',
  20048. '\uFB98': '\u06B3',
  20049. '\uFB99': '\u06B3',
  20050. '\uFB9A': '\u06B1',
  20051. '\uFB9B': '\u06B1',
  20052. '\uFB9C': '\u06B1',
  20053. '\uFB9D': '\u06B1',
  20054. '\uFB9E': '\u06BA',
  20055. '\uFB9F': '\u06BA',
  20056. '\uFBA0': '\u06BB',
  20057. '\uFBA1': '\u06BB',
  20058. '\uFBA2': '\u06BB',
  20059. '\uFBA3': '\u06BB',
  20060. '\uFBA4': '\u06C0',
  20061. '\uFBA5': '\u06C0',
  20062. '\uFBA6': '\u06C1',
  20063. '\uFBA7': '\u06C1',
  20064. '\uFBA8': '\u06C1',
  20065. '\uFBA9': '\u06C1',
  20066. '\uFBAA': '\u06BE',
  20067. '\uFBAB': '\u06BE',
  20068. '\uFBAC': '\u06BE',
  20069. '\uFBAD': '\u06BE',
  20070. '\uFBAE': '\u06D2',
  20071. '\uFBAF': '\u06D2',
  20072. '\uFBB0': '\u06D3',
  20073. '\uFBB1': '\u06D3',
  20074. '\uFBD3': '\u06AD',
  20075. '\uFBD4': '\u06AD',
  20076. '\uFBD5': '\u06AD',
  20077. '\uFBD6': '\u06AD',
  20078. '\uFBD7': '\u06C7',
  20079. '\uFBD8': '\u06C7',
  20080. '\uFBD9': '\u06C6',
  20081. '\uFBDA': '\u06C6',
  20082. '\uFBDB': '\u06C8',
  20083. '\uFBDC': '\u06C8',
  20084. '\uFBDD': '\u0677',
  20085. '\uFBDE': '\u06CB',
  20086. '\uFBDF': '\u06CB',
  20087. '\uFBE0': '\u06C5',
  20088. '\uFBE1': '\u06C5',
  20089. '\uFBE2': '\u06C9',
  20090. '\uFBE3': '\u06C9',
  20091. '\uFBE4': '\u06D0',
  20092. '\uFBE5': '\u06D0',
  20093. '\uFBE6': '\u06D0',
  20094. '\uFBE7': '\u06D0',
  20095. '\uFBE8': '\u0649',
  20096. '\uFBE9': '\u0649',
  20097. '\uFBEA': '\u0626\u0627',
  20098. '\uFBEB': '\u0626\u0627',
  20099. '\uFBEC': '\u0626\u06D5',
  20100. '\uFBED': '\u0626\u06D5',
  20101. '\uFBEE': '\u0626\u0648',
  20102. '\uFBEF': '\u0626\u0648',
  20103. '\uFBF0': '\u0626\u06C7',
  20104. '\uFBF1': '\u0626\u06C7',
  20105. '\uFBF2': '\u0626\u06C6',
  20106. '\uFBF3': '\u0626\u06C6',
  20107. '\uFBF4': '\u0626\u06C8',
  20108. '\uFBF5': '\u0626\u06C8',
  20109. '\uFBF6': '\u0626\u06D0',
  20110. '\uFBF7': '\u0626\u06D0',
  20111. '\uFBF8': '\u0626\u06D0',
  20112. '\uFBF9': '\u0626\u0649',
  20113. '\uFBFA': '\u0626\u0649',
  20114. '\uFBFB': '\u0626\u0649',
  20115. '\uFBFC': '\u06CC',
  20116. '\uFBFD': '\u06CC',
  20117. '\uFBFE': '\u06CC',
  20118. '\uFBFF': '\u06CC',
  20119. '\uFC00': '\u0626\u062C',
  20120. '\uFC01': '\u0626\u062D',
  20121. '\uFC02': '\u0626\u0645',
  20122. '\uFC03': '\u0626\u0649',
  20123. '\uFC04': '\u0626\u064A',
  20124. '\uFC05': '\u0628\u062C',
  20125. '\uFC06': '\u0628\u062D',
  20126. '\uFC07': '\u0628\u062E',
  20127. '\uFC08': '\u0628\u0645',
  20128. '\uFC09': '\u0628\u0649',
  20129. '\uFC0A': '\u0628\u064A',
  20130. '\uFC0B': '\u062A\u062C',
  20131. '\uFC0C': '\u062A\u062D',
  20132. '\uFC0D': '\u062A\u062E',
  20133. '\uFC0E': '\u062A\u0645',
  20134. '\uFC0F': '\u062A\u0649',
  20135. '\uFC10': '\u062A\u064A',
  20136. '\uFC11': '\u062B\u062C',
  20137. '\uFC12': '\u062B\u0645',
  20138. '\uFC13': '\u062B\u0649',
  20139. '\uFC14': '\u062B\u064A',
  20140. '\uFC15': '\u062C\u062D',
  20141. '\uFC16': '\u062C\u0645',
  20142. '\uFC17': '\u062D\u062C',
  20143. '\uFC18': '\u062D\u0645',
  20144. '\uFC19': '\u062E\u062C',
  20145. '\uFC1A': '\u062E\u062D',
  20146. '\uFC1B': '\u062E\u0645',
  20147. '\uFC1C': '\u0633\u062C',
  20148. '\uFC1D': '\u0633\u062D',
  20149. '\uFC1E': '\u0633\u062E',
  20150. '\uFC1F': '\u0633\u0645',
  20151. '\uFC20': '\u0635\u062D',
  20152. '\uFC21': '\u0635\u0645',
  20153. '\uFC22': '\u0636\u062C',
  20154. '\uFC23': '\u0636\u062D',
  20155. '\uFC24': '\u0636\u062E',
  20156. '\uFC25': '\u0636\u0645',
  20157. '\uFC26': '\u0637\u062D',
  20158. '\uFC27': '\u0637\u0645',
  20159. '\uFC28': '\u0638\u0645',
  20160. '\uFC29': '\u0639\u062C',
  20161. '\uFC2A': '\u0639\u0645',
  20162. '\uFC2B': '\u063A\u062C',
  20163. '\uFC2C': '\u063A\u0645',
  20164. '\uFC2D': '\u0641\u062C',
  20165. '\uFC2E': '\u0641\u062D',
  20166. '\uFC2F': '\u0641\u062E',
  20167. '\uFC30': '\u0641\u0645',
  20168. '\uFC31': '\u0641\u0649',
  20169. '\uFC32': '\u0641\u064A',
  20170. '\uFC33': '\u0642\u062D',
  20171. '\uFC34': '\u0642\u0645',
  20172. '\uFC35': '\u0642\u0649',
  20173. '\uFC36': '\u0642\u064A',
  20174. '\uFC37': '\u0643\u0627',
  20175. '\uFC38': '\u0643\u062C',
  20176. '\uFC39': '\u0643\u062D',
  20177. '\uFC3A': '\u0643\u062E',
  20178. '\uFC3B': '\u0643\u0644',
  20179. '\uFC3C': '\u0643\u0645',
  20180. '\uFC3D': '\u0643\u0649',
  20181. '\uFC3E': '\u0643\u064A',
  20182. '\uFC3F': '\u0644\u062C',
  20183. '\uFC40': '\u0644\u062D',
  20184. '\uFC41': '\u0644\u062E',
  20185. '\uFC42': '\u0644\u0645',
  20186. '\uFC43': '\u0644\u0649',
  20187. '\uFC44': '\u0644\u064A',
  20188. '\uFC45': '\u0645\u062C',
  20189. '\uFC46': '\u0645\u062D',
  20190. '\uFC47': '\u0645\u062E',
  20191. '\uFC48': '\u0645\u0645',
  20192. '\uFC49': '\u0645\u0649',
  20193. '\uFC4A': '\u0645\u064A',
  20194. '\uFC4B': '\u0646\u062C',
  20195. '\uFC4C': '\u0646\u062D',
  20196. '\uFC4D': '\u0646\u062E',
  20197. '\uFC4E': '\u0646\u0645',
  20198. '\uFC4F': '\u0646\u0649',
  20199. '\uFC50': '\u0646\u064A',
  20200. '\uFC51': '\u0647\u062C',
  20201. '\uFC52': '\u0647\u0645',
  20202. '\uFC53': '\u0647\u0649',
  20203. '\uFC54': '\u0647\u064A',
  20204. '\uFC55': '\u064A\u062C',
  20205. '\uFC56': '\u064A\u062D',
  20206. '\uFC57': '\u064A\u062E',
  20207. '\uFC58': '\u064A\u0645',
  20208. '\uFC59': '\u064A\u0649',
  20209. '\uFC5A': '\u064A\u064A',
  20210. '\uFC5B': '\u0630\u0670',
  20211. '\uFC5C': '\u0631\u0670',
  20212. '\uFC5D': '\u0649\u0670',
  20213. '\uFC5E': '\u0020\u064C\u0651',
  20214. '\uFC5F': '\u0020\u064D\u0651',
  20215. '\uFC60': '\u0020\u064E\u0651',
  20216. '\uFC61': '\u0020\u064F\u0651',
  20217. '\uFC62': '\u0020\u0650\u0651',
  20218. '\uFC63': '\u0020\u0651\u0670',
  20219. '\uFC64': '\u0626\u0631',
  20220. '\uFC65': '\u0626\u0632',
  20221. '\uFC66': '\u0626\u0645',
  20222. '\uFC67': '\u0626\u0646',
  20223. '\uFC68': '\u0626\u0649',
  20224. '\uFC69': '\u0626\u064A',
  20225. '\uFC6A': '\u0628\u0631',
  20226. '\uFC6B': '\u0628\u0632',
  20227. '\uFC6C': '\u0628\u0645',
  20228. '\uFC6D': '\u0628\u0646',
  20229. '\uFC6E': '\u0628\u0649',
  20230. '\uFC6F': '\u0628\u064A',
  20231. '\uFC70': '\u062A\u0631',
  20232. '\uFC71': '\u062A\u0632',
  20233. '\uFC72': '\u062A\u0645',
  20234. '\uFC73': '\u062A\u0646',
  20235. '\uFC74': '\u062A\u0649',
  20236. '\uFC75': '\u062A\u064A',
  20237. '\uFC76': '\u062B\u0631',
  20238. '\uFC77': '\u062B\u0632',
  20239. '\uFC78': '\u062B\u0645',
  20240. '\uFC79': '\u062B\u0646',
  20241. '\uFC7A': '\u062B\u0649',
  20242. '\uFC7B': '\u062B\u064A',
  20243. '\uFC7C': '\u0641\u0649',
  20244. '\uFC7D': '\u0641\u064A',
  20245. '\uFC7E': '\u0642\u0649',
  20246. '\uFC7F': '\u0642\u064A',
  20247. '\uFC80': '\u0643\u0627',
  20248. '\uFC81': '\u0643\u0644',
  20249. '\uFC82': '\u0643\u0645',
  20250. '\uFC83': '\u0643\u0649',
  20251. '\uFC84': '\u0643\u064A',
  20252. '\uFC85': '\u0644\u0645',
  20253. '\uFC86': '\u0644\u0649',
  20254. '\uFC87': '\u0644\u064A',
  20255. '\uFC88': '\u0645\u0627',
  20256. '\uFC89': '\u0645\u0645',
  20257. '\uFC8A': '\u0646\u0631',
  20258. '\uFC8B': '\u0646\u0632',
  20259. '\uFC8C': '\u0646\u0645',
  20260. '\uFC8D': '\u0646\u0646',
  20261. '\uFC8E': '\u0646\u0649',
  20262. '\uFC8F': '\u0646\u064A',
  20263. '\uFC90': '\u0649\u0670',
  20264. '\uFC91': '\u064A\u0631',
  20265. '\uFC92': '\u064A\u0632',
  20266. '\uFC93': '\u064A\u0645',
  20267. '\uFC94': '\u064A\u0646',
  20268. '\uFC95': '\u064A\u0649',
  20269. '\uFC96': '\u064A\u064A',
  20270. '\uFC97': '\u0626\u062C',
  20271. '\uFC98': '\u0626\u062D',
  20272. '\uFC99': '\u0626\u062E',
  20273. '\uFC9A': '\u0626\u0645',
  20274. '\uFC9B': '\u0626\u0647',
  20275. '\uFC9C': '\u0628\u062C',
  20276. '\uFC9D': '\u0628\u062D',
  20277. '\uFC9E': '\u0628\u062E',
  20278. '\uFC9F': '\u0628\u0645',
  20279. '\uFCA0': '\u0628\u0647',
  20280. '\uFCA1': '\u062A\u062C',
  20281. '\uFCA2': '\u062A\u062D',
  20282. '\uFCA3': '\u062A\u062E',
  20283. '\uFCA4': '\u062A\u0645',
  20284. '\uFCA5': '\u062A\u0647',
  20285. '\uFCA6': '\u062B\u0645',
  20286. '\uFCA7': '\u062C\u062D',
  20287. '\uFCA8': '\u062C\u0645',
  20288. '\uFCA9': '\u062D\u062C',
  20289. '\uFCAA': '\u062D\u0645',
  20290. '\uFCAB': '\u062E\u062C',
  20291. '\uFCAC': '\u062E\u0645',
  20292. '\uFCAD': '\u0633\u062C',
  20293. '\uFCAE': '\u0633\u062D',
  20294. '\uFCAF': '\u0633\u062E',
  20295. '\uFCB0': '\u0633\u0645',
  20296. '\uFCB1': '\u0635\u062D',
  20297. '\uFCB2': '\u0635\u062E',
  20298. '\uFCB3': '\u0635\u0645',
  20299. '\uFCB4': '\u0636\u062C',
  20300. '\uFCB5': '\u0636\u062D',
  20301. '\uFCB6': '\u0636\u062E',
  20302. '\uFCB7': '\u0636\u0645',
  20303. '\uFCB8': '\u0637\u062D',
  20304. '\uFCB9': '\u0638\u0645',
  20305. '\uFCBA': '\u0639\u062C',
  20306. '\uFCBB': '\u0639\u0645',
  20307. '\uFCBC': '\u063A\u062C',
  20308. '\uFCBD': '\u063A\u0645',
  20309. '\uFCBE': '\u0641\u062C',
  20310. '\uFCBF': '\u0641\u062D',
  20311. '\uFCC0': '\u0641\u062E',
  20312. '\uFCC1': '\u0641\u0645',
  20313. '\uFCC2': '\u0642\u062D',
  20314. '\uFCC3': '\u0642\u0645',
  20315. '\uFCC4': '\u0643\u062C',
  20316. '\uFCC5': '\u0643\u062D',
  20317. '\uFCC6': '\u0643\u062E',
  20318. '\uFCC7': '\u0643\u0644',
  20319. '\uFCC8': '\u0643\u0645',
  20320. '\uFCC9': '\u0644\u062C',
  20321. '\uFCCA': '\u0644\u062D',
  20322. '\uFCCB': '\u0644\u062E',
  20323. '\uFCCC': '\u0644\u0645',
  20324. '\uFCCD': '\u0644\u0647',
  20325. '\uFCCE': '\u0645\u062C',
  20326. '\uFCCF': '\u0645\u062D',
  20327. '\uFCD0': '\u0645\u062E',
  20328. '\uFCD1': '\u0645\u0645',
  20329. '\uFCD2': '\u0646\u062C',
  20330. '\uFCD3': '\u0646\u062D',
  20331. '\uFCD4': '\u0646\u062E',
  20332. '\uFCD5': '\u0646\u0645',
  20333. '\uFCD6': '\u0646\u0647',
  20334. '\uFCD7': '\u0647\u062C',
  20335. '\uFCD8': '\u0647\u0645',
  20336. '\uFCD9': '\u0647\u0670',
  20337. '\uFCDA': '\u064A\u062C',
  20338. '\uFCDB': '\u064A\u062D',
  20339. '\uFCDC': '\u064A\u062E',
  20340. '\uFCDD': '\u064A\u0645',
  20341. '\uFCDE': '\u064A\u0647',
  20342. '\uFCDF': '\u0626\u0645',
  20343. '\uFCE0': '\u0626\u0647',
  20344. '\uFCE1': '\u0628\u0645',
  20345. '\uFCE2': '\u0628\u0647',
  20346. '\uFCE3': '\u062A\u0645',
  20347. '\uFCE4': '\u062A\u0647',
  20348. '\uFCE5': '\u062B\u0645',
  20349. '\uFCE6': '\u062B\u0647',
  20350. '\uFCE7': '\u0633\u0645',
  20351. '\uFCE8': '\u0633\u0647',
  20352. '\uFCE9': '\u0634\u0645',
  20353. '\uFCEA': '\u0634\u0647',
  20354. '\uFCEB': '\u0643\u0644',
  20355. '\uFCEC': '\u0643\u0645',
  20356. '\uFCED': '\u0644\u0645',
  20357. '\uFCEE': '\u0646\u0645',
  20358. '\uFCEF': '\u0646\u0647',
  20359. '\uFCF0': '\u064A\u0645',
  20360. '\uFCF1': '\u064A\u0647',
  20361. '\uFCF2': '\u0640\u064E\u0651',
  20362. '\uFCF3': '\u0640\u064F\u0651',
  20363. '\uFCF4': '\u0640\u0650\u0651',
  20364. '\uFCF5': '\u0637\u0649',
  20365. '\uFCF6': '\u0637\u064A',
  20366. '\uFCF7': '\u0639\u0649',
  20367. '\uFCF8': '\u0639\u064A',
  20368. '\uFCF9': '\u063A\u0649',
  20369. '\uFCFA': '\u063A\u064A',
  20370. '\uFCFB': '\u0633\u0649',
  20371. '\uFCFC': '\u0633\u064A',
  20372. '\uFCFD': '\u0634\u0649',
  20373. '\uFCFE': '\u0634\u064A',
  20374. '\uFCFF': '\u062D\u0649',
  20375. '\uFD00': '\u062D\u064A',
  20376. '\uFD01': '\u062C\u0649',
  20377. '\uFD02': '\u062C\u064A',
  20378. '\uFD03': '\u062E\u0649',
  20379. '\uFD04': '\u062E\u064A',
  20380. '\uFD05': '\u0635\u0649',
  20381. '\uFD06': '\u0635\u064A',
  20382. '\uFD07': '\u0636\u0649',
  20383. '\uFD08': '\u0636\u064A',
  20384. '\uFD09': '\u0634\u062C',
  20385. '\uFD0A': '\u0634\u062D',
  20386. '\uFD0B': '\u0634\u062E',
  20387. '\uFD0C': '\u0634\u0645',
  20388. '\uFD0D': '\u0634\u0631',
  20389. '\uFD0E': '\u0633\u0631',
  20390. '\uFD0F': '\u0635\u0631',
  20391. '\uFD10': '\u0636\u0631',
  20392. '\uFD11': '\u0637\u0649',
  20393. '\uFD12': '\u0637\u064A',
  20394. '\uFD13': '\u0639\u0649',
  20395. '\uFD14': '\u0639\u064A',
  20396. '\uFD15': '\u063A\u0649',
  20397. '\uFD16': '\u063A\u064A',
  20398. '\uFD17': '\u0633\u0649',
  20399. '\uFD18': '\u0633\u064A',
  20400. '\uFD19': '\u0634\u0649',
  20401. '\uFD1A': '\u0634\u064A',
  20402. '\uFD1B': '\u062D\u0649',
  20403. '\uFD1C': '\u062D\u064A',
  20404. '\uFD1D': '\u062C\u0649',
  20405. '\uFD1E': '\u062C\u064A',
  20406. '\uFD1F': '\u062E\u0649',
  20407. '\uFD20': '\u062E\u064A',
  20408. '\uFD21': '\u0635\u0649',
  20409. '\uFD22': '\u0635\u064A',
  20410. '\uFD23': '\u0636\u0649',
  20411. '\uFD24': '\u0636\u064A',
  20412. '\uFD25': '\u0634\u062C',
  20413. '\uFD26': '\u0634\u062D',
  20414. '\uFD27': '\u0634\u062E',
  20415. '\uFD28': '\u0634\u0645',
  20416. '\uFD29': '\u0634\u0631',
  20417. '\uFD2A': '\u0633\u0631',
  20418. '\uFD2B': '\u0635\u0631',
  20419. '\uFD2C': '\u0636\u0631',
  20420. '\uFD2D': '\u0634\u062C',
  20421. '\uFD2E': '\u0634\u062D',
  20422. '\uFD2F': '\u0634\u062E',
  20423. '\uFD30': '\u0634\u0645',
  20424. '\uFD31': '\u0633\u0647',
  20425. '\uFD32': '\u0634\u0647',
  20426. '\uFD33': '\u0637\u0645',
  20427. '\uFD34': '\u0633\u062C',
  20428. '\uFD35': '\u0633\u062D',
  20429. '\uFD36': '\u0633\u062E',
  20430. '\uFD37': '\u0634\u062C',
  20431. '\uFD38': '\u0634\u062D',
  20432. '\uFD39': '\u0634\u062E',
  20433. '\uFD3A': '\u0637\u0645',
  20434. '\uFD3B': '\u0638\u0645',
  20435. '\uFD3C': '\u0627\u064B',
  20436. '\uFD3D': '\u0627\u064B',
  20437. '\uFD50': '\u062A\u062C\u0645',
  20438. '\uFD51': '\u062A\u062D\u062C',
  20439. '\uFD52': '\u062A\u062D\u062C',
  20440. '\uFD53': '\u062A\u062D\u0645',
  20441. '\uFD54': '\u062A\u062E\u0645',
  20442. '\uFD55': '\u062A\u0645\u062C',
  20443. '\uFD56': '\u062A\u0645\u062D',
  20444. '\uFD57': '\u062A\u0645\u062E',
  20445. '\uFD58': '\u062C\u0645\u062D',
  20446. '\uFD59': '\u062C\u0645\u062D',
  20447. '\uFD5A': '\u062D\u0645\u064A',
  20448. '\uFD5B': '\u062D\u0645\u0649',
  20449. '\uFD5C': '\u0633\u062D\u062C',
  20450. '\uFD5D': '\u0633\u062C\u062D',
  20451. '\uFD5E': '\u0633\u062C\u0649',
  20452. '\uFD5F': '\u0633\u0645\u062D',
  20453. '\uFD60': '\u0633\u0645\u062D',
  20454. '\uFD61': '\u0633\u0645\u062C',
  20455. '\uFD62': '\u0633\u0645\u0645',
  20456. '\uFD63': '\u0633\u0645\u0645',
  20457. '\uFD64': '\u0635\u062D\u062D',
  20458. '\uFD65': '\u0635\u062D\u062D',
  20459. '\uFD66': '\u0635\u0645\u0645',
  20460. '\uFD67': '\u0634\u062D\u0645',
  20461. '\uFD68': '\u0634\u062D\u0645',
  20462. '\uFD69': '\u0634\u062C\u064A',
  20463. '\uFD6A': '\u0634\u0645\u062E',
  20464. '\uFD6B': '\u0634\u0645\u062E',
  20465. '\uFD6C': '\u0634\u0645\u0645',
  20466. '\uFD6D': '\u0634\u0645\u0645',
  20467. '\uFD6E': '\u0636\u062D\u0649',
  20468. '\uFD6F': '\u0636\u062E\u0645',
  20469. '\uFD70': '\u0636\u062E\u0645',
  20470. '\uFD71': '\u0637\u0645\u062D',
  20471. '\uFD72': '\u0637\u0645\u062D',
  20472. '\uFD73': '\u0637\u0645\u0645',
  20473. '\uFD74': '\u0637\u0645\u064A',
  20474. '\uFD75': '\u0639\u062C\u0645',
  20475. '\uFD76': '\u0639\u0645\u0645',
  20476. '\uFD77': '\u0639\u0645\u0645',
  20477. '\uFD78': '\u0639\u0645\u0649',
  20478. '\uFD79': '\u063A\u0645\u0645',
  20479. '\uFD7A': '\u063A\u0645\u064A',
  20480. '\uFD7B': '\u063A\u0645\u0649',
  20481. '\uFD7C': '\u0641\u062E\u0645',
  20482. '\uFD7D': '\u0641\u062E\u0645',
  20483. '\uFD7E': '\u0642\u0645\u062D',
  20484. '\uFD7F': '\u0642\u0645\u0645',
  20485. '\uFD80': '\u0644\u062D\u0645',
  20486. '\uFD81': '\u0644\u062D\u064A',
  20487. '\uFD82': '\u0644\u062D\u0649',
  20488. '\uFD83': '\u0644\u062C\u062C',
  20489. '\uFD84': '\u0644\u062C\u062C',
  20490. '\uFD85': '\u0644\u062E\u0645',
  20491. '\uFD86': '\u0644\u062E\u0645',
  20492. '\uFD87': '\u0644\u0645\u062D',
  20493. '\uFD88': '\u0644\u0645\u062D',
  20494. '\uFD89': '\u0645\u062D\u062C',
  20495. '\uFD8A': '\u0645\u062D\u0645',
  20496. '\uFD8B': '\u0645\u062D\u064A',
  20497. '\uFD8C': '\u0645\u062C\u062D',
  20498. '\uFD8D': '\u0645\u062C\u0645',
  20499. '\uFD8E': '\u0645\u062E\u062C',
  20500. '\uFD8F': '\u0645\u062E\u0645',
  20501. '\uFD92': '\u0645\u062C\u062E',
  20502. '\uFD93': '\u0647\u0645\u062C',
  20503. '\uFD94': '\u0647\u0645\u0645',
  20504. '\uFD95': '\u0646\u062D\u0645',
  20505. '\uFD96': '\u0646\u062D\u0649',
  20506. '\uFD97': '\u0646\u062C\u0645',
  20507. '\uFD98': '\u0646\u062C\u0645',
  20508. '\uFD99': '\u0646\u062C\u0649',
  20509. '\uFD9A': '\u0646\u0645\u064A',
  20510. '\uFD9B': '\u0646\u0645\u0649',
  20511. '\uFD9C': '\u064A\u0645\u0645',
  20512. '\uFD9D': '\u064A\u0645\u0645',
  20513. '\uFD9E': '\u0628\u062E\u064A',
  20514. '\uFD9F': '\u062A\u062C\u064A',
  20515. '\uFDA0': '\u062A\u062C\u0649',
  20516. '\uFDA1': '\u062A\u062E\u064A',
  20517. '\uFDA2': '\u062A\u062E\u0649',
  20518. '\uFDA3': '\u062A\u0645\u064A',
  20519. '\uFDA4': '\u062A\u0645\u0649',
  20520. '\uFDA5': '\u062C\u0645\u064A',
  20521. '\uFDA6': '\u062C\u062D\u0649',
  20522. '\uFDA7': '\u062C\u0645\u0649',
  20523. '\uFDA8': '\u0633\u062E\u0649',
  20524. '\uFDA9': '\u0635\u062D\u064A',
  20525. '\uFDAA': '\u0634\u062D\u064A',
  20526. '\uFDAB': '\u0636\u062D\u064A',
  20527. '\uFDAC': '\u0644\u062C\u064A',
  20528. '\uFDAD': '\u0644\u0645\u064A',
  20529. '\uFDAE': '\u064A\u062D\u064A',
  20530. '\uFDAF': '\u064A\u062C\u064A',
  20531. '\uFDB0': '\u064A\u0645\u064A',
  20532. '\uFDB1': '\u0645\u0645\u064A',
  20533. '\uFDB2': '\u0642\u0645\u064A',
  20534. '\uFDB3': '\u0646\u062D\u064A',
  20535. '\uFDB4': '\u0642\u0645\u062D',
  20536. '\uFDB5': '\u0644\u062D\u0645',
  20537. '\uFDB6': '\u0639\u0645\u064A',
  20538. '\uFDB7': '\u0643\u0645\u064A',
  20539. '\uFDB8': '\u0646\u062C\u062D',
  20540. '\uFDB9': '\u0645\u062E\u064A',
  20541. '\uFDBA': '\u0644\u062C\u0645',
  20542. '\uFDBB': '\u0643\u0645\u0645',
  20543. '\uFDBC': '\u0644\u062C\u0645',
  20544. '\uFDBD': '\u0646\u062C\u062D',
  20545. '\uFDBE': '\u062C\u062D\u064A',
  20546. '\uFDBF': '\u062D\u062C\u064A',
  20547. '\uFDC0': '\u0645\u062C\u064A',
  20548. '\uFDC1': '\u0641\u0645\u064A',
  20549. '\uFDC2': '\u0628\u062D\u064A',
  20550. '\uFDC3': '\u0643\u0645\u0645',
  20551. '\uFDC4': '\u0639\u062C\u0645',
  20552. '\uFDC5': '\u0635\u0645\u0645',
  20553. '\uFDC6': '\u0633\u062E\u064A',
  20554. '\uFDC7': '\u0646\u062C\u064A',
  20555. '\uFE49': '\u203E',
  20556. '\uFE4A': '\u203E',
  20557. '\uFE4B': '\u203E',
  20558. '\uFE4C': '\u203E',
  20559. '\uFE4D': '\u005F',
  20560. '\uFE4E': '\u005F',
  20561. '\uFE4F': '\u005F',
  20562. '\uFE80': '\u0621',
  20563. '\uFE81': '\u0622',
  20564. '\uFE82': '\u0622',
  20565. '\uFE83': '\u0623',
  20566. '\uFE84': '\u0623',
  20567. '\uFE85': '\u0624',
  20568. '\uFE86': '\u0624',
  20569. '\uFE87': '\u0625',
  20570. '\uFE88': '\u0625',
  20571. '\uFE89': '\u0626',
  20572. '\uFE8A': '\u0626',
  20573. '\uFE8B': '\u0626',
  20574. '\uFE8C': '\u0626',
  20575. '\uFE8D': '\u0627',
  20576. '\uFE8E': '\u0627',
  20577. '\uFE8F': '\u0628',
  20578. '\uFE90': '\u0628',
  20579. '\uFE91': '\u0628',
  20580. '\uFE92': '\u0628',
  20581. '\uFE93': '\u0629',
  20582. '\uFE94': '\u0629',
  20583. '\uFE95': '\u062A',
  20584. '\uFE96': '\u062A',
  20585. '\uFE97': '\u062A',
  20586. '\uFE98': '\u062A',
  20587. '\uFE99': '\u062B',
  20588. '\uFE9A': '\u062B',
  20589. '\uFE9B': '\u062B',
  20590. '\uFE9C': '\u062B',
  20591. '\uFE9D': '\u062C',
  20592. '\uFE9E': '\u062C',
  20593. '\uFE9F': '\u062C',
  20594. '\uFEA0': '\u062C',
  20595. '\uFEA1': '\u062D',
  20596. '\uFEA2': '\u062D',
  20597. '\uFEA3': '\u062D',
  20598. '\uFEA4': '\u062D',
  20599. '\uFEA5': '\u062E',
  20600. '\uFEA6': '\u062E',
  20601. '\uFEA7': '\u062E',
  20602. '\uFEA8': '\u062E',
  20603. '\uFEA9': '\u062F',
  20604. '\uFEAA': '\u062F',
  20605. '\uFEAB': '\u0630',
  20606. '\uFEAC': '\u0630',
  20607. '\uFEAD': '\u0631',
  20608. '\uFEAE': '\u0631',
  20609. '\uFEAF': '\u0632',
  20610. '\uFEB0': '\u0632',
  20611. '\uFEB1': '\u0633',
  20612. '\uFEB2': '\u0633',
  20613. '\uFEB3': '\u0633',
  20614. '\uFEB4': '\u0633',
  20615. '\uFEB5': '\u0634',
  20616. '\uFEB6': '\u0634',
  20617. '\uFEB7': '\u0634',
  20618. '\uFEB8': '\u0634',
  20619. '\uFEB9': '\u0635',
  20620. '\uFEBA': '\u0635',
  20621. '\uFEBB': '\u0635',
  20622. '\uFEBC': '\u0635',
  20623. '\uFEBD': '\u0636',
  20624. '\uFEBE': '\u0636',
  20625. '\uFEBF': '\u0636',
  20626. '\uFEC0': '\u0636',
  20627. '\uFEC1': '\u0637',
  20628. '\uFEC2': '\u0637',
  20629. '\uFEC3': '\u0637',
  20630. '\uFEC4': '\u0637',
  20631. '\uFEC5': '\u0638',
  20632. '\uFEC6': '\u0638',
  20633. '\uFEC7': '\u0638',
  20634. '\uFEC8': '\u0638',
  20635. '\uFEC9': '\u0639',
  20636. '\uFECA': '\u0639',
  20637. '\uFECB': '\u0639',
  20638. '\uFECC': '\u0639',
  20639. '\uFECD': '\u063A',
  20640. '\uFECE': '\u063A',
  20641. '\uFECF': '\u063A',
  20642. '\uFED0': '\u063A',
  20643. '\uFED1': '\u0641',
  20644. '\uFED2': '\u0641',
  20645. '\uFED3': '\u0641',
  20646. '\uFED4': '\u0641',
  20647. '\uFED5': '\u0642',
  20648. '\uFED6': '\u0642',
  20649. '\uFED7': '\u0642',
  20650. '\uFED8': '\u0642',
  20651. '\uFED9': '\u0643',
  20652. '\uFEDA': '\u0643',
  20653. '\uFEDB': '\u0643',
  20654. '\uFEDC': '\u0643',
  20655. '\uFEDD': '\u0644',
  20656. '\uFEDE': '\u0644',
  20657. '\uFEDF': '\u0644',
  20658. '\uFEE0': '\u0644',
  20659. '\uFEE1': '\u0645',
  20660. '\uFEE2': '\u0645',
  20661. '\uFEE3': '\u0645',
  20662. '\uFEE4': '\u0645',
  20663. '\uFEE5': '\u0646',
  20664. '\uFEE6': '\u0646',
  20665. '\uFEE7': '\u0646',
  20666. '\uFEE8': '\u0646',
  20667. '\uFEE9': '\u0647',
  20668. '\uFEEA': '\u0647',
  20669. '\uFEEB': '\u0647',
  20670. '\uFEEC': '\u0647',
  20671. '\uFEED': '\u0648',
  20672. '\uFEEE': '\u0648',
  20673. '\uFEEF': '\u0649',
  20674. '\uFEF0': '\u0649',
  20675. '\uFEF1': '\u064A',
  20676. '\uFEF2': '\u064A',
  20677. '\uFEF3': '\u064A',
  20678. '\uFEF4': '\u064A',
  20679. '\uFEF5': '\u0644\u0622',
  20680. '\uFEF6': '\u0644\u0622',
  20681. '\uFEF7': '\u0644\u0623',
  20682. '\uFEF8': '\u0644\u0623',
  20683. '\uFEF9': '\u0644\u0625',
  20684. '\uFEFA': '\u0644\u0625',
  20685. '\uFEFB': '\u0644\u0627',
  20686. '\uFEFC': '\u0644\u0627'
  20687. };
  20688. function reverseIfRtl(chars) {
  20689. var charsLength = chars.length;
  20690. //reverse an arabic ligature
  20691. if (charsLength <= 1 || !isRTLRangeFor(chars.charCodeAt(0))) {
  20692. return chars;
  20693. }
  20694. var s = '';
  20695. for (var ii = charsLength - 1; ii >= 0; ii--) {
  20696. s += chars[ii];
  20697. }
  20698. return s;
  20699. }
  20700. function adjustWidths(properties) {
  20701. if (properties.fontMatrix[0] === FONT_IDENTITY_MATRIX[0]) {
  20702. return;
  20703. }
  20704. // adjusting width to fontMatrix scale
  20705. var scale = 0.001 / properties.fontMatrix[0];
  20706. var glyphsWidths = properties.widths;
  20707. for (var glyph in glyphsWidths) {
  20708. glyphsWidths[glyph] *= scale;
  20709. }
  20710. properties.defaultWidth *= scale;
  20711. }
  20712. function getFontType(type, subtype) {
  20713. switch (type) {
  20714. case 'Type1':
  20715. return subtype === 'Type1C' ? FontType.TYPE1C : FontType.TYPE1;
  20716. case 'CIDFontType0':
  20717. return subtype === 'CIDFontType0C' ? FontType.CIDFONTTYPE0C :
  20718. FontType.CIDFONTTYPE0;
  20719. case 'OpenType':
  20720. return FontType.OPENTYPE;
  20721. case 'TrueType':
  20722. return FontType.TRUETYPE;
  20723. case 'CIDFontType2':
  20724. return FontType.CIDFONTTYPE2;
  20725. case 'MMType1':
  20726. return FontType.MMTYPE1;
  20727. case 'Type0':
  20728. return FontType.TYPE0;
  20729. default:
  20730. return FontType.UNKNOWN;
  20731. }
  20732. }
  20733. var Glyph = (function GlyphClosure() {
  20734. function Glyph(fontChar, unicode, accent, width, vmetric, operatorListId) {
  20735. this.fontChar = fontChar;
  20736. this.unicode = unicode;
  20737. this.accent = accent;
  20738. this.width = width;
  20739. this.vmetric = vmetric;
  20740. this.operatorListId = operatorListId;
  20741. }
  20742. Glyph.prototype.matchesForCache =
  20743. function(fontChar, unicode, accent, width, vmetric, operatorListId) {
  20744. return this.fontChar === fontChar &&
  20745. this.unicode === unicode &&
  20746. this.accent === accent &&
  20747. this.width === width &&
  20748. this.vmetric === vmetric &&
  20749. this.operatorListId === operatorListId;
  20750. };
  20751. return Glyph;
  20752. })();
  20753. var ToUnicodeMap = (function ToUnicodeMapClosure() {
  20754. function ToUnicodeMap(cmap) {
  20755. // The elements of this._map can be integers or strings, depending on how
  20756. // |cmap| was created.
  20757. this._map = cmap;
  20758. }
  20759. ToUnicodeMap.prototype = {
  20760. get length() {
  20761. return this._map.length;
  20762. },
  20763. forEach: function(callback) {
  20764. for (var charCode in this._map) {
  20765. callback(charCode, this._map[charCode].charCodeAt(0));
  20766. }
  20767. },
  20768. has: function(i) {
  20769. return this._map[i] !== undefined;
  20770. },
  20771. get: function(i) {
  20772. return this._map[i];
  20773. },
  20774. charCodeOf: function(v) {
  20775. return this._map.indexOf(v);
  20776. }
  20777. };
  20778. return ToUnicodeMap;
  20779. })();
  20780. var IdentityToUnicodeMap = (function IdentityToUnicodeMapClosure() {
  20781. function IdentityToUnicodeMap(firstChar, lastChar) {
  20782. this.firstChar = firstChar;
  20783. this.lastChar = lastChar;
  20784. }
  20785. IdentityToUnicodeMap.prototype = {
  20786. get length() {
  20787. return (this.lastChar + 1) - this.firstChar;
  20788. },
  20789. forEach: function (callback) {
  20790. for (var i = this.firstChar, ii = this.lastChar; i <= ii; i++) {
  20791. callback(i, i);
  20792. }
  20793. },
  20794. has: function (i) {
  20795. return this.firstChar <= i && i <= this.lastChar;
  20796. },
  20797. get: function (i) {
  20798. if (this.firstChar <= i && i <= this.lastChar) {
  20799. return String.fromCharCode(i);
  20800. }
  20801. return undefined;
  20802. },
  20803. charCodeOf: function (v) {
  20804. error('should not call .charCodeOf');
  20805. }
  20806. };
  20807. return IdentityToUnicodeMap;
  20808. })();
  20809. var OpenTypeFileBuilder = (function OpenTypeFileBuilderClosure() {
  20810. function writeInt16(dest, offset, num) {
  20811. dest[offset] = (num >> 8) & 0xFF;
  20812. dest[offset + 1] = num & 0xFF;
  20813. }
  20814. function writeInt32(dest, offset, num) {
  20815. dest[offset] = (num >> 24) & 0xFF;
  20816. dest[offset + 1] = (num >> 16) & 0xFF;
  20817. dest[offset + 2] = (num >> 8) & 0xFF;
  20818. dest[offset + 3] = num & 0xFF;
  20819. }
  20820. function writeData(dest, offset, data) {
  20821. var i, ii;
  20822. if (data instanceof Uint8Array) {
  20823. dest.set(data, offset);
  20824. } else if (typeof data === 'string') {
  20825. for (i = 0, ii = data.length; i < ii; i++) {
  20826. dest[offset++] = data.charCodeAt(i) & 0xFF;
  20827. }
  20828. } else {
  20829. // treating everything else as array
  20830. for (i = 0, ii = data.length; i < ii; i++) {
  20831. dest[offset++] = data[i] & 0xFF;
  20832. }
  20833. }
  20834. }
  20835. function OpenTypeFileBuilder(sfnt) {
  20836. this.sfnt = sfnt;
  20837. this.tables = Object.create(null);
  20838. }
  20839. OpenTypeFileBuilder.getSearchParams =
  20840. function OpenTypeFileBuilder_getSearchParams(entriesCount, entrySize) {
  20841. var maxPower2 = 1, log2 = 0;
  20842. while ((maxPower2 ^ entriesCount) > maxPower2) {
  20843. maxPower2 <<= 1;
  20844. log2++;
  20845. }
  20846. var searchRange = maxPower2 * entrySize;
  20847. return {
  20848. range: searchRange,
  20849. entry: log2,
  20850. rangeShift: entrySize * entriesCount - searchRange
  20851. };
  20852. };
  20853. var OTF_HEADER_SIZE = 12;
  20854. var OTF_TABLE_ENTRY_SIZE = 16;
  20855. OpenTypeFileBuilder.prototype = {
  20856. toArray: function OpenTypeFileBuilder_toArray() {
  20857. var sfnt = this.sfnt;
  20858. // Tables needs to be written by ascendant alphabetic order
  20859. var tables = this.tables;
  20860. var tablesNames = Object.keys(tables);
  20861. tablesNames.sort();
  20862. var numTables = tablesNames.length;
  20863. var i, j, jj, table, tableName;
  20864. // layout the tables data
  20865. var offset = OTF_HEADER_SIZE + numTables * OTF_TABLE_ENTRY_SIZE;
  20866. var tableOffsets = [offset];
  20867. for (i = 0; i < numTables; i++) {
  20868. table = tables[tablesNames[i]];
  20869. var paddedLength = ((table.length + 3) & ~3) >>> 0;
  20870. offset += paddedLength;
  20871. tableOffsets.push(offset);
  20872. }
  20873. var file = new Uint8Array(offset);
  20874. // write the table data first (mostly for checksum)
  20875. for (i = 0; i < numTables; i++) {
  20876. table = tables[tablesNames[i]];
  20877. writeData(file, tableOffsets[i], table);
  20878. }
  20879. // sfnt version (4 bytes)
  20880. if (sfnt === 'true') {
  20881. // Windows hates the Mac TrueType sfnt version number
  20882. sfnt = string32(0x00010000);
  20883. }
  20884. file[0] = sfnt.charCodeAt(0) & 0xFF;
  20885. file[1] = sfnt.charCodeAt(1) & 0xFF;
  20886. file[2] = sfnt.charCodeAt(2) & 0xFF;
  20887. file[3] = sfnt.charCodeAt(3) & 0xFF;
  20888. // numTables (2 bytes)
  20889. writeInt16(file, 4, numTables);
  20890. var searchParams = OpenTypeFileBuilder.getSearchParams(numTables, 16);
  20891. // searchRange (2 bytes)
  20892. writeInt16(file, 6, searchParams.range);
  20893. // entrySelector (2 bytes)
  20894. writeInt16(file, 8, searchParams.entry);
  20895. // rangeShift (2 bytes)
  20896. writeInt16(file, 10, searchParams.rangeShift);
  20897. offset = OTF_HEADER_SIZE;
  20898. // writing table entries
  20899. for (i = 0; i < numTables; i++) {
  20900. tableName = tablesNames[i];
  20901. file[offset] = tableName.charCodeAt(0) & 0xFF;
  20902. file[offset + 1] = tableName.charCodeAt(1) & 0xFF;
  20903. file[offset + 2] = tableName.charCodeAt(2) & 0xFF;
  20904. file[offset + 3] = tableName.charCodeAt(3) & 0xFF;
  20905. // checksum
  20906. var checksum = 0;
  20907. for (j = tableOffsets[i], jj = tableOffsets[i + 1]; j < jj; j += 4) {
  20908. var quad = (file[j] << 24) + (file[j + 1] << 16) +
  20909. (file[j + 2] << 8) + file[j + 3];
  20910. checksum = (checksum + quad) | 0;
  20911. }
  20912. writeInt32(file, offset + 4, checksum);
  20913. // offset
  20914. writeInt32(file, offset + 8, tableOffsets[i]);
  20915. // length
  20916. writeInt32(file, offset + 12, tables[tableName].length);
  20917. offset += OTF_TABLE_ENTRY_SIZE;
  20918. }
  20919. return file;
  20920. },
  20921. addTable: function OpenTypeFileBuilder_addTable(tag, data) {
  20922. if (tag in this.tables) {
  20923. throw new Error('Table ' + tag + ' already exists');
  20924. }
  20925. this.tables[tag] = data;
  20926. }
  20927. };
  20928. return OpenTypeFileBuilder;
  20929. })();
  20930. /**
  20931. * 'Font' is the class the outside world should use, it encapsulate all the font
  20932. * decoding logics whatever type it is (assuming the font type is supported).
  20933. *
  20934. * For example to read a Type1 font and to attach it to the document:
  20935. * var type1Font = new Font("MyFontName", binaryFile, propertiesObject);
  20936. * type1Font.bind();
  20937. */
  20938. var Font = (function FontClosure() {
  20939. function Font(name, file, properties) {
  20940. var charCode, glyphName, fontChar;
  20941. this.name = name;
  20942. this.loadedName = properties.loadedName;
  20943. this.isType3Font = properties.isType3Font;
  20944. this.sizes = [];
  20945. this.glyphCache = {};
  20946. var names = name.split('+');
  20947. names = names.length > 1 ? names[1] : names[0];
  20948. names = names.split(/[-,_]/g)[0];
  20949. this.isSerifFont = !!(properties.flags & FontFlags.Serif);
  20950. this.isSymbolicFont = !!(properties.flags & FontFlags.Symbolic);
  20951. this.isMonospace = !!(properties.flags & FontFlags.FixedPitch);
  20952. var type = properties.type;
  20953. var subtype = properties.subtype;
  20954. this.type = type;
  20955. this.fallbackName = (this.isMonospace ? 'monospace' :
  20956. (this.isSerifFont ? 'serif' : 'sans-serif'));
  20957. this.differences = properties.differences;
  20958. this.widths = properties.widths;
  20959. this.defaultWidth = properties.defaultWidth;
  20960. this.composite = properties.composite;
  20961. this.wideChars = properties.wideChars;
  20962. this.cMap = properties.cMap;
  20963. this.ascent = properties.ascent / PDF_GLYPH_SPACE_UNITS;
  20964. this.descent = properties.descent / PDF_GLYPH_SPACE_UNITS;
  20965. this.fontMatrix = properties.fontMatrix;
  20966. this.bbox = properties.bbox;
  20967. this.toUnicode = properties.toUnicode = this.buildToUnicode(properties);
  20968. this.toFontChar = [];
  20969. if (properties.type === 'Type3') {
  20970. for (charCode = 0; charCode < 256; charCode++) {
  20971. this.toFontChar[charCode] = (this.differences[charCode] ||
  20972. properties.defaultEncoding[charCode]);
  20973. }
  20974. this.fontType = FontType.TYPE3;
  20975. return;
  20976. }
  20977. this.cidEncoding = properties.cidEncoding;
  20978. this.vertical = properties.vertical;
  20979. if (this.vertical) {
  20980. this.vmetrics = properties.vmetrics;
  20981. this.defaultVMetrics = properties.defaultVMetrics;
  20982. }
  20983. if (!file || file.isEmpty) {
  20984. if (file) {
  20985. // Some bad PDF generators will include empty font files,
  20986. // attempting to recover by assuming that no file exists.
  20987. warn('Font file is empty in "' + name + '" (' + this.loadedName + ')');
  20988. }
  20989. this.missingFile = true;
  20990. // The file data is not specified. Trying to fix the font name
  20991. // to be used with the canvas.font.
  20992. var fontName = name.replace(/[,_]/g, '-');
  20993. var isStandardFont = !!stdFontMap[fontName] ||
  20994. !!(nonStdFontMap[fontName] && stdFontMap[nonStdFontMap[fontName]]);
  20995. fontName = stdFontMap[fontName] || nonStdFontMap[fontName] || fontName;
  20996. this.bold = (fontName.search(/bold/gi) !== -1);
  20997. this.italic = ((fontName.search(/oblique/gi) !== -1) ||
  20998. (fontName.search(/italic/gi) !== -1));
  20999. // Use 'name' instead of 'fontName' here because the original
  21000. // name ArialBlack for example will be replaced by Helvetica.
  21001. this.black = (name.search(/Black/g) !== -1);
  21002. // if at least one width is present, remeasure all chars when exists
  21003. this.remeasure = Object.keys(this.widths).length > 0;
  21004. if (isStandardFont && type === 'CIDFontType2' &&
  21005. properties.cidEncoding.indexOf('Identity-') === 0) {
  21006. // Standard fonts might be embedded as CID font without glyph mapping.
  21007. // Building one based on GlyphMapForStandardFonts.
  21008. var map = [];
  21009. for (var code in GlyphMapForStandardFonts) {
  21010. map[+code] = GlyphMapForStandardFonts[code];
  21011. }
  21012. var isIdentityUnicode = this.toUnicode instanceof IdentityToUnicodeMap;
  21013. if (!isIdentityUnicode) {
  21014. this.toUnicode.forEach(function(charCode, unicodeCharCode) {
  21015. map[+charCode] = unicodeCharCode;
  21016. });
  21017. }
  21018. this.toFontChar = map;
  21019. this.toUnicode = new ToUnicodeMap(map);
  21020. } else if (/Symbol/i.test(fontName)) {
  21021. var symbols = Encodings.SymbolSetEncoding;
  21022. for (charCode in symbols) {
  21023. fontChar = GlyphsUnicode[symbols[charCode]];
  21024. if (!fontChar) {
  21025. continue;
  21026. }
  21027. this.toFontChar[charCode] = fontChar;
  21028. }
  21029. for (charCode in properties.differences) {
  21030. fontChar = GlyphsUnicode[properties.differences[charCode]];
  21031. if (!fontChar) {
  21032. continue;
  21033. }
  21034. this.toFontChar[charCode] = fontChar;
  21035. }
  21036. } else if (/Dingbats/i.test(fontName)) {
  21037. if (/Wingdings/i.test(name)) {
  21038. warn('Wingdings font without embedded font file, ' +
  21039. 'falling back to the ZapfDingbats encoding.');
  21040. }
  21041. var dingbats = Encodings.ZapfDingbatsEncoding;
  21042. for (charCode in dingbats) {
  21043. fontChar = DingbatsGlyphsUnicode[dingbats[charCode]];
  21044. if (!fontChar) {
  21045. continue;
  21046. }
  21047. this.toFontChar[charCode] = fontChar;
  21048. }
  21049. for (charCode in properties.differences) {
  21050. fontChar = DingbatsGlyphsUnicode[properties.differences[charCode]];
  21051. if (!fontChar) {
  21052. continue;
  21053. }
  21054. this.toFontChar[charCode] = fontChar;
  21055. }
  21056. } else if (isStandardFont) {
  21057. this.toFontChar = [];
  21058. for (charCode in properties.defaultEncoding) {
  21059. glyphName = (properties.differences[charCode] ||
  21060. properties.defaultEncoding[charCode]);
  21061. this.toFontChar[charCode] = GlyphsUnicode[glyphName];
  21062. }
  21063. } else {
  21064. var unicodeCharCode, notCidFont = (type.indexOf('CIDFontType') === -1);
  21065. this.toUnicode.forEach(function(charCode, unicodeCharCode) {
  21066. if (notCidFont) {
  21067. glyphName = (properties.differences[charCode] ||
  21068. properties.defaultEncoding[charCode]);
  21069. unicodeCharCode = (GlyphsUnicode[glyphName] || unicodeCharCode);
  21070. }
  21071. this.toFontChar[charCode] = unicodeCharCode;
  21072. }.bind(this));
  21073. }
  21074. this.loadedName = fontName.split('-')[0];
  21075. this.loading = false;
  21076. this.fontType = getFontType(type, subtype);
  21077. return;
  21078. }
  21079. // Some fonts might use wrong font types for Type1C or CIDFontType0C
  21080. if (subtype === 'Type1C' && (type !== 'Type1' && type !== 'MMType1')) {
  21081. // Some TrueType fonts by mistake claim Type1C
  21082. if (isTrueTypeFile(file)) {
  21083. subtype = 'TrueType';
  21084. } else {
  21085. type = 'Type1';
  21086. }
  21087. }
  21088. if (subtype === 'CIDFontType0C' && type !== 'CIDFontType0') {
  21089. type = 'CIDFontType0';
  21090. }
  21091. if (subtype === 'OpenType') {
  21092. type = 'OpenType';
  21093. }
  21094. // Some CIDFontType0C fonts by mistake claim CIDFontType0.
  21095. if (type === 'CIDFontType0') {
  21096. subtype = isType1File(file) ? 'CIDFontType0' : 'CIDFontType0C';
  21097. }
  21098. var data;
  21099. switch (type) {
  21100. case 'MMType1':
  21101. info('MMType1 font (' + name + '), falling back to Type1.');
  21102. /* falls through */
  21103. case 'Type1':
  21104. case 'CIDFontType0':
  21105. this.mimetype = 'font/opentype';
  21106. var cff = (subtype === 'Type1C' || subtype === 'CIDFontType0C') ?
  21107. new CFFFont(file, properties) : new Type1Font(name, file, properties);
  21108. adjustWidths(properties);
  21109. // Wrap the CFF data inside an OTF font file
  21110. data = this.convert(name, cff, properties);
  21111. break;
  21112. case 'OpenType':
  21113. case 'TrueType':
  21114. case 'CIDFontType2':
  21115. this.mimetype = 'font/opentype';
  21116. // Repair the TrueType file. It is can be damaged in the point of
  21117. // view of the sanitizer
  21118. data = this.checkAndRepair(name, file, properties);
  21119. if (this.isOpenType) {
  21120. type = 'OpenType';
  21121. }
  21122. break;
  21123. default:
  21124. error('Font ' + type + ' is not supported');
  21125. break;
  21126. }
  21127. this.data = data;
  21128. this.fontType = getFontType(type, subtype);
  21129. // Transfer some properties again that could change during font conversion
  21130. this.fontMatrix = properties.fontMatrix;
  21131. this.widths = properties.widths;
  21132. this.defaultWidth = properties.defaultWidth;
  21133. this.encoding = properties.baseEncoding;
  21134. this.seacMap = properties.seacMap;
  21135. this.loading = true;
  21136. }
  21137. Font.getFontID = (function () {
  21138. var ID = 1;
  21139. return function Font_getFontID() {
  21140. return String(ID++);
  21141. };
  21142. })();
  21143. function int16(b0, b1) {
  21144. return (b0 << 8) + b1;
  21145. }
  21146. function int32(b0, b1, b2, b3) {
  21147. return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;
  21148. }
  21149. function string16(value) {
  21150. return String.fromCharCode((value >> 8) & 0xff, value & 0xff);
  21151. }
  21152. function safeString16(value) {
  21153. // clamp value to the 16-bit int range
  21154. value = (value > 0x7FFF ? 0x7FFF : (value < -0x8000 ? -0x8000 : value));
  21155. return String.fromCharCode((value >> 8) & 0xff, value & 0xff);
  21156. }
  21157. function isTrueTypeFile(file) {
  21158. var header = file.peekBytes(4);
  21159. return readUint32(header, 0) === 0x00010000;
  21160. }
  21161. function isType1File(file) {
  21162. var header = file.peekBytes(2);
  21163. // All Type1 font programs must begin with the comment '%!' (0x25 + 0x21).
  21164. if (header[0] === 0x25 && header[1] === 0x21) {
  21165. return true;
  21166. }
  21167. // ... obviously some fonts violate that part of the specification,
  21168. // please refer to the comment in |Type1Font| below.
  21169. if (header[0] === 0x80 && header[1] === 0x01) { // pfb file header.
  21170. return true;
  21171. }
  21172. return false;
  21173. }
  21174. /**
  21175. * Helper function for |adjustMapping|.
  21176. * @return {boolean}
  21177. */
  21178. function isProblematicUnicodeLocation(code) {
  21179. if (code <= 0x1F) { // Control chars
  21180. return true;
  21181. }
  21182. if (code >= 0x80 && code <= 0x9F) { // Control chars
  21183. return true;
  21184. }
  21185. if ((code >= 0x2000 && code <= 0x200F) || // General punctuation chars
  21186. (code >= 0x2028 && code <= 0x202F) ||
  21187. (code >= 0x2060 && code <= 0x206F)) {
  21188. return true;
  21189. }
  21190. if (code >= 0xFFF0 && code <= 0xFFFF) { // Specials Unicode block
  21191. return true;
  21192. }
  21193. switch (code) {
  21194. case 0x7F: // Control char
  21195. case 0xA0: // Non breaking space
  21196. case 0xAD: // Soft hyphen
  21197. case 0x2011: // Non breaking hyphen
  21198. case 0x205F: // Medium mathematical space
  21199. case 0x25CC: // Dotted circle (combining mark)
  21200. return true;
  21201. }
  21202. if ((code & ~0xFF) === 0x0E00) { // Thai/Lao chars (with combining mark)
  21203. return true;
  21204. }
  21205. return false;
  21206. }
  21207. /**
  21208. * Rebuilds the char code to glyph ID map by trying to replace the char codes
  21209. * with their unicode value. It also moves char codes that are in known
  21210. * problematic locations.
  21211. * @return {Object} Two properties:
  21212. * 'toFontChar' - maps original char codes(the value that will be read
  21213. * from commands such as show text) to the char codes that will be used in the
  21214. * font that we build
  21215. * 'charCodeToGlyphId' - maps the new font char codes to glyph ids
  21216. */
  21217. function adjustMapping(charCodeToGlyphId, properties) {
  21218. var toUnicode = properties.toUnicode;
  21219. var isSymbolic = !!(properties.flags & FontFlags.Symbolic);
  21220. var isIdentityUnicode =
  21221. properties.toUnicode instanceof IdentityToUnicodeMap;
  21222. var newMap = Object.create(null);
  21223. var toFontChar = [];
  21224. var usedFontCharCodes = [];
  21225. var nextAvailableFontCharCode = PRIVATE_USE_OFFSET_START;
  21226. for (var originalCharCode in charCodeToGlyphId) {
  21227. originalCharCode |= 0;
  21228. var glyphId = charCodeToGlyphId[originalCharCode];
  21229. var fontCharCode = originalCharCode;
  21230. // First try to map the value to a unicode position if a non identity map
  21231. // was created.
  21232. if (!isIdentityUnicode && toUnicode.has(originalCharCode)) {
  21233. var unicode = toUnicode.get(fontCharCode);
  21234. // TODO: Try to map ligatures to the correct spot.
  21235. if (unicode.length === 1) {
  21236. fontCharCode = unicode.charCodeAt(0);
  21237. }
  21238. }
  21239. // Try to move control characters, special characters and already mapped
  21240. // characters to the private use area since they will not be drawn by
  21241. // canvas if left in their current position. Also, move characters if the
  21242. // font was symbolic and there is only an identity unicode map since the
  21243. // characters probably aren't in the correct position (fixes an issue
  21244. // with firefox and thuluthfont).
  21245. if ((usedFontCharCodes[fontCharCode] !== undefined ||
  21246. isProblematicUnicodeLocation(fontCharCode) ||
  21247. (isSymbolic && isIdentityUnicode)) &&
  21248. nextAvailableFontCharCode <= PRIVATE_USE_OFFSET_END) { // Room left.
  21249. // Loop to try and find a free spot in the private use area.
  21250. do {
  21251. fontCharCode = nextAvailableFontCharCode++;
  21252. if (SKIP_PRIVATE_USE_RANGE_F000_TO_F01F && fontCharCode === 0xF000) {
  21253. fontCharCode = 0xF020;
  21254. nextAvailableFontCharCode = fontCharCode + 1;
  21255. }
  21256. } while (usedFontCharCodes[fontCharCode] !== undefined &&
  21257. nextAvailableFontCharCode <= PRIVATE_USE_OFFSET_END);
  21258. }
  21259. newMap[fontCharCode] = glyphId;
  21260. toFontChar[originalCharCode] = fontCharCode;
  21261. usedFontCharCodes[fontCharCode] = true;
  21262. }
  21263. return {
  21264. toFontChar: toFontChar,
  21265. charCodeToGlyphId: newMap,
  21266. nextAvailableFontCharCode: nextAvailableFontCharCode
  21267. };
  21268. }
  21269. function getRanges(glyphs) {
  21270. // Array.sort() sorts by characters, not numerically, so convert to an
  21271. // array of characters.
  21272. var codes = [];
  21273. for (var charCode in glyphs) {
  21274. codes.push({ fontCharCode: charCode | 0, glyphId: glyphs[charCode] });
  21275. }
  21276. codes.sort(function fontGetRangesSort(a, b) {
  21277. return a.fontCharCode - b.fontCharCode;
  21278. });
  21279. // Split the sorted codes into ranges.
  21280. var ranges = [];
  21281. var length = codes.length;
  21282. for (var n = 0; n < length; ) {
  21283. var start = codes[n].fontCharCode;
  21284. var codeIndices = [codes[n].glyphId];
  21285. ++n;
  21286. var end = start;
  21287. while (n < length && end + 1 === codes[n].fontCharCode) {
  21288. codeIndices.push(codes[n].glyphId);
  21289. ++end;
  21290. ++n;
  21291. if (end === 0xFFFF) {
  21292. break;
  21293. }
  21294. }
  21295. ranges.push([start, end, codeIndices]);
  21296. }
  21297. return ranges;
  21298. }
  21299. function createCmapTable(glyphs) {
  21300. var ranges = getRanges(glyphs);
  21301. var numTables = ranges[ranges.length - 1][1] > 0xFFFF ? 2 : 1;
  21302. var cmap = '\x00\x00' + // version
  21303. string16(numTables) + // numTables
  21304. '\x00\x03' + // platformID
  21305. '\x00\x01' + // encodingID
  21306. string32(4 + numTables * 8); // start of the table record
  21307. var i, ii, j, jj;
  21308. for (i = ranges.length - 1; i >= 0; --i) {
  21309. if (ranges[i][0] <= 0xFFFF) { break; }
  21310. }
  21311. var bmpLength = i + 1;
  21312. if (ranges[i][0] < 0xFFFF && ranges[i][1] === 0xFFFF) {
  21313. ranges[i][1] = 0xFFFE;
  21314. }
  21315. var trailingRangesCount = ranges[i][1] < 0xFFFF ? 1 : 0;
  21316. var segCount = bmpLength + trailingRangesCount;
  21317. var searchParams = OpenTypeFileBuilder.getSearchParams(segCount, 2);
  21318. // Fill up the 4 parallel arrays describing the segments.
  21319. var startCount = '';
  21320. var endCount = '';
  21321. var idDeltas = '';
  21322. var idRangeOffsets = '';
  21323. var glyphsIds = '';
  21324. var bias = 0;
  21325. var range, start, end, codes;
  21326. for (i = 0, ii = bmpLength; i < ii; i++) {
  21327. range = ranges[i];
  21328. start = range[0];
  21329. end = range[1];
  21330. startCount += string16(start);
  21331. endCount += string16(end);
  21332. codes = range[2];
  21333. var contiguous = true;
  21334. for (j = 1, jj = codes.length; j < jj; ++j) {
  21335. if (codes[j] !== codes[j - 1] + 1) {
  21336. contiguous = false;
  21337. break;
  21338. }
  21339. }
  21340. if (!contiguous) {
  21341. var offset = (segCount - i) * 2 + bias * 2;
  21342. bias += (end - start + 1);
  21343. idDeltas += string16(0);
  21344. idRangeOffsets += string16(offset);
  21345. for (j = 0, jj = codes.length; j < jj; ++j) {
  21346. glyphsIds += string16(codes[j]);
  21347. }
  21348. } else {
  21349. var startCode = codes[0];
  21350. idDeltas += string16((startCode - start) & 0xFFFF);
  21351. idRangeOffsets += string16(0);
  21352. }
  21353. }
  21354. if (trailingRangesCount > 0) {
  21355. endCount += '\xFF\xFF';
  21356. startCount += '\xFF\xFF';
  21357. idDeltas += '\x00\x01';
  21358. idRangeOffsets += '\x00\x00';
  21359. }
  21360. var format314 = '\x00\x00' + // language
  21361. string16(2 * segCount) +
  21362. string16(searchParams.range) +
  21363. string16(searchParams.entry) +
  21364. string16(searchParams.rangeShift) +
  21365. endCount + '\x00\x00' + startCount +
  21366. idDeltas + idRangeOffsets + glyphsIds;
  21367. var format31012 = '';
  21368. var header31012 = '';
  21369. if (numTables > 1) {
  21370. cmap += '\x00\x03' + // platformID
  21371. '\x00\x0A' + // encodingID
  21372. string32(4 + numTables * 8 +
  21373. 4 + format314.length); // start of the table record
  21374. format31012 = '';
  21375. for (i = 0, ii = ranges.length; i < ii; i++) {
  21376. range = ranges[i];
  21377. start = range[0];
  21378. codes = range[2];
  21379. var code = codes[0];
  21380. for (j = 1, jj = codes.length; j < jj; ++j) {
  21381. if (codes[j] !== codes[j - 1] + 1) {
  21382. end = range[0] + j - 1;
  21383. format31012 += string32(start) + // startCharCode
  21384. string32(end) + // endCharCode
  21385. string32(code); // startGlyphID
  21386. start = end + 1;
  21387. code = codes[j];
  21388. }
  21389. }
  21390. format31012 += string32(start) + // startCharCode
  21391. string32(range[1]) + // endCharCode
  21392. string32(code); // startGlyphID
  21393. }
  21394. header31012 = '\x00\x0C' + // format
  21395. '\x00\x00' + // reserved
  21396. string32(format31012.length + 16) + // length
  21397. '\x00\x00\x00\x00' + // language
  21398. string32(format31012.length / 12); // nGroups
  21399. }
  21400. return cmap + '\x00\x04' + // format
  21401. string16(format314.length + 4) + // length
  21402. format314 + header31012 + format31012;
  21403. }
  21404. function validateOS2Table(os2) {
  21405. var stream = new Stream(os2.data);
  21406. var version = stream.getUint16();
  21407. // TODO verify all OS/2 tables fields, but currently we validate only those
  21408. // that give us issues
  21409. stream.getBytes(60); // skipping type, misc sizes, panose, unicode ranges
  21410. var selection = stream.getUint16();
  21411. if (version < 4 && (selection & 0x0300)) {
  21412. return false;
  21413. }
  21414. var firstChar = stream.getUint16();
  21415. var lastChar = stream.getUint16();
  21416. if (firstChar > lastChar) {
  21417. return false;
  21418. }
  21419. stream.getBytes(6); // skipping sTypoAscender/Descender/LineGap
  21420. var usWinAscent = stream.getUint16();
  21421. if (usWinAscent === 0) { // makes font unreadable by windows
  21422. return false;
  21423. }
  21424. // OS/2 appears to be valid, resetting some fields
  21425. os2.data[8] = os2.data[9] = 0; // IE rejects fonts if fsType != 0
  21426. return true;
  21427. }
  21428. function createOS2Table(properties, charstrings, override) {
  21429. override = override || {
  21430. unitsPerEm: 0,
  21431. yMax: 0,
  21432. yMin: 0,
  21433. ascent: 0,
  21434. descent: 0
  21435. };
  21436. var ulUnicodeRange1 = 0;
  21437. var ulUnicodeRange2 = 0;
  21438. var ulUnicodeRange3 = 0;
  21439. var ulUnicodeRange4 = 0;
  21440. var firstCharIndex = null;
  21441. var lastCharIndex = 0;
  21442. if (charstrings) {
  21443. for (var code in charstrings) {
  21444. code |= 0;
  21445. if (firstCharIndex > code || !firstCharIndex) {
  21446. firstCharIndex = code;
  21447. }
  21448. if (lastCharIndex < code) {
  21449. lastCharIndex = code;
  21450. }
  21451. var position = getUnicodeRangeFor(code);
  21452. if (position < 32) {
  21453. ulUnicodeRange1 |= 1 << position;
  21454. } else if (position < 64) {
  21455. ulUnicodeRange2 |= 1 << position - 32;
  21456. } else if (position < 96) {
  21457. ulUnicodeRange3 |= 1 << position - 64;
  21458. } else if (position < 123) {
  21459. ulUnicodeRange4 |= 1 << position - 96;
  21460. } else {
  21461. error('Unicode ranges Bits > 123 are reserved for internal usage');
  21462. }
  21463. }
  21464. } else {
  21465. // TODO
  21466. firstCharIndex = 0;
  21467. lastCharIndex = 255;
  21468. }
  21469. var bbox = properties.bbox || [0, 0, 0, 0];
  21470. var unitsPerEm = (override.unitsPerEm ||
  21471. 1 / (properties.fontMatrix || FONT_IDENTITY_MATRIX)[0]);
  21472. // if the font units differ to the PDF glyph space units
  21473. // then scale up the values
  21474. var scale = (properties.ascentScaled ? 1.0 :
  21475. unitsPerEm / PDF_GLYPH_SPACE_UNITS);
  21476. var typoAscent = (override.ascent ||
  21477. Math.round(scale * (properties.ascent || bbox[3])));
  21478. var typoDescent = (override.descent ||
  21479. Math.round(scale * (properties.descent || bbox[1])));
  21480. if (typoDescent > 0 && properties.descent > 0 && bbox[1] < 0) {
  21481. typoDescent = -typoDescent; // fixing incorrect descent
  21482. }
  21483. var winAscent = override.yMax || typoAscent;
  21484. var winDescent = -override.yMin || -typoDescent;
  21485. return '\x00\x03' + // version
  21486. '\x02\x24' + // xAvgCharWidth
  21487. '\x01\xF4' + // usWeightClass
  21488. '\x00\x05' + // usWidthClass
  21489. '\x00\x00' + // fstype (0 to let the font loads via font-face on IE)
  21490. '\x02\x8A' + // ySubscriptXSize
  21491. '\x02\xBB' + // ySubscriptYSize
  21492. '\x00\x00' + // ySubscriptXOffset
  21493. '\x00\x8C' + // ySubscriptYOffset
  21494. '\x02\x8A' + // ySuperScriptXSize
  21495. '\x02\xBB' + // ySuperScriptYSize
  21496. '\x00\x00' + // ySuperScriptXOffset
  21497. '\x01\xDF' + // ySuperScriptYOffset
  21498. '\x00\x31' + // yStrikeOutSize
  21499. '\x01\x02' + // yStrikeOutPosition
  21500. '\x00\x00' + // sFamilyClass
  21501. '\x00\x00\x06' +
  21502. String.fromCharCode(properties.fixedPitch ? 0x09 : 0x00) +
  21503. '\x00\x00\x00\x00\x00\x00' + // Panose
  21504. string32(ulUnicodeRange1) + // ulUnicodeRange1 (Bits 0-31)
  21505. string32(ulUnicodeRange2) + // ulUnicodeRange2 (Bits 32-63)
  21506. string32(ulUnicodeRange3) + // ulUnicodeRange3 (Bits 64-95)
  21507. string32(ulUnicodeRange4) + // ulUnicodeRange4 (Bits 96-127)
  21508. '\x2A\x32\x31\x2A' + // achVendID
  21509. string16(properties.italicAngle ? 1 : 0) + // fsSelection
  21510. string16(firstCharIndex ||
  21511. properties.firstChar) + // usFirstCharIndex
  21512. string16(lastCharIndex || properties.lastChar) + // usLastCharIndex
  21513. string16(typoAscent) + // sTypoAscender
  21514. string16(typoDescent) + // sTypoDescender
  21515. '\x00\x64' + // sTypoLineGap (7%-10% of the unitsPerEM value)
  21516. string16(winAscent) + // usWinAscent
  21517. string16(winDescent) + // usWinDescent
  21518. '\x00\x00\x00\x00' + // ulCodePageRange1 (Bits 0-31)
  21519. '\x00\x00\x00\x00' + // ulCodePageRange2 (Bits 32-63)
  21520. string16(properties.xHeight) + // sxHeight
  21521. string16(properties.capHeight) + // sCapHeight
  21522. string16(0) + // usDefaultChar
  21523. string16(firstCharIndex || properties.firstChar) + // usBreakChar
  21524. '\x00\x03'; // usMaxContext
  21525. }
  21526. function createPostTable(properties) {
  21527. var angle = Math.floor(properties.italicAngle * (Math.pow(2, 16)));
  21528. return ('\x00\x03\x00\x00' + // Version number
  21529. string32(angle) + // italicAngle
  21530. '\x00\x00' + // underlinePosition
  21531. '\x00\x00' + // underlineThickness
  21532. string32(properties.fixedPitch) + // isFixedPitch
  21533. '\x00\x00\x00\x00' + // minMemType42
  21534. '\x00\x00\x00\x00' + // maxMemType42
  21535. '\x00\x00\x00\x00' + // minMemType1
  21536. '\x00\x00\x00\x00'); // maxMemType1
  21537. }
  21538. function createNameTable(name, proto) {
  21539. if (!proto) {
  21540. proto = [[], []]; // no strings and unicode strings
  21541. }
  21542. var strings = [
  21543. proto[0][0] || 'Original licence', // 0.Copyright
  21544. proto[0][1] || name, // 1.Font family
  21545. proto[0][2] || 'Unknown', // 2.Font subfamily (font weight)
  21546. proto[0][3] || 'uniqueID', // 3.Unique ID
  21547. proto[0][4] || name, // 4.Full font name
  21548. proto[0][5] || 'Version 0.11', // 5.Version
  21549. proto[0][6] || '', // 6.Postscript name
  21550. proto[0][7] || 'Unknown', // 7.Trademark
  21551. proto[0][8] || 'Unknown', // 8.Manufacturer
  21552. proto[0][9] || 'Unknown' // 9.Designer
  21553. ];
  21554. // Mac want 1-byte per character strings while Windows want
  21555. // 2-bytes per character, so duplicate the names table
  21556. var stringsUnicode = [];
  21557. var i, ii, j, jj, str;
  21558. for (i = 0, ii = strings.length; i < ii; i++) {
  21559. str = proto[1][i] || strings[i];
  21560. var strBufUnicode = [];
  21561. for (j = 0, jj = str.length; j < jj; j++) {
  21562. strBufUnicode.push(string16(str.charCodeAt(j)));
  21563. }
  21564. stringsUnicode.push(strBufUnicode.join(''));
  21565. }
  21566. var names = [strings, stringsUnicode];
  21567. var platforms = ['\x00\x01', '\x00\x03'];
  21568. var encodings = ['\x00\x00', '\x00\x01'];
  21569. var languages = ['\x00\x00', '\x04\x09'];
  21570. var namesRecordCount = strings.length * platforms.length;
  21571. var nameTable =
  21572. '\x00\x00' + // format
  21573. string16(namesRecordCount) + // Number of names Record
  21574. string16(namesRecordCount * 12 + 6); // Storage
  21575. // Build the name records field
  21576. var strOffset = 0;
  21577. for (i = 0, ii = platforms.length; i < ii; i++) {
  21578. var strs = names[i];
  21579. for (j = 0, jj = strs.length; j < jj; j++) {
  21580. str = strs[j];
  21581. var nameRecord =
  21582. platforms[i] + // platform ID
  21583. encodings[i] + // encoding ID
  21584. languages[i] + // language ID
  21585. string16(j) + // name ID
  21586. string16(str.length) +
  21587. string16(strOffset);
  21588. nameTable += nameRecord;
  21589. strOffset += str.length;
  21590. }
  21591. }
  21592. nameTable += strings.join('') + stringsUnicode.join('');
  21593. return nameTable;
  21594. }
  21595. Font.prototype = {
  21596. name: null,
  21597. font: null,
  21598. mimetype: null,
  21599. encoding: null,
  21600. get renderer() {
  21601. var renderer = FontRendererFactory.create(this);
  21602. return shadow(this, 'renderer', renderer);
  21603. },
  21604. exportData: function Font_exportData() {
  21605. var data = {};
  21606. for (var i in this) {
  21607. if (this.hasOwnProperty(i)) {
  21608. data[i] = this[i];
  21609. }
  21610. }
  21611. return data;
  21612. },
  21613. checkAndRepair: function Font_checkAndRepair(name, font, properties) {
  21614. function readTableEntry(file) {
  21615. var tag = bytesToString(file.getBytes(4));
  21616. var checksum = file.getInt32();
  21617. var offset = file.getInt32() >>> 0;
  21618. var length = file.getInt32() >>> 0;
  21619. // Read the table associated data
  21620. var previousPosition = file.pos;
  21621. file.pos = file.start ? file.start : 0;
  21622. file.skip(offset);
  21623. var data = file.getBytes(length);
  21624. file.pos = previousPosition;
  21625. if (tag === 'head') {
  21626. // clearing checksum adjustment
  21627. data[8] = data[9] = data[10] = data[11] = 0;
  21628. data[17] |= 0x20; //Set font optimized for cleartype flag
  21629. }
  21630. return {
  21631. tag: tag,
  21632. checksum: checksum,
  21633. length: length,
  21634. offset: offset,
  21635. data: data
  21636. };
  21637. }
  21638. function readOpenTypeHeader(ttf) {
  21639. return {
  21640. version: bytesToString(ttf.getBytes(4)),
  21641. numTables: ttf.getUint16(),
  21642. searchRange: ttf.getUint16(),
  21643. entrySelector: ttf.getUint16(),
  21644. rangeShift: ttf.getUint16()
  21645. };
  21646. }
  21647. /**
  21648. * Read the appropriate subtable from the cmap according to 9.6.6.4 from
  21649. * PDF spec
  21650. */
  21651. function readCmapTable(cmap, font, isSymbolicFont) {
  21652. var segment;
  21653. var start = (font.start ? font.start : 0) + cmap.offset;
  21654. font.pos = start;
  21655. var version = font.getUint16();
  21656. var numTables = font.getUint16();
  21657. var potentialTable;
  21658. var canBreak = false;
  21659. // There's an order of preference in terms of which cmap subtable to
  21660. // use:
  21661. // - non-symbolic fonts the preference is a 3,1 table then a 1,0 table
  21662. // - symbolic fonts the preference is a 3,0 table then a 1,0 table
  21663. // The following takes advantage of the fact that the tables are sorted
  21664. // to work.
  21665. for (var i = 0; i < numTables; i++) {
  21666. var platformId = font.getUint16();
  21667. var encodingId = font.getUint16();
  21668. var offset = font.getInt32() >>> 0;
  21669. var useTable = false;
  21670. if (platformId === 0 && encodingId === 0) {
  21671. useTable = true;
  21672. // Continue the loop since there still may be a higher priority
  21673. // table.
  21674. } else if (platformId === 1 && encodingId === 0) {
  21675. useTable = true;
  21676. // Continue the loop since there still may be a higher priority
  21677. // table.
  21678. } else if (platformId === 3 && encodingId === 1 &&
  21679. (!isSymbolicFont || !potentialTable)) {
  21680. useTable = true;
  21681. if (!isSymbolicFont) {
  21682. canBreak = true;
  21683. }
  21684. } else if (isSymbolicFont && platformId === 3 && encodingId === 0) {
  21685. useTable = true;
  21686. canBreak = true;
  21687. }
  21688. if (useTable) {
  21689. potentialTable = {
  21690. platformId: platformId,
  21691. encodingId: encodingId,
  21692. offset: offset
  21693. };
  21694. }
  21695. if (canBreak) {
  21696. break;
  21697. }
  21698. }
  21699. if (potentialTable) {
  21700. font.pos = start + potentialTable.offset;
  21701. }
  21702. if (!potentialTable || font.peekByte() === -1) {
  21703. warn('Could not find a preferred cmap table.');
  21704. return {
  21705. platformId: -1,
  21706. encodingId: -1,
  21707. mappings: [],
  21708. hasShortCmap: false
  21709. };
  21710. }
  21711. var format = font.getUint16();
  21712. var length = font.getUint16();
  21713. var language = font.getUint16();
  21714. var hasShortCmap = false;
  21715. var mappings = [];
  21716. var j, glyphId;
  21717. // TODO(mack): refactor this cmap subtable reading logic out
  21718. if (format === 0) {
  21719. for (j = 0; j < 256; j++) {
  21720. var index = font.getByte();
  21721. if (!index) {
  21722. continue;
  21723. }
  21724. mappings.push({
  21725. charCode: j,
  21726. glyphId: index
  21727. });
  21728. }
  21729. hasShortCmap = true;
  21730. } else if (format === 4) {
  21731. // re-creating the table in format 4 since the encoding
  21732. // might be changed
  21733. var segCount = (font.getUint16() >> 1);
  21734. font.getBytes(6); // skipping range fields
  21735. var segIndex, segments = [];
  21736. for (segIndex = 0; segIndex < segCount; segIndex++) {
  21737. segments.push({ end: font.getUint16() });
  21738. }
  21739. font.getUint16();
  21740. for (segIndex = 0; segIndex < segCount; segIndex++) {
  21741. segments[segIndex].start = font.getUint16();
  21742. }
  21743. for (segIndex = 0; segIndex < segCount; segIndex++) {
  21744. segments[segIndex].delta = font.getUint16();
  21745. }
  21746. var offsetsCount = 0;
  21747. for (segIndex = 0; segIndex < segCount; segIndex++) {
  21748. segment = segments[segIndex];
  21749. var rangeOffset = font.getUint16();
  21750. if (!rangeOffset) {
  21751. segment.offsetIndex = -1;
  21752. continue;
  21753. }
  21754. var offsetIndex = (rangeOffset >> 1) - (segCount - segIndex);
  21755. segment.offsetIndex = offsetIndex;
  21756. offsetsCount = Math.max(offsetsCount, offsetIndex +
  21757. segment.end - segment.start + 1);
  21758. }
  21759. var offsets = [];
  21760. for (j = 0; j < offsetsCount; j++) {
  21761. offsets.push(font.getUint16());
  21762. }
  21763. for (segIndex = 0; segIndex < segCount; segIndex++) {
  21764. segment = segments[segIndex];
  21765. start = segment.start;
  21766. var end = segment.end;
  21767. var delta = segment.delta;
  21768. offsetIndex = segment.offsetIndex;
  21769. for (j = start; j <= end; j++) {
  21770. if (j === 0xFFFF) {
  21771. continue;
  21772. }
  21773. glyphId = (offsetIndex < 0 ?
  21774. j : offsets[offsetIndex + j - start]);
  21775. glyphId = (glyphId + delta) & 0xFFFF;
  21776. if (glyphId === 0) {
  21777. continue;
  21778. }
  21779. mappings.push({
  21780. charCode: j,
  21781. glyphId: glyphId
  21782. });
  21783. }
  21784. }
  21785. } else if (format === 6) {
  21786. // Format 6 is a 2-bytes dense mapping, which means the font data
  21787. // lives glue together even if they are pretty far in the unicode
  21788. // table. (This looks weird, so I can have missed something), this
  21789. // works on Linux but seems to fails on Mac so let's rewrite the
  21790. // cmap table to a 3-1-4 style
  21791. var firstCode = font.getUint16();
  21792. var entryCount = font.getUint16();
  21793. for (j = 0; j < entryCount; j++) {
  21794. glyphId = font.getUint16();
  21795. var charCode = firstCode + j;
  21796. mappings.push({
  21797. charCode: charCode,
  21798. glyphId: glyphId
  21799. });
  21800. }
  21801. } else {
  21802. error('cmap table has unsupported format: ' + format);
  21803. }
  21804. // removing duplicate entries
  21805. mappings.sort(function (a, b) {
  21806. return a.charCode - b.charCode;
  21807. });
  21808. for (i = 1; i < mappings.length; i++) {
  21809. if (mappings[i - 1].charCode === mappings[i].charCode) {
  21810. mappings.splice(i, 1);
  21811. i--;
  21812. }
  21813. }
  21814. return {
  21815. platformId: potentialTable.platformId,
  21816. encodingId: potentialTable.encodingId,
  21817. mappings: mappings,
  21818. hasShortCmap: hasShortCmap
  21819. };
  21820. }
  21821. function sanitizeMetrics(font, header, metrics, numGlyphs) {
  21822. if (!header) {
  21823. if (metrics) {
  21824. metrics.data = null;
  21825. }
  21826. return;
  21827. }
  21828. font.pos = (font.start ? font.start : 0) + header.offset;
  21829. font.pos += header.length - 2;
  21830. var numOfMetrics = font.getUint16();
  21831. if (numOfMetrics > numGlyphs) {
  21832. info('The numOfMetrics (' + numOfMetrics + ') should not be ' +
  21833. 'greater than the numGlyphs (' + numGlyphs + ')');
  21834. // Reduce numOfMetrics if it is greater than numGlyphs
  21835. numOfMetrics = numGlyphs;
  21836. header.data[34] = (numOfMetrics & 0xff00) >> 8;
  21837. header.data[35] = numOfMetrics & 0x00ff;
  21838. }
  21839. var numOfSidebearings = numGlyphs - numOfMetrics;
  21840. var numMissing = numOfSidebearings -
  21841. ((metrics.length - numOfMetrics * 4) >> 1);
  21842. if (numMissing > 0) {
  21843. // For each missing glyph, we set both the width and lsb to 0 (zero).
  21844. // Since we need to add two properties for each glyph, this explains
  21845. // the use of |numMissing * 2| when initializing the typed array.
  21846. var entries = new Uint8Array(metrics.length + numMissing * 2);
  21847. entries.set(metrics.data);
  21848. metrics.data = entries;
  21849. }
  21850. }
  21851. function sanitizeGlyph(source, sourceStart, sourceEnd, dest, destStart,
  21852. hintsValid) {
  21853. if (sourceEnd - sourceStart <= 12) {
  21854. // glyph with data less than 12 is invalid one
  21855. return 0;
  21856. }
  21857. var glyf = source.subarray(sourceStart, sourceEnd);
  21858. var contoursCount = (glyf[0] << 8) | glyf[1];
  21859. if (contoursCount & 0x8000) {
  21860. // complex glyph, writing as is
  21861. dest.set(glyf, destStart);
  21862. return glyf.length;
  21863. }
  21864. var i, j = 10, flagsCount = 0;
  21865. for (i = 0; i < contoursCount; i++) {
  21866. var endPoint = (glyf[j] << 8) | glyf[j + 1];
  21867. flagsCount = endPoint + 1;
  21868. j += 2;
  21869. }
  21870. // skipping instructions
  21871. var instructionsStart = j;
  21872. var instructionsLength = (glyf[j] << 8) | glyf[j + 1];
  21873. j += 2 + instructionsLength;
  21874. var instructionsEnd = j;
  21875. // validating flags
  21876. var coordinatesLength = 0;
  21877. for (i = 0; i < flagsCount; i++) {
  21878. var flag = glyf[j++];
  21879. if (flag & 0xC0) {
  21880. // reserved flags must be zero, cleaning up
  21881. glyf[j - 1] = flag & 0x3F;
  21882. }
  21883. var xyLength = ((flag & 2) ? 1 : (flag & 16) ? 0 : 2) +
  21884. ((flag & 4) ? 1 : (flag & 32) ? 0 : 2);
  21885. coordinatesLength += xyLength;
  21886. if (flag & 8) {
  21887. var repeat = glyf[j++];
  21888. i += repeat;
  21889. coordinatesLength += repeat * xyLength;
  21890. }
  21891. }
  21892. // glyph without coordinates will be rejected
  21893. if (coordinatesLength === 0) {
  21894. return 0;
  21895. }
  21896. var glyphDataLength = j + coordinatesLength;
  21897. if (glyphDataLength > glyf.length) {
  21898. // not enough data for coordinates
  21899. return 0;
  21900. }
  21901. if (!hintsValid && instructionsLength > 0) {
  21902. dest.set(glyf.subarray(0, instructionsStart), destStart);
  21903. dest.set([0, 0], destStart + instructionsStart);
  21904. dest.set(glyf.subarray(instructionsEnd, glyphDataLength),
  21905. destStart + instructionsStart + 2);
  21906. glyphDataLength -= instructionsLength;
  21907. if (glyf.length - glyphDataLength > 3) {
  21908. glyphDataLength = (glyphDataLength + 3) & ~3;
  21909. }
  21910. return glyphDataLength;
  21911. }
  21912. if (glyf.length - glyphDataLength > 3) {
  21913. // truncating and aligning to 4 bytes the long glyph data
  21914. glyphDataLength = (glyphDataLength + 3) & ~3;
  21915. dest.set(glyf.subarray(0, glyphDataLength), destStart);
  21916. return glyphDataLength;
  21917. }
  21918. // glyph data is fine
  21919. dest.set(glyf, destStart);
  21920. return glyf.length;
  21921. }
  21922. function sanitizeHead(head, numGlyphs, locaLength) {
  21923. var data = head.data;
  21924. // Validate version:
  21925. // Should always be 0x00010000
  21926. var version = int32(data[0], data[1], data[2], data[3]);
  21927. if (version >> 16 !== 1) {
  21928. info('Attempting to fix invalid version in head table: ' + version);
  21929. data[0] = 0;
  21930. data[1] = 1;
  21931. data[2] = 0;
  21932. data[3] = 0;
  21933. }
  21934. var indexToLocFormat = int16(data[50], data[51]);
  21935. if (indexToLocFormat < 0 || indexToLocFormat > 1) {
  21936. info('Attempting to fix invalid indexToLocFormat in head table: ' +
  21937. indexToLocFormat);
  21938. // The value of indexToLocFormat should be 0 if the loca table
  21939. // consists of short offsets, and should be 1 if the loca table
  21940. // consists of long offsets.
  21941. //
  21942. // The number of entries in the loca table should be numGlyphs + 1.
  21943. //
  21944. // Using this information, we can work backwards to deduce if the
  21945. // size of each offset in the loca table, and thus figure out the
  21946. // appropriate value for indexToLocFormat.
  21947. var numGlyphsPlusOne = numGlyphs + 1;
  21948. if (locaLength === numGlyphsPlusOne << 1) {
  21949. // 0x0000 indicates the loca table consists of short offsets
  21950. data[50] = 0;
  21951. data[51] = 0;
  21952. } else if (locaLength === numGlyphsPlusOne << 2) {
  21953. // 0x0001 indicates the loca table consists of long offsets
  21954. data[50] = 0;
  21955. data[51] = 1;
  21956. } else {
  21957. warn('Could not fix indexToLocFormat: ' + indexToLocFormat);
  21958. }
  21959. }
  21960. }
  21961. function sanitizeGlyphLocations(loca, glyf, numGlyphs,
  21962. isGlyphLocationsLong, hintsValid,
  21963. dupFirstEntry) {
  21964. var itemSize, itemDecode, itemEncode;
  21965. if (isGlyphLocationsLong) {
  21966. itemSize = 4;
  21967. itemDecode = function fontItemDecodeLong(data, offset) {
  21968. return (data[offset] << 24) | (data[offset + 1] << 16) |
  21969. (data[offset + 2] << 8) | data[offset + 3];
  21970. };
  21971. itemEncode = function fontItemEncodeLong(data, offset, value) {
  21972. data[offset] = (value >>> 24) & 0xFF;
  21973. data[offset + 1] = (value >> 16) & 0xFF;
  21974. data[offset + 2] = (value >> 8) & 0xFF;
  21975. data[offset + 3] = value & 0xFF;
  21976. };
  21977. } else {
  21978. itemSize = 2;
  21979. itemDecode = function fontItemDecode(data, offset) {
  21980. return (data[offset] << 9) | (data[offset + 1] << 1);
  21981. };
  21982. itemEncode = function fontItemEncode(data, offset, value) {
  21983. data[offset] = (value >> 9) & 0xFF;
  21984. data[offset + 1] = (value >> 1) & 0xFF;
  21985. };
  21986. }
  21987. var locaData = loca.data;
  21988. var locaDataSize = itemSize * (1 + numGlyphs);
  21989. // is loca.data too short or long?
  21990. if (locaData.length !== locaDataSize) {
  21991. locaData = new Uint8Array(locaDataSize);
  21992. locaData.set(loca.data.subarray(0, locaDataSize));
  21993. loca.data = locaData;
  21994. }
  21995. // removing the invalid glyphs
  21996. var oldGlyfData = glyf.data;
  21997. var oldGlyfDataLength = oldGlyfData.length;
  21998. var newGlyfData = new Uint8Array(oldGlyfDataLength);
  21999. var startOffset = itemDecode(locaData, 0);
  22000. var writeOffset = 0;
  22001. var missingGlyphData = {};
  22002. itemEncode(locaData, 0, writeOffset);
  22003. var i, j;
  22004. for (i = 0, j = itemSize; i < numGlyphs; i++, j += itemSize) {
  22005. var endOffset = itemDecode(locaData, j);
  22006. if (endOffset > oldGlyfDataLength &&
  22007. ((oldGlyfDataLength + 3) & ~3) === endOffset) {
  22008. // Aspose breaks fonts by aligning the glyphs to the qword, but not
  22009. // the glyf table size, which makes last glyph out of range.
  22010. endOffset = oldGlyfDataLength;
  22011. }
  22012. if (endOffset > oldGlyfDataLength) {
  22013. // glyph end offset points outside glyf data, rejecting the glyph
  22014. itemEncode(locaData, j, writeOffset);
  22015. startOffset = endOffset;
  22016. continue;
  22017. }
  22018. if (startOffset === endOffset) {
  22019. missingGlyphData[i] = true;
  22020. }
  22021. var newLength = sanitizeGlyph(oldGlyfData, startOffset, endOffset,
  22022. newGlyfData, writeOffset, hintsValid);
  22023. writeOffset += newLength;
  22024. itemEncode(locaData, j, writeOffset);
  22025. startOffset = endOffset;
  22026. }
  22027. if (writeOffset === 0) {
  22028. // glyf table cannot be empty -- redoing the glyf and loca tables
  22029. // to have single glyph with one point
  22030. var simpleGlyph = new Uint8Array(
  22031. [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 49, 0]);
  22032. for (i = 0, j = itemSize; i < numGlyphs; i++, j += itemSize) {
  22033. itemEncode(locaData, j, simpleGlyph.length);
  22034. }
  22035. glyf.data = simpleGlyph;
  22036. return missingGlyphData;
  22037. }
  22038. if (dupFirstEntry) {
  22039. var firstEntryLength = itemDecode(locaData, itemSize);
  22040. if (newGlyfData.length > firstEntryLength + writeOffset) {
  22041. glyf.data = newGlyfData.subarray(0, firstEntryLength + writeOffset);
  22042. } else {
  22043. glyf.data = new Uint8Array(firstEntryLength + writeOffset);
  22044. glyf.data.set(newGlyfData.subarray(0, writeOffset));
  22045. }
  22046. glyf.data.set(newGlyfData.subarray(0, firstEntryLength), writeOffset);
  22047. itemEncode(loca.data, locaData.length - itemSize,
  22048. writeOffset + firstEntryLength);
  22049. } else {
  22050. glyf.data = newGlyfData.subarray(0, writeOffset);
  22051. }
  22052. return missingGlyphData;
  22053. }
  22054. function readPostScriptTable(post, properties, maxpNumGlyphs) {
  22055. var start = (font.start ? font.start : 0) + post.offset;
  22056. font.pos = start;
  22057. var length = post.length, end = start + length;
  22058. var version = font.getInt32();
  22059. // skip rest to the tables
  22060. font.getBytes(28);
  22061. var glyphNames;
  22062. var valid = true;
  22063. var i;
  22064. switch (version) {
  22065. case 0x00010000:
  22066. glyphNames = MacStandardGlyphOrdering;
  22067. break;
  22068. case 0x00020000:
  22069. var numGlyphs = font.getUint16();
  22070. if (numGlyphs !== maxpNumGlyphs) {
  22071. valid = false;
  22072. break;
  22073. }
  22074. var glyphNameIndexes = [];
  22075. for (i = 0; i < numGlyphs; ++i) {
  22076. var index = font.getUint16();
  22077. if (index >= 32768) {
  22078. valid = false;
  22079. break;
  22080. }
  22081. glyphNameIndexes.push(index);
  22082. }
  22083. if (!valid) {
  22084. break;
  22085. }
  22086. var customNames = [];
  22087. var strBuf = [];
  22088. while (font.pos < end) {
  22089. var stringLength = font.getByte();
  22090. strBuf.length = stringLength;
  22091. for (i = 0; i < stringLength; ++i) {
  22092. strBuf[i] = String.fromCharCode(font.getByte());
  22093. }
  22094. customNames.push(strBuf.join(''));
  22095. }
  22096. glyphNames = [];
  22097. for (i = 0; i < numGlyphs; ++i) {
  22098. var j = glyphNameIndexes[i];
  22099. if (j < 258) {
  22100. glyphNames.push(MacStandardGlyphOrdering[j]);
  22101. continue;
  22102. }
  22103. glyphNames.push(customNames[j - 258]);
  22104. }
  22105. break;
  22106. case 0x00030000:
  22107. break;
  22108. default:
  22109. warn('Unknown/unsupported post table version ' + version);
  22110. valid = false;
  22111. if (properties.defaultEncoding) {
  22112. glyphNames = properties.defaultEncoding;
  22113. }
  22114. break;
  22115. }
  22116. properties.glyphNames = glyphNames;
  22117. return valid;
  22118. }
  22119. function readNameTable(nameTable) {
  22120. var start = (font.start ? font.start : 0) + nameTable.offset;
  22121. font.pos = start;
  22122. var names = [[], []];
  22123. var length = nameTable.length, end = start + length;
  22124. var format = font.getUint16();
  22125. var FORMAT_0_HEADER_LENGTH = 6;
  22126. if (format !== 0 || length < FORMAT_0_HEADER_LENGTH) {
  22127. // unsupported name table format or table "too" small
  22128. return names;
  22129. }
  22130. var numRecords = font.getUint16();
  22131. var stringsStart = font.getUint16();
  22132. var records = [];
  22133. var NAME_RECORD_LENGTH = 12;
  22134. var i, ii;
  22135. for (i = 0; i < numRecords &&
  22136. font.pos + NAME_RECORD_LENGTH <= end; i++) {
  22137. var r = {
  22138. platform: font.getUint16(),
  22139. encoding: font.getUint16(),
  22140. language: font.getUint16(),
  22141. name: font.getUint16(),
  22142. length: font.getUint16(),
  22143. offset: font.getUint16()
  22144. };
  22145. // using only Macintosh and Windows platform/encoding names
  22146. if ((r.platform === 1 && r.encoding === 0 && r.language === 0) ||
  22147. (r.platform === 3 && r.encoding === 1 && r.language === 0x409)) {
  22148. records.push(r);
  22149. }
  22150. }
  22151. for (i = 0, ii = records.length; i < ii; i++) {
  22152. var record = records[i];
  22153. var pos = start + stringsStart + record.offset;
  22154. if (pos + record.length > end) {
  22155. continue; // outside of name table, ignoring
  22156. }
  22157. font.pos = pos;
  22158. var nameIndex = record.name;
  22159. if (record.encoding) {
  22160. // unicode
  22161. var str = '';
  22162. for (var j = 0, jj = record.length; j < jj; j += 2) {
  22163. str += String.fromCharCode(font.getUint16());
  22164. }
  22165. names[1][nameIndex] = str;
  22166. } else {
  22167. names[0][nameIndex] = bytesToString(font.getBytes(record.length));
  22168. }
  22169. }
  22170. return names;
  22171. }
  22172. var TTOpsStackDeltas = [
  22173. 0, 0, 0, 0, 0, 0, 0, 0, -2, -2, -2, -2, 0, 0, -2, -5,
  22174. -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, -1, 0, -1, -1, -1, -1,
  22175. 1, -1, -999, 0, 1, 0, -1, -2, 0, -1, -2, -1, -1, 0, -1, -1,
  22176. 0, 0, -999, -999, -1, -1, -1, -1, -2, -999, -2, -2, -999, 0, -2, -2,
  22177. 0, 0, -2, 0, -2, 0, 0, 0, -2, -1, -1, 1, 1, 0, 0, -1,
  22178. -1, -1, -1, -1, -1, -1, 0, 0, -1, 0, -1, -1, 0, -999, -1, -1,
  22179. -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  22180. -2, -999, -999, -999, -999, -999, -1, -1, -2, -2, 0, 0, 0, 0, -1, -1,
  22181. -999, -2, -2, 0, 0, -1, -2, -2, 0, 0, 0, -1, -1, -1, -2];
  22182. // 0xC0-DF == -1 and 0xE0-FF == -2
  22183. function sanitizeTTProgram(table, ttContext) {
  22184. var data = table.data;
  22185. var i = 0, j, n, b, funcId, pc, lastEndf = 0, lastDeff = 0;
  22186. var stack = [];
  22187. var callstack = [];
  22188. var functionsCalled = [];
  22189. var tooComplexToFollowFunctions =
  22190. ttContext.tooComplexToFollowFunctions;
  22191. var inFDEF = false, ifLevel = 0, inELSE = 0;
  22192. for (var ii = data.length; i < ii;) {
  22193. var op = data[i++];
  22194. // The TrueType instruction set docs can be found at
  22195. // https://developer.apple.com/fonts/TTRefMan/RM05/Chap5.html
  22196. if (op === 0x40) { // NPUSHB - pushes n bytes
  22197. n = data[i++];
  22198. if (inFDEF || inELSE) {
  22199. i += n;
  22200. } else {
  22201. for (j = 0; j < n; j++) {
  22202. stack.push(data[i++]);
  22203. }
  22204. }
  22205. } else if (op === 0x41) { // NPUSHW - pushes n words
  22206. n = data[i++];
  22207. if (inFDEF || inELSE) {
  22208. i += n * 2;
  22209. } else {
  22210. for (j = 0; j < n; j++) {
  22211. b = data[i++];
  22212. stack.push((b << 8) | data[i++]);
  22213. }
  22214. }
  22215. } else if ((op & 0xF8) === 0xB0) { // PUSHB - pushes bytes
  22216. n = op - 0xB0 + 1;
  22217. if (inFDEF || inELSE) {
  22218. i += n;
  22219. } else {
  22220. for (j = 0; j < n; j++) {
  22221. stack.push(data[i++]);
  22222. }
  22223. }
  22224. } else if ((op & 0xF8) === 0xB8) { // PUSHW - pushes words
  22225. n = op - 0xB8 + 1;
  22226. if (inFDEF || inELSE) {
  22227. i += n * 2;
  22228. } else {
  22229. for (j = 0; j < n; j++) {
  22230. b = data[i++];
  22231. stack.push((b << 8) | data[i++]);
  22232. }
  22233. }
  22234. } else if (op === 0x2B && !tooComplexToFollowFunctions) { // CALL
  22235. if (!inFDEF && !inELSE) {
  22236. // collecting inforamtion about which functions are used
  22237. funcId = stack[stack.length - 1];
  22238. ttContext.functionsUsed[funcId] = true;
  22239. if (funcId in ttContext.functionsStackDeltas) {
  22240. stack.length += ttContext.functionsStackDeltas[funcId];
  22241. } else if (funcId in ttContext.functionsDefined &&
  22242. functionsCalled.indexOf(funcId) < 0) {
  22243. callstack.push({data: data, i: i, stackTop: stack.length - 1});
  22244. functionsCalled.push(funcId);
  22245. pc = ttContext.functionsDefined[funcId];
  22246. if (!pc) {
  22247. warn('TT: CALL non-existent function');
  22248. ttContext.hintsValid = false;
  22249. return;
  22250. }
  22251. data = pc.data;
  22252. i = pc.i;
  22253. }
  22254. }
  22255. } else if (op === 0x2C && !tooComplexToFollowFunctions) { // FDEF
  22256. if (inFDEF || inELSE) {
  22257. warn('TT: nested FDEFs not allowed');
  22258. tooComplexToFollowFunctions = true;
  22259. }
  22260. inFDEF = true;
  22261. // collecting inforamtion about which functions are defined
  22262. lastDeff = i;
  22263. funcId = stack.pop();
  22264. ttContext.functionsDefined[funcId] = {data: data, i: i};
  22265. } else if (op === 0x2D) { // ENDF - end of function
  22266. if (inFDEF) {
  22267. inFDEF = false;
  22268. lastEndf = i;
  22269. } else {
  22270. pc = callstack.pop();
  22271. if (!pc) {
  22272. warn('TT: ENDF bad stack');
  22273. ttContext.hintsValid = false;
  22274. return;
  22275. }
  22276. funcId = functionsCalled.pop();
  22277. data = pc.data;
  22278. i = pc.i;
  22279. ttContext.functionsStackDeltas[funcId] =
  22280. stack.length - pc.stackTop;
  22281. }
  22282. } else if (op === 0x89) { // IDEF - instruction definition
  22283. if (inFDEF || inELSE) {
  22284. warn('TT: nested IDEFs not allowed');
  22285. tooComplexToFollowFunctions = true;
  22286. }
  22287. inFDEF = true;
  22288. // recording it as a function to track ENDF
  22289. lastDeff = i;
  22290. } else if (op === 0x58) { // IF
  22291. ++ifLevel;
  22292. } else if (op === 0x1B) { // ELSE
  22293. inELSE = ifLevel;
  22294. } else if (op === 0x59) { // EIF
  22295. if (inELSE === ifLevel) {
  22296. inELSE = 0;
  22297. }
  22298. --ifLevel;
  22299. } else if (op === 0x1C) { // JMPR
  22300. if (!inFDEF && !inELSE) {
  22301. var offset = stack[stack.length - 1];
  22302. // only jumping forward to prevent infinite loop
  22303. if (offset > 0) {
  22304. i += offset - 1;
  22305. }
  22306. }
  22307. }
  22308. // Adjusting stack not extactly, but just enough to get function id
  22309. if (!inFDEF && !inELSE) {
  22310. var stackDelta = op <= 0x8E ? TTOpsStackDeltas[op] :
  22311. op >= 0xC0 && op <= 0xDF ? -1 : op >= 0xE0 ? -2 : 0;
  22312. if (op >= 0x71 && op <= 0x75) {
  22313. n = stack.pop();
  22314. if (n === n) {
  22315. stackDelta = -n * 2;
  22316. }
  22317. }
  22318. while (stackDelta < 0 && stack.length > 0) {
  22319. stack.pop();
  22320. stackDelta++;
  22321. }
  22322. while (stackDelta > 0) {
  22323. stack.push(NaN); // pushing any number into stack
  22324. stackDelta--;
  22325. }
  22326. }
  22327. }
  22328. ttContext.tooComplexToFollowFunctions = tooComplexToFollowFunctions;
  22329. var content = [data];
  22330. if (i > data.length) {
  22331. content.push(new Uint8Array(i - data.length));
  22332. }
  22333. if (lastDeff > lastEndf) {
  22334. warn('TT: complementing a missing function tail');
  22335. // new function definition started, but not finished
  22336. // complete function by [CLEAR, ENDF]
  22337. content.push(new Uint8Array([0x22, 0x2D]));
  22338. }
  22339. foldTTTable(table, content);
  22340. }
  22341. function checkInvalidFunctions(ttContext, maxFunctionDefs) {
  22342. if (ttContext.tooComplexToFollowFunctions) {
  22343. return;
  22344. }
  22345. if (ttContext.functionsDefined.length > maxFunctionDefs) {
  22346. warn('TT: more functions defined than expected');
  22347. ttContext.hintsValid = false;
  22348. return;
  22349. }
  22350. for (var j = 0, jj = ttContext.functionsUsed.length; j < jj; j++) {
  22351. if (j > maxFunctionDefs) {
  22352. warn('TT: invalid function id: ' + j);
  22353. ttContext.hintsValid = false;
  22354. return;
  22355. }
  22356. if (ttContext.functionsUsed[j] && !ttContext.functionsDefined[j]) {
  22357. warn('TT: undefined function: ' + j);
  22358. ttContext.hintsValid = false;
  22359. return;
  22360. }
  22361. }
  22362. }
  22363. function foldTTTable(table, content) {
  22364. if (content.length > 1) {
  22365. // concatenating the content items
  22366. var newLength = 0;
  22367. var j, jj;
  22368. for (j = 0, jj = content.length; j < jj; j++) {
  22369. newLength += content[j].length;
  22370. }
  22371. newLength = (newLength + 3) & ~3;
  22372. var result = new Uint8Array(newLength);
  22373. var pos = 0;
  22374. for (j = 0, jj = content.length; j < jj; j++) {
  22375. result.set(content[j], pos);
  22376. pos += content[j].length;
  22377. }
  22378. table.data = result;
  22379. table.length = newLength;
  22380. }
  22381. }
  22382. function sanitizeTTPrograms(fpgm, prep, cvt) {
  22383. var ttContext = {
  22384. functionsDefined: [],
  22385. functionsUsed: [],
  22386. functionsStackDeltas: [],
  22387. tooComplexToFollowFunctions: false,
  22388. hintsValid: true
  22389. };
  22390. if (fpgm) {
  22391. sanitizeTTProgram(fpgm, ttContext);
  22392. }
  22393. if (prep) {
  22394. sanitizeTTProgram(prep, ttContext);
  22395. }
  22396. if (fpgm) {
  22397. checkInvalidFunctions(ttContext, maxFunctionDefs);
  22398. }
  22399. if (cvt && (cvt.length & 1)) {
  22400. var cvtData = new Uint8Array(cvt.length + 1);
  22401. cvtData.set(cvt.data);
  22402. cvt.data = cvtData;
  22403. }
  22404. return ttContext.hintsValid;
  22405. }
  22406. // The following steps modify the original font data, making copy
  22407. font = new Stream(new Uint8Array(font.getBytes()));
  22408. var VALID_TABLES = ['OS/2', 'cmap', 'head', 'hhea', 'hmtx', 'maxp',
  22409. 'name', 'post', 'loca', 'glyf', 'fpgm', 'prep', 'cvt ', 'CFF '];
  22410. var header = readOpenTypeHeader(font);
  22411. var numTables = header.numTables;
  22412. var cff, cffFile;
  22413. var tables = { 'OS/2': null, cmap: null, head: null, hhea: null,
  22414. hmtx: null, maxp: null, name: null, post: null };
  22415. var table;
  22416. for (var i = 0; i < numTables; i++) {
  22417. table = readTableEntry(font);
  22418. if (VALID_TABLES.indexOf(table.tag) < 0) {
  22419. continue; // skipping table if it's not a required or optional table
  22420. }
  22421. if (table.length === 0) {
  22422. continue; // skipping empty tables
  22423. }
  22424. tables[table.tag] = table;
  22425. }
  22426. var isTrueType = !tables['CFF '];
  22427. if (!isTrueType) {
  22428. // OpenType font
  22429. if (header.version === 'OTTO' ||
  22430. !tables.head || !tables.hhea || !tables.maxp || !tables.post) {
  22431. // no major tables: throwing everything at CFFFont
  22432. cffFile = new Stream(tables['CFF '].data);
  22433. cff = new CFFFont(cffFile, properties);
  22434. return this.convert(name, cff, properties);
  22435. }
  22436. delete tables.glyf;
  22437. delete tables.loca;
  22438. delete tables.fpgm;
  22439. delete tables.prep;
  22440. delete tables['cvt '];
  22441. this.isOpenType = true;
  22442. } else {
  22443. if (!tables.glyf || !tables.loca) {
  22444. error('Required "glyf" or "loca" tables are not found');
  22445. }
  22446. this.isOpenType = false;
  22447. }
  22448. if (!tables.maxp) {
  22449. error('Required "maxp" table is not found');
  22450. }
  22451. font.pos = (font.start || 0) + tables.maxp.offset;
  22452. var version = font.getInt32();
  22453. var numGlyphs = font.getUint16();
  22454. var maxFunctionDefs = 0;
  22455. if (version >= 0x00010000 && tables.maxp.length >= 22) {
  22456. // maxZones can be invalid
  22457. font.pos += 8;
  22458. var maxZones = font.getUint16();
  22459. if (maxZones > 2) { // reset to 2 if font has invalid maxZones
  22460. tables.maxp.data[14] = 0;
  22461. tables.maxp.data[15] = 2;
  22462. }
  22463. font.pos += 4;
  22464. maxFunctionDefs = font.getUint16();
  22465. }
  22466. var dupFirstEntry = false;
  22467. if (properties.type === 'CIDFontType2' && properties.toUnicode &&
  22468. properties.toUnicode.get(0) > '\u0000') {
  22469. // oracle's defect (see 3427), duplicating first entry
  22470. dupFirstEntry = true;
  22471. numGlyphs++;
  22472. tables.maxp.data[4] = numGlyphs >> 8;
  22473. tables.maxp.data[5] = numGlyphs & 255;
  22474. }
  22475. var hintsValid = sanitizeTTPrograms(tables.fpgm, tables.prep,
  22476. tables['cvt '], maxFunctionDefs);
  22477. if (!hintsValid) {
  22478. delete tables.fpgm;
  22479. delete tables.prep;
  22480. delete tables['cvt '];
  22481. }
  22482. // Ensure the hmtx table contains the advance width and
  22483. // sidebearings information for numGlyphs in the maxp table
  22484. sanitizeMetrics(font, tables.hhea, tables.hmtx, numGlyphs);
  22485. if (!tables.head) {
  22486. error('Required "head" table is not found');
  22487. }
  22488. sanitizeHead(tables.head, numGlyphs, isTrueType ? tables.loca.length : 0);
  22489. var missingGlyphs = {};
  22490. if (isTrueType) {
  22491. var isGlyphLocationsLong = int16(tables.head.data[50],
  22492. tables.head.data[51]);
  22493. missingGlyphs = sanitizeGlyphLocations(tables.loca, tables.glyf,
  22494. numGlyphs, isGlyphLocationsLong,
  22495. hintsValid, dupFirstEntry);
  22496. }
  22497. if (!tables.hhea) {
  22498. error('Required "hhea" table is not found');
  22499. }
  22500. // Sanitizer reduces the glyph advanceWidth to the maxAdvanceWidth
  22501. // Sometimes it's 0. That needs to be fixed
  22502. if (tables.hhea.data[10] === 0 && tables.hhea.data[11] === 0) {
  22503. tables.hhea.data[10] = 0xFF;
  22504. tables.hhea.data[11] = 0xFF;
  22505. }
  22506. // The 'post' table has glyphs names.
  22507. if (tables.post) {
  22508. var valid = readPostScriptTable(tables.post, properties, numGlyphs);
  22509. if (!valid) {
  22510. tables.post = null;
  22511. }
  22512. }
  22513. var charCodeToGlyphId = [], charCode;
  22514. var toUnicode = properties.toUnicode, widths = properties.widths;
  22515. var isIdentityUnicode = toUnicode instanceof IdentityToUnicodeMap;
  22516. function hasGlyph(glyphId, charCode, widthCode) {
  22517. if (!missingGlyphs[glyphId]) {
  22518. return true;
  22519. }
  22520. if (!isIdentityUnicode && charCode >= 0 && toUnicode.has(charCode)) {
  22521. return true;
  22522. }
  22523. if (widths && widthCode >= 0 && isNum(widths[widthCode])) {
  22524. return true;
  22525. }
  22526. return false;
  22527. }
  22528. if (properties.type === 'CIDFontType2') {
  22529. var cidToGidMap = properties.cidToGidMap || [];
  22530. var isCidToGidMapEmpty = cidToGidMap.length === 0;
  22531. properties.cMap.forEach(function(charCode, cid) {
  22532. assert(cid <= 0xffff, 'Max size of CID is 65,535');
  22533. var glyphId = -1;
  22534. if (isCidToGidMapEmpty) {
  22535. glyphId = charCode;
  22536. } else if (cidToGidMap[cid] !== undefined) {
  22537. glyphId = cidToGidMap[cid];
  22538. }
  22539. if (glyphId >= 0 && glyphId < numGlyphs &&
  22540. hasGlyph(glyphId, charCode, cid)) {
  22541. charCodeToGlyphId[charCode] = glyphId;
  22542. }
  22543. });
  22544. if (dupFirstEntry) {
  22545. charCodeToGlyphId[0] = numGlyphs - 1;
  22546. }
  22547. } else {
  22548. // Most of the following logic in this code branch is based on the
  22549. // 9.6.6.4 of the PDF spec.
  22550. var cmapTable = readCmapTable(tables.cmap, font, this.isSymbolicFont);
  22551. var cmapPlatformId = cmapTable.platformId;
  22552. var cmapEncodingId = cmapTable.encodingId;
  22553. var cmapMappings = cmapTable.mappings;
  22554. var cmapMappingsLength = cmapMappings.length;
  22555. var hasEncoding = properties.differences.length ||
  22556. !!properties.baseEncodingName;
  22557. // The spec seems to imply that if the font is symbolic the encoding
  22558. // should be ignored, this doesn't appear to work for 'preistabelle.pdf'
  22559. // where the the font is symbolic and it has an encoding.
  22560. if (hasEncoding &&
  22561. (cmapPlatformId === 3 && cmapEncodingId === 1 ||
  22562. cmapPlatformId === 1 && cmapEncodingId === 0) ||
  22563. (cmapPlatformId === -1 && cmapEncodingId === -1 && // Temporary hack
  22564. !!Encodings[properties.baseEncodingName])) { // Temporary hack
  22565. // When no preferred cmap table was found and |baseEncodingName| is
  22566. // one of the predefined encodings, we seem to obtain a better
  22567. // |charCodeToGlyphId| map from the code below (fixes bug 1057544).
  22568. // TODO: Note that this is a hack which should be removed as soon as
  22569. // we have proper support for more exotic cmap tables.
  22570. var baseEncoding = [];
  22571. if (properties.baseEncodingName === 'MacRomanEncoding' ||
  22572. properties.baseEncodingName === 'WinAnsiEncoding') {
  22573. baseEncoding = Encodings[properties.baseEncodingName];
  22574. }
  22575. for (charCode = 0; charCode < 256; charCode++) {
  22576. var glyphName;
  22577. if (this.differences && charCode in this.differences) {
  22578. glyphName = this.differences[charCode];
  22579. } else if (charCode in baseEncoding &&
  22580. baseEncoding[charCode] !== '') {
  22581. glyphName = baseEncoding[charCode];
  22582. } else {
  22583. glyphName = Encodings.StandardEncoding[charCode];
  22584. }
  22585. if (!glyphName) {
  22586. continue;
  22587. }
  22588. var unicodeOrCharCode;
  22589. if (cmapPlatformId === 3 && cmapEncodingId === 1) {
  22590. unicodeOrCharCode = GlyphsUnicode[glyphName];
  22591. } else if (cmapPlatformId === 1 && cmapEncodingId === 0) {
  22592. // TODO: the encoding needs to be updated with mac os table.
  22593. unicodeOrCharCode = Encodings.MacRomanEncoding.indexOf(glyphName);
  22594. }
  22595. var found = false;
  22596. for (i = 0; i < cmapMappingsLength; ++i) {
  22597. if (cmapMappings[i].charCode === unicodeOrCharCode &&
  22598. hasGlyph(cmapMappings[i].glyphId, unicodeOrCharCode, -1)) {
  22599. charCodeToGlyphId[charCode] = cmapMappings[i].glyphId;
  22600. found = true;
  22601. break;
  22602. }
  22603. }
  22604. if (!found && properties.glyphNames) {
  22605. // Try to map using the post table.
  22606. var glyphId = properties.glyphNames.indexOf(glyphName);
  22607. if (glyphId > 0 && hasGlyph(glyphId, -1, -1)) {
  22608. charCodeToGlyphId[charCode] = glyphId;
  22609. } else {
  22610. charCodeToGlyphId[charCode] = 0; // notdef
  22611. }
  22612. }
  22613. }
  22614. } else if (cmapPlatformId === 0 && cmapEncodingId === 0) {
  22615. // Default Unicode semantics, use the charcodes as is.
  22616. for (i = 0; i < cmapMappingsLength; ++i) {
  22617. charCodeToGlyphId[cmapMappings[i].charCode] =
  22618. cmapMappings[i].glyphId;
  22619. }
  22620. } else {
  22621. // For (3, 0) cmap tables:
  22622. // The charcode key being stored in charCodeToGlyphId is the lower
  22623. // byte of the two-byte charcodes of the cmap table since according to
  22624. // the spec: 'each byte from the string shall be prepended with the
  22625. // high byte of the range [of charcodes in the cmap table], to form
  22626. // a two-byte character, which shall be used to select the
  22627. // associated glyph description from the subtable'.
  22628. //
  22629. // For (1, 0) cmap tables:
  22630. // 'single bytes from the string shall be used to look up the
  22631. // associated glyph descriptions from the subtable'. This means
  22632. // charcodes in the cmap will be single bytes, so no-op since
  22633. // glyph.charCode & 0xFF === glyph.charCode
  22634. for (i = 0; i < cmapMappingsLength; ++i) {
  22635. charCode = cmapMappings[i].charCode & 0xFF;
  22636. charCodeToGlyphId[charCode] = cmapMappings[i].glyphId;
  22637. }
  22638. }
  22639. }
  22640. if (charCodeToGlyphId.length === 0) {
  22641. // defines at least one glyph
  22642. charCodeToGlyphId[0] = 0;
  22643. }
  22644. // Converting glyphs and ids into font's cmap table
  22645. var newMapping = adjustMapping(charCodeToGlyphId, properties);
  22646. this.toFontChar = newMapping.toFontChar;
  22647. tables.cmap = {
  22648. tag: 'cmap',
  22649. data: createCmapTable(newMapping.charCodeToGlyphId)
  22650. };
  22651. if (!tables['OS/2'] || !validateOS2Table(tables['OS/2'])) {
  22652. // extract some more font properties from the OpenType head and
  22653. // hhea tables; yMin and descent value are always negative
  22654. var override = {
  22655. unitsPerEm: int16(tables.head.data[18], tables.head.data[19]),
  22656. yMax: int16(tables.head.data[42], tables.head.data[43]),
  22657. yMin: int16(tables.head.data[38], tables.head.data[39]) - 0x10000,
  22658. ascent: int16(tables.hhea.data[4], tables.hhea.data[5]),
  22659. descent: int16(tables.hhea.data[6], tables.hhea.data[7]) - 0x10000
  22660. };
  22661. tables['OS/2'] = {
  22662. tag: 'OS/2',
  22663. data: createOS2Table(properties, newMapping.charCodeToGlyphId,
  22664. override)
  22665. };
  22666. }
  22667. // Rewrite the 'post' table if needed
  22668. if (!tables.post) {
  22669. tables.post = {
  22670. tag: 'post',
  22671. data: createPostTable(properties)
  22672. };
  22673. }
  22674. if (!isTrueType) {
  22675. try {
  22676. // Trying to repair CFF file
  22677. cffFile = new Stream(tables['CFF '].data);
  22678. var parser = new CFFParser(cffFile, properties);
  22679. cff = parser.parse();
  22680. var compiler = new CFFCompiler(cff);
  22681. tables['CFF '].data = compiler.compile();
  22682. } catch (e) {
  22683. warn('Failed to compile font ' + properties.loadedName);
  22684. }
  22685. }
  22686. // Re-creating 'name' table
  22687. if (!tables.name) {
  22688. tables.name = {
  22689. tag: 'name',
  22690. data: createNameTable(this.name)
  22691. };
  22692. } else {
  22693. // ... using existing 'name' table as prototype
  22694. var namePrototype = readNameTable(tables.name);
  22695. tables.name.data = createNameTable(name, namePrototype);
  22696. }
  22697. var builder = new OpenTypeFileBuilder(header.version);
  22698. for (var tableTag in tables) {
  22699. builder.addTable(tableTag, tables[tableTag].data);
  22700. }
  22701. return builder.toArray();
  22702. },
  22703. convert: function Font_convert(fontName, font, properties) {
  22704. // TODO: Check the charstring widths to determine this.
  22705. properties.fixedPitch = false;
  22706. var mapping = font.getGlyphMapping(properties);
  22707. var newMapping = adjustMapping(mapping, properties);
  22708. this.toFontChar = newMapping.toFontChar;
  22709. var numGlyphs = font.numGlyphs;
  22710. function getCharCodes(charCodeToGlyphId, glyphId) {
  22711. var charCodes = null;
  22712. for (var charCode in charCodeToGlyphId) {
  22713. if (glyphId === charCodeToGlyphId[charCode]) {
  22714. if (!charCodes) {
  22715. charCodes = [];
  22716. }
  22717. charCodes.push(charCode | 0);
  22718. }
  22719. }
  22720. return charCodes;
  22721. }
  22722. function createCharCode(charCodeToGlyphId, glyphId) {
  22723. for (var charCode in charCodeToGlyphId) {
  22724. if (glyphId === charCodeToGlyphId[charCode]) {
  22725. return charCode | 0;
  22726. }
  22727. }
  22728. newMapping.charCodeToGlyphId[newMapping.nextAvailableFontCharCode] =
  22729. glyphId;
  22730. return newMapping.nextAvailableFontCharCode++;
  22731. }
  22732. var seacs = font.seacs;
  22733. if (SEAC_ANALYSIS_ENABLED && seacs && seacs.length) {
  22734. var matrix = properties.fontMatrix || FONT_IDENTITY_MATRIX;
  22735. var charset = font.getCharset();
  22736. var seacMap = Object.create(null);
  22737. for (var glyphId in seacs) {
  22738. glyphId |= 0;
  22739. var seac = seacs[glyphId];
  22740. var baseGlyphName = Encodings.StandardEncoding[seac[2]];
  22741. var accentGlyphName = Encodings.StandardEncoding[seac[3]];
  22742. var baseGlyphId = charset.indexOf(baseGlyphName);
  22743. var accentGlyphId = charset.indexOf(accentGlyphName);
  22744. if (baseGlyphId < 0 || accentGlyphId < 0) {
  22745. continue;
  22746. }
  22747. var accentOffset = {
  22748. x: seac[0] * matrix[0] + seac[1] * matrix[2] + matrix[4],
  22749. y: seac[0] * matrix[1] + seac[1] * matrix[3] + matrix[5]
  22750. };
  22751. var charCodes = getCharCodes(mapping, glyphId);
  22752. if (!charCodes) {
  22753. // There's no point in mapping it if the char code was never mapped
  22754. // to begin with.
  22755. continue;
  22756. }
  22757. for (var i = 0, ii = charCodes.length; i < ii; i++) {
  22758. var charCode = charCodes[i];
  22759. // Find a fontCharCode that maps to the base and accent glyphs.
  22760. // If one doesn't exists, create it.
  22761. var charCodeToGlyphId = newMapping.charCodeToGlyphId;
  22762. var baseFontCharCode = createCharCode(charCodeToGlyphId,
  22763. baseGlyphId);
  22764. var accentFontCharCode = createCharCode(charCodeToGlyphId,
  22765. accentGlyphId);
  22766. seacMap[charCode] = {
  22767. baseFontCharCode: baseFontCharCode,
  22768. accentFontCharCode: accentFontCharCode,
  22769. accentOffset: accentOffset
  22770. };
  22771. }
  22772. }
  22773. properties.seacMap = seacMap;
  22774. }
  22775. var unitsPerEm = 1 / (properties.fontMatrix || FONT_IDENTITY_MATRIX)[0];
  22776. var builder = new OpenTypeFileBuilder('\x4F\x54\x54\x4F');
  22777. // PostScript Font Program
  22778. builder.addTable('CFF ', font.data);
  22779. // OS/2 and Windows Specific metrics
  22780. builder.addTable('OS/2', createOS2Table(properties,
  22781. newMapping.charCodeToGlyphId));
  22782. // Character to glyphs mapping
  22783. builder.addTable('cmap', createCmapTable(newMapping.charCodeToGlyphId));
  22784. // Font header
  22785. builder.addTable('head',
  22786. '\x00\x01\x00\x00' + // Version number
  22787. '\x00\x00\x10\x00' + // fontRevision
  22788. '\x00\x00\x00\x00' + // checksumAdjustement
  22789. '\x5F\x0F\x3C\xF5' + // magicNumber
  22790. '\x00\x00' + // Flags
  22791. safeString16(unitsPerEm) + // unitsPerEM
  22792. '\x00\x00\x00\x00\x9e\x0b\x7e\x27' + // creation date
  22793. '\x00\x00\x00\x00\x9e\x0b\x7e\x27' + // modifification date
  22794. '\x00\x00' + // xMin
  22795. safeString16(properties.descent) + // yMin
  22796. '\x0F\xFF' + // xMax
  22797. safeString16(properties.ascent) + // yMax
  22798. string16(properties.italicAngle ? 2 : 0) + // macStyle
  22799. '\x00\x11' + // lowestRecPPEM
  22800. '\x00\x00' + // fontDirectionHint
  22801. '\x00\x00' + // indexToLocFormat
  22802. '\x00\x00'); // glyphDataFormat
  22803. // Horizontal header
  22804. builder.addTable('hhea',
  22805. '\x00\x01\x00\x00' + // Version number
  22806. safeString16(properties.ascent) + // Typographic Ascent
  22807. safeString16(properties.descent) + // Typographic Descent
  22808. '\x00\x00' + // Line Gap
  22809. '\xFF\xFF' + // advanceWidthMax
  22810. '\x00\x00' + // minLeftSidebearing
  22811. '\x00\x00' + // minRightSidebearing
  22812. '\x00\x00' + // xMaxExtent
  22813. safeString16(properties.capHeight) + // caretSlopeRise
  22814. safeString16(Math.tan(properties.italicAngle) *
  22815. properties.xHeight) + // caretSlopeRun
  22816. '\x00\x00' + // caretOffset
  22817. '\x00\x00' + // -reserved-
  22818. '\x00\x00' + // -reserved-
  22819. '\x00\x00' + // -reserved-
  22820. '\x00\x00' + // -reserved-
  22821. '\x00\x00' + // metricDataFormat
  22822. string16(numGlyphs)); // Number of HMetrics
  22823. // Horizontal metrics
  22824. builder.addTable('hmtx', (function fontFieldsHmtx() {
  22825. var charstrings = font.charstrings;
  22826. var cffWidths = font.cff ? font.cff.widths : null;
  22827. var hmtx = '\x00\x00\x00\x00'; // Fake .notdef
  22828. for (var i = 1, ii = numGlyphs; i < ii; i++) {
  22829. var width = 0;
  22830. if (charstrings) {
  22831. var charstring = charstrings[i - 1];
  22832. width = 'width' in charstring ? charstring.width : 0;
  22833. } else if (cffWidths) {
  22834. width = Math.ceil(cffWidths[i] || 0);
  22835. }
  22836. hmtx += string16(width) + string16(0);
  22837. }
  22838. return hmtx;
  22839. })());
  22840. // Maximum profile
  22841. builder.addTable('maxp',
  22842. '\x00\x00\x50\x00' + // Version number
  22843. string16(numGlyphs)); // Num of glyphs
  22844. // Naming tables
  22845. builder.addTable('name', createNameTable(fontName));
  22846. // PostScript informations
  22847. builder.addTable('post', createPostTable(properties));
  22848. return builder.toArray();
  22849. },
  22850. /**
  22851. * Builds a char code to unicode map based on section 9.10 of the spec.
  22852. * @param {Object} properties Font properties object.
  22853. * @return {Object} A ToUnicodeMap object.
  22854. */
  22855. buildToUnicode: function Font_buildToUnicode(properties) {
  22856. // Section 9.10.2 Mapping Character Codes to Unicode Values
  22857. if (properties.toUnicode && properties.toUnicode.length !== 0) {
  22858. return properties.toUnicode;
  22859. }
  22860. // According to the spec if the font is a simple font we should only map
  22861. // to unicode if the base encoding is MacRoman, MacExpert, or WinAnsi or
  22862. // the differences array only contains adobe standard or symbol set names,
  22863. // in pratice it seems better to always try to create a toUnicode
  22864. // map based of the default encoding.
  22865. var toUnicode, charcode;
  22866. if (!properties.composite /* is simple font */) {
  22867. toUnicode = [];
  22868. var encoding = properties.defaultEncoding.slice();
  22869. var baseEncodingName = properties.baseEncodingName;
  22870. // Merge in the differences array.
  22871. var differences = properties.differences;
  22872. for (charcode in differences) {
  22873. encoding[charcode] = differences[charcode];
  22874. }
  22875. for (charcode in encoding) {
  22876. // a) Map the character code to a character name.
  22877. var glyphName = encoding[charcode];
  22878. // b) Look up the character name in the Adobe Glyph List (see the
  22879. // Bibliography) to obtain the corresponding Unicode value.
  22880. if (glyphName === '') {
  22881. continue;
  22882. } else if (GlyphsUnicode[glyphName] === undefined) {
  22883. // (undocumented) c) Few heuristics to recognize unknown glyphs
  22884. // NOTE: Adobe Reader does not do this step, but OSX Preview does
  22885. var code = 0;
  22886. switch (glyphName[0]) {
  22887. case 'G': // Gxx glyph
  22888. if (glyphName.length === 3) {
  22889. code = parseInt(glyphName.substr(1), 16);
  22890. }
  22891. break;
  22892. case 'g': // g00xx glyph
  22893. if (glyphName.length === 5) {
  22894. code = parseInt(glyphName.substr(1), 16);
  22895. }
  22896. break;
  22897. case 'C': // Cddd glyph
  22898. case 'c': // cddd glyph
  22899. if (glyphName.length >= 3) {
  22900. code = +glyphName.substr(1);
  22901. }
  22902. break;
  22903. }
  22904. if (code) {
  22905. // If |baseEncodingName| is one the predefined encodings,
  22906. // and |code| equals |charcode|, using the glyph defined in the
  22907. // baseEncoding seems to yield a better |toUnicode| mapping
  22908. // (fixes issue 5070).
  22909. if (baseEncodingName && code === +charcode) {
  22910. var baseEncoding = Encodings[baseEncodingName];
  22911. if (baseEncoding && (glyphName = baseEncoding[charcode])) {
  22912. toUnicode[charcode] =
  22913. String.fromCharCode(GlyphsUnicode[glyphName]);
  22914. continue;
  22915. }
  22916. }
  22917. toUnicode[charcode] = String.fromCharCode(code);
  22918. }
  22919. continue;
  22920. }
  22921. toUnicode[charcode] = String.fromCharCode(GlyphsUnicode[glyphName]);
  22922. }
  22923. return new ToUnicodeMap(toUnicode);
  22924. }
  22925. // If the font is a composite font that uses one of the predefined CMaps
  22926. // listed in Table 118 (except Identity–H and Identity–V) or whose
  22927. // descendant CIDFont uses the Adobe-GB1, Adobe-CNS1, Adobe-Japan1, or
  22928. // Adobe-Korea1 character collection:
  22929. if (properties.composite && (
  22930. (properties.cMap.builtInCMap &&
  22931. !(properties.cMap instanceof IdentityCMap)) ||
  22932. (properties.cidSystemInfo.registry === 'Adobe' &&
  22933. (properties.cidSystemInfo.ordering === 'GB1' ||
  22934. properties.cidSystemInfo.ordering === 'CNS1' ||
  22935. properties.cidSystemInfo.ordering === 'Japan1' ||
  22936. properties.cidSystemInfo.ordering === 'Korea1')))) {
  22937. // Then:
  22938. // a) Map the character code to a character identifier (CID) according
  22939. // to the font’s CMap.
  22940. // b) Obtain the registry and ordering of the character collection used
  22941. // by the font’s CMap (for example, Adobe and Japan1) from its
  22942. // CIDSystemInfo dictionary.
  22943. var registry = properties.cidSystemInfo.registry;
  22944. var ordering = properties.cidSystemInfo.ordering;
  22945. // c) Construct a second CMap name by concatenating the registry and
  22946. // ordering obtained in step (b) in the format registry–ordering–UCS2
  22947. // (for example, Adobe–Japan1–UCS2).
  22948. var ucs2CMapName = new Name(registry + '-' + ordering + '-UCS2');
  22949. // d) Obtain the CMap with the name constructed in step (c) (available
  22950. // from the ASN Web site; see the Bibliography).
  22951. var ucs2CMap = CMapFactory.create(ucs2CMapName,
  22952. { url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null);
  22953. var cMap = properties.cMap;
  22954. toUnicode = [];
  22955. cMap.forEach(function(charcode, cid) {
  22956. assert(cid <= 0xffff, 'Max size of CID is 65,535');
  22957. // e) Map the CID obtained in step (a) according to the CMap obtained
  22958. // in step (d), producing a Unicode value.
  22959. var ucs2 = ucs2CMap.lookup(cid);
  22960. if (ucs2) {
  22961. toUnicode[charcode] =
  22962. String.fromCharCode((ucs2.charCodeAt(0) << 8) +
  22963. ucs2.charCodeAt(1));
  22964. }
  22965. });
  22966. return new ToUnicodeMap(toUnicode);
  22967. }
  22968. // The viewer's choice, just use an identity map.
  22969. return new IdentityToUnicodeMap(properties.firstChar,
  22970. properties.lastChar);
  22971. },
  22972. get spaceWidth() {
  22973. if ('_shadowWidth' in this) {
  22974. return this._shadowWidth;
  22975. }
  22976. // trying to estimate space character width
  22977. var possibleSpaceReplacements = ['space', 'minus', 'one', 'i'];
  22978. var width;
  22979. for (var i = 0, ii = possibleSpaceReplacements.length; i < ii; i++) {
  22980. var glyphName = possibleSpaceReplacements[i];
  22981. // if possible, getting width by glyph name
  22982. if (glyphName in this.widths) {
  22983. width = this.widths[glyphName];
  22984. break;
  22985. }
  22986. var glyphUnicode = GlyphsUnicode[glyphName];
  22987. // finding the charcode via unicodeToCID map
  22988. var charcode = 0;
  22989. if (this.composite) {
  22990. if (this.cMap.contains(glyphUnicode)) {
  22991. charcode = this.cMap.lookup(glyphUnicode);
  22992. }
  22993. }
  22994. // ... via toUnicode map
  22995. if (!charcode && 'toUnicode' in this) {
  22996. charcode = this.toUnicode.charCodeOf(glyphUnicode);
  22997. }
  22998. // setting it to unicode if negative or undefined
  22999. if (charcode <= 0) {
  23000. charcode = glyphUnicode;
  23001. }
  23002. // trying to get width via charcode
  23003. width = this.widths[charcode];
  23004. if (width) {
  23005. break; // the non-zero width found
  23006. }
  23007. }
  23008. width = width || this.defaultWidth;
  23009. // Do not shadow the property here. See discussion:
  23010. // https://github.com/mozilla/pdf.js/pull/2127#discussion_r1662280
  23011. this._shadowWidth = width;
  23012. return width;
  23013. },
  23014. charToGlyph: function Font_charToGlyph(charcode) {
  23015. var fontCharCode, width, operatorListId;
  23016. var widthCode = charcode;
  23017. if (this.cMap && this.cMap.contains(charcode)) {
  23018. widthCode = this.cMap.lookup(charcode);
  23019. }
  23020. width = this.widths[widthCode];
  23021. width = isNum(width) ? width : this.defaultWidth;
  23022. var vmetric = this.vmetrics && this.vmetrics[widthCode];
  23023. var unicode = this.toUnicode.get(charcode) || charcode;
  23024. if (typeof unicode === 'number') {
  23025. unicode = String.fromCharCode(unicode);
  23026. }
  23027. // First try the toFontChar map, if it's not there then try falling
  23028. // back to the char code.
  23029. fontCharCode = this.toFontChar[charcode] || charcode;
  23030. if (this.missingFile) {
  23031. fontCharCode = mapSpecialUnicodeValues(fontCharCode);
  23032. }
  23033. if (this.isType3Font) {
  23034. // Font char code in this case is actually a glyph name.
  23035. operatorListId = fontCharCode;
  23036. }
  23037. var accent = null;
  23038. if (this.seacMap && this.seacMap[charcode]) {
  23039. var seac = this.seacMap[charcode];
  23040. fontCharCode = seac.baseFontCharCode;
  23041. accent = {
  23042. fontChar: String.fromCharCode(seac.accentFontCharCode),
  23043. offset: seac.accentOffset
  23044. };
  23045. }
  23046. var fontChar = String.fromCharCode(fontCharCode);
  23047. var glyph = this.glyphCache[charcode];
  23048. if (!glyph ||
  23049. !glyph.matchesForCache(fontChar, unicode, accent, width, vmetric,
  23050. operatorListId)) {
  23051. glyph = new Glyph(fontChar, unicode, accent, width, vmetric,
  23052. operatorListId);
  23053. this.glyphCache[charcode] = glyph;
  23054. }
  23055. return glyph;
  23056. },
  23057. charsToGlyphs: function Font_charsToGlyphs(chars) {
  23058. var charsCache = this.charsCache;
  23059. var glyphs, glyph, charcode;
  23060. // if we translated this string before, just grab it from the cache
  23061. if (charsCache) {
  23062. glyphs = charsCache[chars];
  23063. if (glyphs) {
  23064. return glyphs;
  23065. }
  23066. }
  23067. // lazily create the translation cache
  23068. if (!charsCache) {
  23069. charsCache = this.charsCache = Object.create(null);
  23070. }
  23071. glyphs = [];
  23072. var charsCacheKey = chars;
  23073. var i = 0, ii;
  23074. if (this.cMap) {
  23075. // composite fonts have multi-byte strings convert the string from
  23076. // single-byte to multi-byte
  23077. var c = {};
  23078. while (i < chars.length) {
  23079. this.cMap.readCharCode(chars, i, c);
  23080. charcode = c.charcode;
  23081. var length = c.length;
  23082. i += length;
  23083. glyph = this.charToGlyph(charcode);
  23084. glyphs.push(glyph);
  23085. // placing null after each word break charcode (ASCII SPACE)
  23086. // Ignore occurences of 0x20 in multiple-byte codes.
  23087. if (length === 1 && chars.charCodeAt(i - 1) === 0x20) {
  23088. glyphs.push(null);
  23089. }
  23090. }
  23091. } else {
  23092. for (i = 0, ii = chars.length; i < ii; ++i) {
  23093. charcode = chars.charCodeAt(i);
  23094. glyph = this.charToGlyph(charcode);
  23095. glyphs.push(glyph);
  23096. if (charcode === 0x20) {
  23097. glyphs.push(null);
  23098. }
  23099. }
  23100. }
  23101. // Enter the translated string into the cache
  23102. return (charsCache[charsCacheKey] = glyphs);
  23103. }
  23104. };
  23105. return Font;
  23106. })();
  23107. var ErrorFont = (function ErrorFontClosure() {
  23108. function ErrorFont(error) {
  23109. this.error = error;
  23110. this.loadedName = 'g_font_error';
  23111. this.loading = false;
  23112. }
  23113. ErrorFont.prototype = {
  23114. charsToGlyphs: function ErrorFont_charsToGlyphs() {
  23115. return [];
  23116. },
  23117. exportData: function ErrorFont_exportData() {
  23118. return {error: this.error};
  23119. }
  23120. };
  23121. return ErrorFont;
  23122. })();
  23123. /**
  23124. * Shared logic for building a char code to glyph id mapping for Type1 and
  23125. * simple CFF fonts. See section 9.6.6.2 of the spec.
  23126. * @param {Object} properties Font properties object.
  23127. * @param {Object} builtInEncoding The encoding contained within the actual font
  23128. * data.
  23129. * @param {Array} Array of glyph names where the index is the glyph ID.
  23130. * @returns {Object} A char code to glyph ID map.
  23131. */
  23132. function type1FontGlyphMapping(properties, builtInEncoding, glyphNames) {
  23133. var charCodeToGlyphId = Object.create(null);
  23134. var glyphId, charCode, baseEncoding;
  23135. if (properties.baseEncodingName) {
  23136. // If a valid base encoding name was used, the mapping is initialized with
  23137. // that.
  23138. baseEncoding = Encodings[properties.baseEncodingName];
  23139. for (charCode = 0; charCode < baseEncoding.length; charCode++) {
  23140. glyphId = glyphNames.indexOf(baseEncoding[charCode]);
  23141. if (glyphId >= 0) {
  23142. charCodeToGlyphId[charCode] = glyphId;
  23143. } else {
  23144. charCodeToGlyphId[charCode] = 0; // notdef
  23145. }
  23146. }
  23147. } else if (!!(properties.flags & FontFlags.Symbolic)) {
  23148. // For a symbolic font the encoding should be the fonts built-in
  23149. // encoding.
  23150. for (charCode in builtInEncoding) {
  23151. charCodeToGlyphId[charCode] = builtInEncoding[charCode];
  23152. }
  23153. } else {
  23154. // For non-symbolic fonts that don't have a base encoding the standard
  23155. // encoding should be used.
  23156. baseEncoding = Encodings.StandardEncoding;
  23157. for (charCode = 0; charCode < baseEncoding.length; charCode++) {
  23158. glyphId = glyphNames.indexOf(baseEncoding[charCode]);
  23159. if (glyphId >= 0) {
  23160. charCodeToGlyphId[charCode] = glyphId;
  23161. } else {
  23162. charCodeToGlyphId[charCode] = 0; // notdef
  23163. }
  23164. }
  23165. }
  23166. // Lastly, merge in the differences.
  23167. var differences = properties.differences;
  23168. if (differences) {
  23169. for (charCode in differences) {
  23170. var glyphName = differences[charCode];
  23171. glyphId = glyphNames.indexOf(glyphName);
  23172. if (glyphId >= 0) {
  23173. charCodeToGlyphId[charCode] = glyphId;
  23174. } else {
  23175. charCodeToGlyphId[charCode] = 0; // notdef
  23176. }
  23177. }
  23178. }
  23179. return charCodeToGlyphId;
  23180. }
  23181. /*
  23182. * CharStrings are encoded following the the CharString Encoding sequence
  23183. * describe in Chapter 6 of the "Adobe Type1 Font Format" specification.
  23184. * The value in a byte indicates a command, a number, or subsequent bytes
  23185. * that are to be interpreted in a special way.
  23186. *
  23187. * CharString Number Encoding:
  23188. * A CharString byte containing the values from 32 through 255 inclusive
  23189. * indicate an integer. These values are decoded in four ranges.
  23190. *
  23191. * 1. A CharString byte containing a value, v, between 32 and 246 inclusive,
  23192. * indicate the integer v - 139. Thus, the integer values from -107 through
  23193. * 107 inclusive may be encoded in single byte.
  23194. *
  23195. * 2. A CharString byte containing a value, v, between 247 and 250 inclusive,
  23196. * indicates an integer involving the next byte, w, according to the formula:
  23197. * [(v - 247) x 256] + w + 108
  23198. *
  23199. * 3. A CharString byte containing a value, v, between 251 and 254 inclusive,
  23200. * indicates an integer involving the next byte, w, according to the formula:
  23201. * -[(v - 251) * 256] - w - 108
  23202. *
  23203. * 4. A CharString containing the value 255 indicates that the next 4 bytes
  23204. * are a two complement signed integer. The first of these bytes contains the
  23205. * highest order bits, the second byte contains the next higher order bits
  23206. * and the fourth byte contain the lowest order bits.
  23207. *
  23208. *
  23209. * CharString Command Encoding:
  23210. * CharStrings commands are encoded in 1 or 2 bytes.
  23211. *
  23212. * Single byte commands are encoded in 1 byte that contains a value between
  23213. * 0 and 31 inclusive.
  23214. * If a command byte contains the value 12, then the value in the next byte
  23215. * indicates a command. This "escape" mechanism allows many extra commands
  23216. * to be encoded and this encoding technique helps to minimize the length of
  23217. * the charStrings.
  23218. */
  23219. var Type1CharString = (function Type1CharStringClosure() {
  23220. var COMMAND_MAP = {
  23221. 'hstem': [1],
  23222. 'vstem': [3],
  23223. 'vmoveto': [4],
  23224. 'rlineto': [5],
  23225. 'hlineto': [6],
  23226. 'vlineto': [7],
  23227. 'rrcurveto': [8],
  23228. 'callsubr': [10],
  23229. 'flex': [12, 35],
  23230. 'drop' : [12, 18],
  23231. 'endchar': [14],
  23232. 'rmoveto': [21],
  23233. 'hmoveto': [22],
  23234. 'vhcurveto': [30],
  23235. 'hvcurveto': [31]
  23236. };
  23237. function Type1CharString() {
  23238. this.width = 0;
  23239. this.lsb = 0;
  23240. this.flexing = false;
  23241. this.output = [];
  23242. this.stack = [];
  23243. }
  23244. Type1CharString.prototype = {
  23245. convert: function Type1CharString_convert(encoded, subrs) {
  23246. var count = encoded.length;
  23247. var error = false;
  23248. var wx, sbx, subrNumber;
  23249. for (var i = 0; i < count; i++) {
  23250. var value = encoded[i];
  23251. if (value < 32) {
  23252. if (value === 12) {
  23253. value = (value << 8) + encoded[++i];
  23254. }
  23255. switch (value) {
  23256. case 1: // hstem
  23257. if (!HINTING_ENABLED) {
  23258. this.stack = [];
  23259. break;
  23260. }
  23261. error = this.executeCommand(2, COMMAND_MAP.hstem);
  23262. break;
  23263. case 3: // vstem
  23264. if (!HINTING_ENABLED) {
  23265. this.stack = [];
  23266. break;
  23267. }
  23268. error = this.executeCommand(2, COMMAND_MAP.vstem);
  23269. break;
  23270. case 4: // vmoveto
  23271. if (this.flexing) {
  23272. if (this.stack.length < 1) {
  23273. error = true;
  23274. break;
  23275. }
  23276. // Add the dx for flex and but also swap the values so they are
  23277. // the right order.
  23278. var dy = this.stack.pop();
  23279. this.stack.push(0, dy);
  23280. break;
  23281. }
  23282. error = this.executeCommand(1, COMMAND_MAP.vmoveto);
  23283. break;
  23284. case 5: // rlineto
  23285. error = this.executeCommand(2, COMMAND_MAP.rlineto);
  23286. break;
  23287. case 6: // hlineto
  23288. error = this.executeCommand(1, COMMAND_MAP.hlineto);
  23289. break;
  23290. case 7: // vlineto
  23291. error = this.executeCommand(1, COMMAND_MAP.vlineto);
  23292. break;
  23293. case 8: // rrcurveto
  23294. error = this.executeCommand(6, COMMAND_MAP.rrcurveto);
  23295. break;
  23296. case 9: // closepath
  23297. // closepath is a Type1 command that does not take argument and is
  23298. // useless in Type2 and it can simply be ignored.
  23299. this.stack = [];
  23300. break;
  23301. case 10: // callsubr
  23302. if (this.stack.length < 1) {
  23303. error = true;
  23304. break;
  23305. }
  23306. subrNumber = this.stack.pop();
  23307. error = this.convert(subrs[subrNumber], subrs);
  23308. break;
  23309. case 11: // return
  23310. return error;
  23311. case 13: // hsbw
  23312. if (this.stack.length < 2) {
  23313. error = true;
  23314. break;
  23315. }
  23316. // To convert to type2 we have to move the width value to the
  23317. // first part of the charstring and then use hmoveto with lsb.
  23318. wx = this.stack.pop();
  23319. sbx = this.stack.pop();
  23320. this.lsb = sbx;
  23321. this.width = wx;
  23322. this.stack.push(wx, sbx);
  23323. error = this.executeCommand(2, COMMAND_MAP.hmoveto);
  23324. break;
  23325. case 14: // endchar
  23326. this.output.push(COMMAND_MAP.endchar[0]);
  23327. break;
  23328. case 21: // rmoveto
  23329. if (this.flexing) {
  23330. break;
  23331. }
  23332. error = this.executeCommand(2, COMMAND_MAP.rmoveto);
  23333. break;
  23334. case 22: // hmoveto
  23335. if (this.flexing) {
  23336. // Add the dy for flex.
  23337. this.stack.push(0);
  23338. break;
  23339. }
  23340. error = this.executeCommand(1, COMMAND_MAP.hmoveto);
  23341. break;
  23342. case 30: // vhcurveto
  23343. error = this.executeCommand(4, COMMAND_MAP.vhcurveto);
  23344. break;
  23345. case 31: // hvcurveto
  23346. error = this.executeCommand(4, COMMAND_MAP.hvcurveto);
  23347. break;
  23348. case (12 << 8) + 0: // dotsection
  23349. // dotsection is a Type1 command to specify some hinting feature
  23350. // for dots that do not take a parameter and it can safely be
  23351. // ignored for Type2.
  23352. this.stack = [];
  23353. break;
  23354. case (12 << 8) + 1: // vstem3
  23355. if (!HINTING_ENABLED) {
  23356. this.stack = [];
  23357. break;
  23358. }
  23359. // [vh]stem3 are Type1 only and Type2 supports [vh]stem with
  23360. // multiple parameters, so instead of returning [vh]stem3 take a
  23361. // shortcut and return [vhstem] instead.
  23362. error = this.executeCommand(2, COMMAND_MAP.vstem);
  23363. break;
  23364. case (12 << 8) + 2: // hstem3
  23365. if (!HINTING_ENABLED) {
  23366. this.stack = [];
  23367. break;
  23368. }
  23369. // See vstem3.
  23370. error = this.executeCommand(2, COMMAND_MAP.hstem);
  23371. break;
  23372. case (12 << 8) + 6: // seac
  23373. // seac is like type 2's special endchar but it doesn't use the
  23374. // first argument asb, so remove it.
  23375. if (SEAC_ANALYSIS_ENABLED) {
  23376. this.seac = this.stack.splice(-4, 4);
  23377. error = this.executeCommand(0, COMMAND_MAP.endchar);
  23378. } else {
  23379. error = this.executeCommand(4, COMMAND_MAP.endchar);
  23380. }
  23381. break;
  23382. case (12 << 8) + 7: // sbw
  23383. if (this.stack.length < 4) {
  23384. error = true;
  23385. break;
  23386. }
  23387. // To convert to type2 we have to move the width value to the
  23388. // first part of the charstring and then use rmoveto with
  23389. // (dx, dy). The height argument will not be used for vmtx and
  23390. // vhea tables reconstruction -- ignoring it.
  23391. var wy = this.stack.pop();
  23392. wx = this.stack.pop();
  23393. var sby = this.stack.pop();
  23394. sbx = this.stack.pop();
  23395. this.lsb = sbx;
  23396. this.width = wx;
  23397. this.stack.push(wx, sbx, sby);
  23398. error = this.executeCommand(3, COMMAND_MAP.rmoveto);
  23399. break;
  23400. case (12 << 8) + 12: // div
  23401. if (this.stack.length < 2) {
  23402. error = true;
  23403. break;
  23404. }
  23405. var num2 = this.stack.pop();
  23406. var num1 = this.stack.pop();
  23407. this.stack.push(num1 / num2);
  23408. break;
  23409. case (12 << 8) + 16: // callothersubr
  23410. if (this.stack.length < 2) {
  23411. error = true;
  23412. break;
  23413. }
  23414. subrNumber = this.stack.pop();
  23415. var numArgs = this.stack.pop();
  23416. if (subrNumber === 0 && numArgs === 3) {
  23417. var flexArgs = this.stack.splice(this.stack.length - 17, 17);
  23418. this.stack.push(
  23419. flexArgs[2] + flexArgs[0], // bcp1x + rpx
  23420. flexArgs[3] + flexArgs[1], // bcp1y + rpy
  23421. flexArgs[4], // bcp2x
  23422. flexArgs[5], // bcp2y
  23423. flexArgs[6], // p2x
  23424. flexArgs[7], // p2y
  23425. flexArgs[8], // bcp3x
  23426. flexArgs[9], // bcp3y
  23427. flexArgs[10], // bcp4x
  23428. flexArgs[11], // bcp4y
  23429. flexArgs[12], // p3x
  23430. flexArgs[13], // p3y
  23431. flexArgs[14] // flexDepth
  23432. // 15 = finalx unused by flex
  23433. // 16 = finaly unused by flex
  23434. );
  23435. error = this.executeCommand(13, COMMAND_MAP.flex, true);
  23436. this.flexing = false;
  23437. this.stack.push(flexArgs[15], flexArgs[16]);
  23438. } else if (subrNumber === 1 && numArgs === 0) {
  23439. this.flexing = true;
  23440. }
  23441. break;
  23442. case (12 << 8) + 17: // pop
  23443. // Ignore this since it is only used with othersubr.
  23444. break;
  23445. case (12 << 8) + 33: // setcurrentpoint
  23446. // Ignore for now.
  23447. this.stack = [];
  23448. break;
  23449. default:
  23450. warn('Unknown type 1 charstring command of "' + value + '"');
  23451. break;
  23452. }
  23453. if (error) {
  23454. break;
  23455. }
  23456. continue;
  23457. } else if (value <= 246) {
  23458. value = value - 139;
  23459. } else if (value <= 250) {
  23460. value = ((value - 247) * 256) + encoded[++i] + 108;
  23461. } else if (value <= 254) {
  23462. value = -((value - 251) * 256) - encoded[++i] - 108;
  23463. } else {
  23464. value = (encoded[++i] & 0xff) << 24 | (encoded[++i] & 0xff) << 16 |
  23465. (encoded[++i] & 0xff) << 8 | (encoded[++i] & 0xff) << 0;
  23466. }
  23467. this.stack.push(value);
  23468. }
  23469. return error;
  23470. },
  23471. executeCommand: function(howManyArgs, command, keepStack) {
  23472. var stackLength = this.stack.length;
  23473. if (howManyArgs > stackLength) {
  23474. return true;
  23475. }
  23476. var start = stackLength - howManyArgs;
  23477. for (var i = start; i < stackLength; i++) {
  23478. var value = this.stack[i];
  23479. if (value === (value | 0)) { // int
  23480. this.output.push(28, (value >> 8) & 0xff, value & 0xff);
  23481. } else { // fixed point
  23482. value = (65536 * value) | 0;
  23483. this.output.push(255,
  23484. (value >> 24) & 0xFF,
  23485. (value >> 16) & 0xFF,
  23486. (value >> 8) & 0xFF,
  23487. value & 0xFF);
  23488. }
  23489. }
  23490. this.output.push.apply(this.output, command);
  23491. if (keepStack) {
  23492. this.stack.splice(start, howManyArgs);
  23493. } else {
  23494. this.stack.length = 0;
  23495. }
  23496. return false;
  23497. }
  23498. };
  23499. return Type1CharString;
  23500. })();
  23501. /*
  23502. * Type1Parser encapsulate the needed code for parsing a Type1 font
  23503. * program. Some of its logic depends on the Type2 charstrings
  23504. * structure.
  23505. * Note: this doesn't really parse the font since that would require evaluation
  23506. * of PostScript, but it is possible in most cases to extract what we need
  23507. * without a full parse.
  23508. */
  23509. var Type1Parser = (function Type1ParserClosure() {
  23510. /*
  23511. * Decrypt a Sequence of Ciphertext Bytes to Produce the Original Sequence
  23512. * of Plaintext Bytes. The function took a key as a parameter which can be
  23513. * for decrypting the eexec block of for decoding charStrings.
  23514. */
  23515. var EEXEC_ENCRYPT_KEY = 55665;
  23516. var CHAR_STRS_ENCRYPT_KEY = 4330;
  23517. function isHexDigit(code) {
  23518. return code >= 48 && code <= 57 || // '0'-'9'
  23519. code >= 65 && code <= 70 || // 'A'-'F'
  23520. code >= 97 && code <= 102; // 'a'-'f'
  23521. }
  23522. function decrypt(data, key, discardNumber) {
  23523. var r = key | 0, c1 = 52845, c2 = 22719;
  23524. var count = data.length;
  23525. var decrypted = new Uint8Array(count);
  23526. for (var i = 0; i < count; i++) {
  23527. var value = data[i];
  23528. decrypted[i] = value ^ (r >> 8);
  23529. r = ((value + r) * c1 + c2) & ((1 << 16) - 1);
  23530. }
  23531. return Array.prototype.slice.call(decrypted, discardNumber);
  23532. }
  23533. function decryptAscii(data, key, discardNumber) {
  23534. var r = key | 0, c1 = 52845, c2 = 22719;
  23535. var count = data.length, maybeLength = count >>> 1;
  23536. var decrypted = new Uint8Array(maybeLength);
  23537. var i, j;
  23538. for (i = 0, j = 0; i < count; i++) {
  23539. var digit1 = data[i];
  23540. if (!isHexDigit(digit1)) {
  23541. continue;
  23542. }
  23543. i++;
  23544. var digit2;
  23545. while (i < count && !isHexDigit(digit2 = data[i])) {
  23546. i++;
  23547. }
  23548. if (i < count) {
  23549. var value = parseInt(String.fromCharCode(digit1, digit2), 16);
  23550. decrypted[j++] = value ^ (r >> 8);
  23551. r = ((value + r) * c1 + c2) & ((1 << 16) - 1);
  23552. }
  23553. }
  23554. return Array.prototype.slice.call(decrypted, discardNumber, j);
  23555. }
  23556. function isSpecial(c) {
  23557. return c === 0x2F || // '/'
  23558. c === 0x5B || c === 0x5D || // '[', ']'
  23559. c === 0x7B || c === 0x7D || // '{', '}'
  23560. c === 0x28 || c === 0x29; // '(', ')'
  23561. }
  23562. function Type1Parser(stream, encrypted) {
  23563. if (encrypted) {
  23564. var data = stream.getBytes();
  23565. var isBinary = !(isHexDigit(data[0]) && isHexDigit(data[1]) &&
  23566. isHexDigit(data[2]) && isHexDigit(data[3]));
  23567. stream = new Stream(isBinary ? decrypt(data, EEXEC_ENCRYPT_KEY, 4) :
  23568. decryptAscii(data, EEXEC_ENCRYPT_KEY, 4));
  23569. }
  23570. this.stream = stream;
  23571. this.nextChar();
  23572. }
  23573. Type1Parser.prototype = {
  23574. readNumberArray: function Type1Parser_readNumberArray() {
  23575. this.getToken(); // read '[' or '{' (arrays can start with either)
  23576. var array = [];
  23577. while (true) {
  23578. var token = this.getToken();
  23579. if (token === null || token === ']' || token === '}') {
  23580. break;
  23581. }
  23582. array.push(parseFloat(token || 0));
  23583. }
  23584. return array;
  23585. },
  23586. readNumber: function Type1Parser_readNumber() {
  23587. var token = this.getToken();
  23588. return parseFloat(token || 0);
  23589. },
  23590. readInt: function Type1Parser_readInt() {
  23591. // Use '| 0' to prevent setting a double into length such as the double
  23592. // does not flow into the loop variable.
  23593. var token = this.getToken();
  23594. return parseInt(token || 0, 10) | 0;
  23595. },
  23596. readBoolean: function Type1Parser_readBoolean() {
  23597. var token = this.getToken();
  23598. // Use 1 and 0 since that's what type2 charstrings use.
  23599. return token === 'true' ? 1 : 0;
  23600. },
  23601. nextChar : function Type1_nextChar() {
  23602. return (this.currentChar = this.stream.getByte());
  23603. },
  23604. getToken: function Type1Parser_getToken() {
  23605. // Eat whitespace and comments.
  23606. var comment = false;
  23607. var ch = this.currentChar;
  23608. while (true) {
  23609. if (ch === -1) {
  23610. return null;
  23611. }
  23612. if (comment) {
  23613. if (ch === 0x0A || ch === 0x0D) {
  23614. comment = false;
  23615. }
  23616. } else if (ch === 0x25) { // '%'
  23617. comment = true;
  23618. } else if (!Lexer.isSpace(ch)) {
  23619. break;
  23620. }
  23621. ch = this.nextChar();
  23622. }
  23623. if (isSpecial(ch)) {
  23624. this.nextChar();
  23625. return String.fromCharCode(ch);
  23626. }
  23627. var token = '';
  23628. do {
  23629. token += String.fromCharCode(ch);
  23630. ch = this.nextChar();
  23631. } while (ch >= 0 && !Lexer.isSpace(ch) && !isSpecial(ch));
  23632. return token;
  23633. },
  23634. /*
  23635. * Returns an object containing a Subrs array and a CharStrings
  23636. * array extracted from and eexec encrypted block of data
  23637. */
  23638. extractFontProgram: function Type1Parser_extractFontProgram() {
  23639. var stream = this.stream;
  23640. var subrs = [], charstrings = [];
  23641. var program = {
  23642. subrs: [],
  23643. charstrings: [],
  23644. properties: {
  23645. 'privateData': {
  23646. 'lenIV': 4
  23647. }
  23648. }
  23649. };
  23650. var token, length, data, lenIV, encoded;
  23651. while ((token = this.getToken()) !== null) {
  23652. if (token !== '/') {
  23653. continue;
  23654. }
  23655. token = this.getToken();
  23656. switch (token) {
  23657. case 'CharStrings':
  23658. // The number immediately following CharStrings must be greater or
  23659. // equal to the number of CharStrings.
  23660. this.getToken();
  23661. this.getToken(); // read in 'dict'
  23662. this.getToken(); // read in 'dup'
  23663. this.getToken(); // read in 'begin'
  23664. while(true) {
  23665. token = this.getToken();
  23666. if (token === null || token === 'end') {
  23667. break;
  23668. }
  23669. if (token !== '/') {
  23670. continue;
  23671. }
  23672. var glyph = this.getToken();
  23673. length = this.readInt();
  23674. this.getToken(); // read in 'RD' or '-|'
  23675. data = stream.makeSubStream(stream.pos, length);
  23676. lenIV = program.properties.privateData['lenIV'];
  23677. encoded = decrypt(data.getBytes(), CHAR_STRS_ENCRYPT_KEY, lenIV);
  23678. // Skip past the required space and binary data.
  23679. stream.skip(length);
  23680. this.nextChar();
  23681. token = this.getToken(); // read in 'ND' or '|-'
  23682. if (token === 'noaccess') {
  23683. this.getToken(); // read in 'def'
  23684. }
  23685. charstrings.push({
  23686. glyph: glyph,
  23687. encoded: encoded
  23688. });
  23689. }
  23690. break;
  23691. case 'Subrs':
  23692. var num = this.readInt();
  23693. this.getToken(); // read in 'array'
  23694. while ((token = this.getToken()) === 'dup') {
  23695. var index = this.readInt();
  23696. length = this.readInt();
  23697. this.getToken(); // read in 'RD' or '-|'
  23698. data = stream.makeSubStream(stream.pos, length);
  23699. lenIV = program.properties.privateData['lenIV'];
  23700. encoded = decrypt(data.getBytes(), CHAR_STRS_ENCRYPT_KEY, lenIV);
  23701. // Skip past the required space and binary data.
  23702. stream.skip(length);
  23703. this.nextChar();
  23704. token = this.getToken(); // read in 'NP' or '|'
  23705. if (token === 'noaccess') {
  23706. this.getToken(); // read in 'put'
  23707. }
  23708. subrs[index] = encoded;
  23709. }
  23710. break;
  23711. case 'BlueValues':
  23712. case 'OtherBlues':
  23713. case 'FamilyBlues':
  23714. case 'FamilyOtherBlues':
  23715. var blueArray = this.readNumberArray();
  23716. // *Blue* values may contain invalid data: disables reading of
  23717. // those values when hinting is disabled.
  23718. if (blueArray.length > 0 && (blueArray.length % 2) === 0 &&
  23719. HINTING_ENABLED) {
  23720. program.properties.privateData[token] = blueArray;
  23721. }
  23722. break;
  23723. case 'StemSnapH':
  23724. case 'StemSnapV':
  23725. program.properties.privateData[token] = this.readNumberArray();
  23726. break;
  23727. case 'StdHW':
  23728. case 'StdVW':
  23729. program.properties.privateData[token] =
  23730. this.readNumberArray()[0];
  23731. break;
  23732. case 'BlueShift':
  23733. case 'lenIV':
  23734. case 'BlueFuzz':
  23735. case 'BlueScale':
  23736. case 'LanguageGroup':
  23737. case 'ExpansionFactor':
  23738. program.properties.privateData[token] = this.readNumber();
  23739. break;
  23740. case 'ForceBold':
  23741. program.properties.privateData[token] = this.readBoolean();
  23742. break;
  23743. }
  23744. }
  23745. for (var i = 0; i < charstrings.length; i++) {
  23746. glyph = charstrings[i].glyph;
  23747. encoded = charstrings[i].encoded;
  23748. var charString = new Type1CharString();
  23749. var error = charString.convert(encoded, subrs);
  23750. var output = charString.output;
  23751. if (error) {
  23752. // It seems when FreeType encounters an error while evaluating a glyph
  23753. // that it completely ignores the glyph so we'll mimic that behaviour
  23754. // here and put an endchar to make the validator happy.
  23755. output = [14];
  23756. }
  23757. program.charstrings.push({
  23758. glyphName: glyph,
  23759. charstring: output,
  23760. width: charString.width,
  23761. lsb: charString.lsb,
  23762. seac: charString.seac
  23763. });
  23764. }
  23765. return program;
  23766. },
  23767. extractFontHeader: function Type1Parser_extractFontHeader(properties) {
  23768. var token;
  23769. while ((token = this.getToken()) !== null) {
  23770. if (token !== '/') {
  23771. continue;
  23772. }
  23773. token = this.getToken();
  23774. switch (token) {
  23775. case 'FontMatrix':
  23776. var matrix = this.readNumberArray();
  23777. properties.fontMatrix = matrix;
  23778. break;
  23779. case 'Encoding':
  23780. var encodingArg = this.getToken();
  23781. var encoding;
  23782. if (!/^\d+$/.test(encodingArg)) {
  23783. // encoding name is specified
  23784. encoding = Encodings[encodingArg];
  23785. } else {
  23786. encoding = [];
  23787. var size = parseInt(encodingArg, 10) | 0;
  23788. this.getToken(); // read in 'array'
  23789. for (var j = 0; j < size; j++) {
  23790. token = this.getToken();
  23791. // skipping till first dup or def (e.g. ignoring for statement)
  23792. while (token !== 'dup' && token !== 'def') {
  23793. token = this.getToken();
  23794. if (token === null) {
  23795. return; // invalid header
  23796. }
  23797. }
  23798. if (token === 'def') {
  23799. break; // read all array data
  23800. }
  23801. var index = this.readInt();
  23802. this.getToken(); // read in '/'
  23803. var glyph = this.getToken();
  23804. encoding[index] = glyph;
  23805. this.getToken(); // read the in 'put'
  23806. }
  23807. }
  23808. properties.builtInEncoding = encoding;
  23809. break;
  23810. case 'FontBBox':
  23811. var fontBBox = this.readNumberArray();
  23812. // adjusting ascent/descent
  23813. properties.ascent = fontBBox[3];
  23814. properties.descent = fontBBox[1];
  23815. properties.ascentScaled = true;
  23816. break;
  23817. }
  23818. }
  23819. }
  23820. };
  23821. return Type1Parser;
  23822. })();
  23823. /**
  23824. * The CFF class takes a Type1 file and wrap it into a
  23825. * 'Compact Font Format' which itself embed Type2 charstrings.
  23826. */
  23827. var CFFStandardStrings = [
  23828. '.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent',
  23829. 'ampersand', 'quoteright', 'parenleft', 'parenright', 'asterisk', 'plus',
  23830. 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four',
  23831. 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less',
  23832. 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
  23833. 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  23834. 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum',
  23835. 'underscore', 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
  23836. 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
  23837. 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', 'exclamdown', 'cent',
  23838. 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency',
  23839. 'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft',
  23840. 'guilsinglright', 'fi', 'fl', 'endash', 'dagger', 'daggerdbl',
  23841. 'periodcentered', 'paragraph', 'bullet', 'quotesinglbase', 'quotedblbase',
  23842. 'quotedblright', 'guillemotright', 'ellipsis', 'perthousand', 'questiondown',
  23843. 'grave', 'acute', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent',
  23844. 'dieresis', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron', 'emdash',
  23845. 'AE', 'ordfeminine', 'Lslash', 'Oslash', 'OE', 'ordmasculine', 'ae',
  23846. 'dotlessi', 'lslash', 'oslash', 'oe', 'germandbls', 'onesuperior',
  23847. 'logicalnot', 'mu', 'trademark', 'Eth', 'onehalf', 'plusminus', 'Thorn',
  23848. 'onequarter', 'divide', 'brokenbar', 'degree', 'thorn', 'threequarters',
  23849. 'twosuperior', 'registered', 'minus', 'eth', 'multiply', 'threesuperior',
  23850. 'copyright', 'Aacute', 'Acircumflex', 'Adieresis', 'Agrave', 'Aring',
  23851. 'Atilde', 'Ccedilla', 'Eacute', 'Ecircumflex', 'Edieresis', 'Egrave',
  23852. 'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Ntilde', 'Oacute',
  23853. 'Ocircumflex', 'Odieresis', 'Ograve', 'Otilde', 'Scaron', 'Uacute',
  23854. 'Ucircumflex', 'Udieresis', 'Ugrave', 'Yacute', 'Ydieresis', 'Zcaron',
  23855. 'aacute', 'acircumflex', 'adieresis', 'agrave', 'aring', 'atilde',
  23856. 'ccedilla', 'eacute', 'ecircumflex', 'edieresis', 'egrave', 'iacute',
  23857. 'icircumflex', 'idieresis', 'igrave', 'ntilde', 'oacute', 'ocircumflex',
  23858. 'odieresis', 'ograve', 'otilde', 'scaron', 'uacute', 'ucircumflex',
  23859. 'udieresis', 'ugrave', 'yacute', 'ydieresis', 'zcaron', 'exclamsmall',
  23860. 'Hungarumlautsmall', 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall',
  23861. 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader',
  23862. 'onedotenleader', 'zerooldstyle', 'oneoldstyle', 'twooldstyle',
  23863. 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle',
  23864. 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'commasuperior',
  23865. 'threequartersemdash', 'periodsuperior', 'questionsmall', 'asuperior',
  23866. 'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', 'isuperior',
  23867. 'lsuperior', 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior',
  23868. 'tsuperior', 'ff', 'ffi', 'ffl', 'parenleftinferior', 'parenrightinferior',
  23869. 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall', 'Bsmall',
  23870. 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall',
  23871. 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', 'Osmall', 'Psmall',
  23872. 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall',
  23873. 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah',
  23874. 'Tildesmall', 'exclamdownsmall', 'centoldstyle', 'Lslashsmall',
  23875. 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall', 'Caronsmall',
  23876. 'Dotaccentsmall', 'Macronsmall', 'figuredash', 'hypheninferior',
  23877. 'Ogoneksmall', 'Ringsmall', 'Cedillasmall', 'questiondownsmall', 'oneeighth',
  23878. 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds',
  23879. 'zerosuperior', 'foursuperior', 'fivesuperior', 'sixsuperior',
  23880. 'sevensuperior', 'eightsuperior', 'ninesuperior', 'zeroinferior',
  23881. 'oneinferior', 'twoinferior', 'threeinferior', 'fourinferior',
  23882. 'fiveinferior', 'sixinferior', 'seveninferior', 'eightinferior',
  23883. 'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior',
  23884. 'commainferior', 'Agravesmall', 'Aacutesmall', 'Acircumflexsmall',
  23885. 'Atildesmall', 'Adieresissmall', 'Aringsmall', 'AEsmall', 'Ccedillasmall',
  23886. 'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall',
  23887. 'Igravesmall', 'Iacutesmall', 'Icircumflexsmall', 'Idieresissmall',
  23888. 'Ethsmall', 'Ntildesmall', 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall',
  23889. 'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall',
  23890. 'Uacutesmall', 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall',
  23891. 'Thornsmall', 'Ydieresissmall', '001.000', '001.001', '001.002', '001.003',
  23892. 'Black', 'Bold', 'Book', 'Light', 'Medium', 'Regular', 'Roman', 'Semibold'
  23893. ];
  23894. // Type1Font is also a CIDFontType0.
  23895. var Type1Font = function Type1Font(name, file, properties) {
  23896. // Some bad generators embed pfb file as is, we have to strip 6-byte headers.
  23897. // Also, length1 and length2 might be off by 6 bytes as well.
  23898. // http://www.math.ubc.ca/~cass/piscript/type1.pdf
  23899. var PFB_HEADER_SIZE = 6;
  23900. var headerBlockLength = properties.length1;
  23901. var eexecBlockLength = properties.length2;
  23902. var pfbHeader = file.peekBytes(PFB_HEADER_SIZE);
  23903. var pfbHeaderPresent = pfbHeader[0] === 0x80 && pfbHeader[1] === 0x01;
  23904. if (pfbHeaderPresent) {
  23905. file.skip(PFB_HEADER_SIZE);
  23906. headerBlockLength = (pfbHeader[5] << 24) | (pfbHeader[4] << 16) |
  23907. (pfbHeader[3] << 8) | pfbHeader[2];
  23908. }
  23909. // Get the data block containing glyphs and subrs informations
  23910. var headerBlock = new Stream(file.getBytes(headerBlockLength));
  23911. var headerBlockParser = new Type1Parser(headerBlock);
  23912. headerBlockParser.extractFontHeader(properties);
  23913. if (pfbHeaderPresent) {
  23914. pfbHeader = file.getBytes(PFB_HEADER_SIZE);
  23915. eexecBlockLength = (pfbHeader[5] << 24) | (pfbHeader[4] << 16) |
  23916. (pfbHeader[3] << 8) | pfbHeader[2];
  23917. }
  23918. // Decrypt the data blocks and retrieve it's content
  23919. var eexecBlock = new Stream(file.getBytes(eexecBlockLength));
  23920. var eexecBlockParser = new Type1Parser(eexecBlock, true);
  23921. var data = eexecBlockParser.extractFontProgram();
  23922. for (var info in data.properties) {
  23923. properties[info] = data.properties[info];
  23924. }
  23925. var charstrings = data.charstrings;
  23926. var type2Charstrings = this.getType2Charstrings(charstrings);
  23927. var subrs = this.getType2Subrs(data.subrs);
  23928. this.charstrings = charstrings;
  23929. this.data = this.wrap(name, type2Charstrings, this.charstrings,
  23930. subrs, properties);
  23931. this.seacs = this.getSeacs(data.charstrings);
  23932. };
  23933. Type1Font.prototype = {
  23934. get numGlyphs() {
  23935. return this.charstrings.length + 1;
  23936. },
  23937. getCharset: function Type1Font_getCharset() {
  23938. var charset = ['.notdef'];
  23939. var charstrings = this.charstrings;
  23940. for (var glyphId = 0; glyphId < charstrings.length; glyphId++) {
  23941. charset.push(charstrings[glyphId].glyphName);
  23942. }
  23943. return charset;
  23944. },
  23945. getGlyphMapping: function Type1Font_getGlyphMapping(properties) {
  23946. var charstrings = this.charstrings;
  23947. var glyphNames = ['.notdef'], glyphId;
  23948. for (glyphId = 0; glyphId < charstrings.length; glyphId++) {
  23949. glyphNames.push(charstrings[glyphId].glyphName);
  23950. }
  23951. var encoding = properties.builtInEncoding;
  23952. if (encoding) {
  23953. var builtInEncoding = {};
  23954. for (var charCode in encoding) {
  23955. glyphId = glyphNames.indexOf(encoding[charCode]);
  23956. if (glyphId >= 0) {
  23957. builtInEncoding[charCode] = glyphId;
  23958. }
  23959. }
  23960. }
  23961. return type1FontGlyphMapping(properties, builtInEncoding, glyphNames);
  23962. },
  23963. getSeacs: function Type1Font_getSeacs(charstrings) {
  23964. var i, ii;
  23965. var seacMap = [];
  23966. for (i = 0, ii = charstrings.length; i < ii; i++) {
  23967. var charstring = charstrings[i];
  23968. if (charstring.seac) {
  23969. // Offset by 1 for .notdef
  23970. seacMap[i + 1] = charstring.seac;
  23971. }
  23972. }
  23973. return seacMap;
  23974. },
  23975. getType2Charstrings: function Type1Font_getType2Charstrings(
  23976. type1Charstrings) {
  23977. var type2Charstrings = [];
  23978. for (var i = 0, ii = type1Charstrings.length; i < ii; i++) {
  23979. type2Charstrings.push(type1Charstrings[i].charstring);
  23980. }
  23981. return type2Charstrings;
  23982. },
  23983. getType2Subrs: function Type1Font_getType2Subrs(type1Subrs) {
  23984. var bias = 0;
  23985. var count = type1Subrs.length;
  23986. if (count < 1133) {
  23987. bias = 107;
  23988. } else if (count < 33769) {
  23989. bias = 1131;
  23990. } else {
  23991. bias = 32768;
  23992. }
  23993. // Add a bunch of empty subrs to deal with the Type2 bias
  23994. var type2Subrs = [];
  23995. var i;
  23996. for (i = 0; i < bias; i++) {
  23997. type2Subrs.push([0x0B]);
  23998. }
  23999. for (i = 0; i < count; i++) {
  24000. type2Subrs.push(type1Subrs[i]);
  24001. }
  24002. return type2Subrs;
  24003. },
  24004. wrap: function Type1Font_wrap(name, glyphs, charstrings, subrs, properties) {
  24005. var cff = new CFF();
  24006. cff.header = new CFFHeader(1, 0, 4, 4);
  24007. cff.names = [name];
  24008. var topDict = new CFFTopDict();
  24009. // CFF strings IDs 0...390 are predefined names, so refering
  24010. // to entries in our own String INDEX starts at SID 391.
  24011. topDict.setByName('version', 391);
  24012. topDict.setByName('Notice', 392);
  24013. topDict.setByName('FullName', 393);
  24014. topDict.setByName('FamilyName', 394);
  24015. topDict.setByName('Weight', 395);
  24016. topDict.setByName('Encoding', null); // placeholder
  24017. topDict.setByName('FontMatrix', properties.fontMatrix);
  24018. topDict.setByName('FontBBox', properties.bbox);
  24019. topDict.setByName('charset', null); // placeholder
  24020. topDict.setByName('CharStrings', null); // placeholder
  24021. topDict.setByName('Private', null); // placeholder
  24022. cff.topDict = topDict;
  24023. var strings = new CFFStrings();
  24024. strings.add('Version 0.11'); // Version
  24025. strings.add('See original notice'); // Notice
  24026. strings.add(name); // FullName
  24027. strings.add(name); // FamilyName
  24028. strings.add('Medium'); // Weight
  24029. cff.strings = strings;
  24030. cff.globalSubrIndex = new CFFIndex();
  24031. var count = glyphs.length;
  24032. var charsetArray = [0];
  24033. var i, ii;
  24034. for (i = 0; i < count; i++) {
  24035. var index = CFFStandardStrings.indexOf(charstrings[i].glyphName);
  24036. // TODO: Insert the string and correctly map it. Previously it was
  24037. // thought mapping names that aren't in the standard strings to .notdef
  24038. // was fine, however in issue818 when mapping them all to .notdef the
  24039. // adieresis glyph no longer worked.
  24040. if (index === -1) {
  24041. index = 0;
  24042. }
  24043. charsetArray.push((index >> 8) & 0xff, index & 0xff);
  24044. }
  24045. cff.charset = new CFFCharset(false, 0, [], charsetArray);
  24046. var charStringsIndex = new CFFIndex();
  24047. charStringsIndex.add([0x8B, 0x0E]); // .notdef
  24048. for (i = 0; i < count; i++) {
  24049. charStringsIndex.add(glyphs[i]);
  24050. }
  24051. cff.charStrings = charStringsIndex;
  24052. var privateDict = new CFFPrivateDict();
  24053. privateDict.setByName('Subrs', null); // placeholder
  24054. var fields = [
  24055. 'BlueValues',
  24056. 'OtherBlues',
  24057. 'FamilyBlues',
  24058. 'FamilyOtherBlues',
  24059. 'StemSnapH',
  24060. 'StemSnapV',
  24061. 'BlueShift',
  24062. 'BlueFuzz',
  24063. 'BlueScale',
  24064. 'LanguageGroup',
  24065. 'ExpansionFactor',
  24066. 'ForceBold',
  24067. 'StdHW',
  24068. 'StdVW'
  24069. ];
  24070. for (i = 0, ii = fields.length; i < ii; i++) {
  24071. var field = fields[i];
  24072. if (!properties.privateData.hasOwnProperty(field)) {
  24073. continue;
  24074. }
  24075. var value = properties.privateData[field];
  24076. if (isArray(value)) {
  24077. // All of the private dictionary array data in CFF must be stored as
  24078. // "delta-encoded" numbers.
  24079. for (var j = value.length - 1; j > 0; j--) {
  24080. value[j] -= value[j - 1]; // ... difference from previous value
  24081. }
  24082. }
  24083. privateDict.setByName(field, value);
  24084. }
  24085. cff.topDict.privateDict = privateDict;
  24086. var subrIndex = new CFFIndex();
  24087. for (i = 0, ii = subrs.length; i < ii; i++) {
  24088. subrIndex.add(subrs[i]);
  24089. }
  24090. privateDict.subrsIndex = subrIndex;
  24091. var compiler = new CFFCompiler(cff);
  24092. return compiler.compile();
  24093. }
  24094. };
  24095. var CFFFont = (function CFFFontClosure() {
  24096. function CFFFont(file, properties) {
  24097. this.properties = properties;
  24098. var parser = new CFFParser(file, properties);
  24099. this.cff = parser.parse();
  24100. var compiler = new CFFCompiler(this.cff);
  24101. this.seacs = this.cff.seacs;
  24102. try {
  24103. this.data = compiler.compile();
  24104. } catch (e) {
  24105. warn('Failed to compile font ' + properties.loadedName);
  24106. // There may have just been an issue with the compiler, set the data
  24107. // anyway and hope the font loaded.
  24108. this.data = file;
  24109. }
  24110. }
  24111. CFFFont.prototype = {
  24112. get numGlyphs() {
  24113. return this.cff.charStrings.count;
  24114. },
  24115. getCharset: function CFFFont_getCharset() {
  24116. return this.cff.charset.charset;
  24117. },
  24118. getGlyphMapping: function CFFFont_getGlyphMapping() {
  24119. var cff = this.cff;
  24120. var properties = this.properties;
  24121. var charsets = cff.charset.charset;
  24122. var charCodeToGlyphId;
  24123. var glyphId;
  24124. if (properties.composite) {
  24125. charCodeToGlyphId = Object.create(null);
  24126. if (cff.isCIDFont) {
  24127. // If the font is actually a CID font then we should use the charset
  24128. // to map CIDs to GIDs.
  24129. for (glyphId = 0; glyphId < charsets.length; glyphId++) {
  24130. var cid = charsets[glyphId];
  24131. var charCode = properties.cMap.charCodeOf(cid);
  24132. charCodeToGlyphId[charCode] = glyphId;
  24133. }
  24134. } else {
  24135. // If it is NOT actually a CID font then CIDs should be mapped
  24136. // directly to GIDs.
  24137. for (glyphId = 0; glyphId < cff.charStrings.count; glyphId++) {
  24138. charCodeToGlyphId[glyphId] = glyphId;
  24139. }
  24140. }
  24141. return charCodeToGlyphId;
  24142. }
  24143. var encoding = cff.encoding ? cff.encoding.encoding : null;
  24144. charCodeToGlyphId = type1FontGlyphMapping(properties, encoding, charsets);
  24145. return charCodeToGlyphId;
  24146. }
  24147. };
  24148. return CFFFont;
  24149. })();
  24150. var CFFParser = (function CFFParserClosure() {
  24151. var CharstringValidationData = [
  24152. null,
  24153. { id: 'hstem', min: 2, stackClearing: true, stem: true },
  24154. null,
  24155. { id: 'vstem', min: 2, stackClearing: true, stem: true },
  24156. { id: 'vmoveto', min: 1, stackClearing: true },
  24157. { id: 'rlineto', min: 2, resetStack: true },
  24158. { id: 'hlineto', min: 1, resetStack: true },
  24159. { id: 'vlineto', min: 1, resetStack: true },
  24160. { id: 'rrcurveto', min: 6, resetStack: true },
  24161. null,
  24162. { id: 'callsubr', min: 1, undefStack: true },
  24163. { id: 'return', min: 0, undefStack: true },
  24164. null, // 12
  24165. null,
  24166. { id: 'endchar', min: 0, stackClearing: true },
  24167. null,
  24168. null,
  24169. null,
  24170. { id: 'hstemhm', min: 2, stackClearing: true, stem: true },
  24171. { id: 'hintmask', min: 0, stackClearing: true },
  24172. { id: 'cntrmask', min: 0, stackClearing: true },
  24173. { id: 'rmoveto', min: 2, stackClearing: true },
  24174. { id: 'hmoveto', min: 1, stackClearing: true },
  24175. { id: 'vstemhm', min: 2, stackClearing: true, stem: true },
  24176. { id: 'rcurveline', min: 8, resetStack: true },
  24177. { id: 'rlinecurve', min: 8, resetStack: true },
  24178. { id: 'vvcurveto', min: 4, resetStack: true },
  24179. { id: 'hhcurveto', min: 4, resetStack: true },
  24180. null, // shortint
  24181. { id: 'callgsubr', min: 1, undefStack: true },
  24182. { id: 'vhcurveto', min: 4, resetStack: true },
  24183. { id: 'hvcurveto', min: 4, resetStack: true }
  24184. ];
  24185. var CharstringValidationData12 = [
  24186. null,
  24187. null,
  24188. null,
  24189. { id: 'and', min: 2, stackDelta: -1 },
  24190. { id: 'or', min: 2, stackDelta: -1 },
  24191. { id: 'not', min: 1, stackDelta: 0 },
  24192. null,
  24193. null,
  24194. null,
  24195. { id: 'abs', min: 1, stackDelta: 0 },
  24196. { id: 'add', min: 2, stackDelta: -1,
  24197. stackFn: function stack_div(stack, index) {
  24198. stack[index - 2] = stack[index - 2] + stack[index - 1];
  24199. }
  24200. },
  24201. { id: 'sub', min: 2, stackDelta: -1,
  24202. stackFn: function stack_div(stack, index) {
  24203. stack[index - 2] = stack[index - 2] - stack[index - 1];
  24204. }
  24205. },
  24206. { id: 'div', min: 2, stackDelta: -1,
  24207. stackFn: function stack_div(stack, index) {
  24208. stack[index - 2] = stack[index - 2] / stack[index - 1];
  24209. }
  24210. },
  24211. null,
  24212. { id: 'neg', min: 1, stackDelta: 0,
  24213. stackFn: function stack_div(stack, index) {
  24214. stack[index - 1] = -stack[index - 1];
  24215. }
  24216. },
  24217. { id: 'eq', min: 2, stackDelta: -1 },
  24218. null,
  24219. null,
  24220. { id: 'drop', min: 1, stackDelta: -1 },
  24221. null,
  24222. { id: 'put', min: 2, stackDelta: -2 },
  24223. { id: 'get', min: 1, stackDelta: 0 },
  24224. { id: 'ifelse', min: 4, stackDelta: -3 },
  24225. { id: 'random', min: 0, stackDelta: 1 },
  24226. { id: 'mul', min: 2, stackDelta: -1,
  24227. stackFn: function stack_div(stack, index) {
  24228. stack[index - 2] = stack[index - 2] * stack[index - 1];
  24229. }
  24230. },
  24231. null,
  24232. { id: 'sqrt', min: 1, stackDelta: 0 },
  24233. { id: 'dup', min: 1, stackDelta: 1 },
  24234. { id: 'exch', min: 2, stackDelta: 0 },
  24235. { id: 'index', min: 2, stackDelta: 0 },
  24236. { id: 'roll', min: 3, stackDelta: -2 },
  24237. null,
  24238. null,
  24239. null,
  24240. { id: 'hflex', min: 7, resetStack: true },
  24241. { id: 'flex', min: 13, resetStack: true },
  24242. { id: 'hflex1', min: 9, resetStack: true },
  24243. { id: 'flex1', min: 11, resetStack: true }
  24244. ];
  24245. function CFFParser(file, properties) {
  24246. this.bytes = file.getBytes();
  24247. this.properties = properties;
  24248. }
  24249. CFFParser.prototype = {
  24250. parse: function CFFParser_parse() {
  24251. var properties = this.properties;
  24252. var cff = new CFF();
  24253. this.cff = cff;
  24254. // The first five sections must be in order, all the others are reached
  24255. // via offsets contained in one of the below.
  24256. var header = this.parseHeader();
  24257. var nameIndex = this.parseIndex(header.endPos);
  24258. var topDictIndex = this.parseIndex(nameIndex.endPos);
  24259. var stringIndex = this.parseIndex(topDictIndex.endPos);
  24260. var globalSubrIndex = this.parseIndex(stringIndex.endPos);
  24261. var topDictParsed = this.parseDict(topDictIndex.obj.get(0));
  24262. var topDict = this.createDict(CFFTopDict, topDictParsed, cff.strings);
  24263. cff.header = header.obj;
  24264. cff.names = this.parseNameIndex(nameIndex.obj);
  24265. cff.strings = this.parseStringIndex(stringIndex.obj);
  24266. cff.topDict = topDict;
  24267. cff.globalSubrIndex = globalSubrIndex.obj;
  24268. this.parsePrivateDict(cff.topDict);
  24269. cff.isCIDFont = topDict.hasName('ROS');
  24270. var charStringOffset = topDict.getByName('CharStrings');
  24271. var charStringsAndSeacs = this.parseCharStrings(charStringOffset);
  24272. cff.charStrings = charStringsAndSeacs.charStrings;
  24273. cff.seacs = charStringsAndSeacs.seacs;
  24274. cff.widths = charStringsAndSeacs.widths;
  24275. var fontMatrix = topDict.getByName('FontMatrix');
  24276. if (fontMatrix) {
  24277. properties.fontMatrix = fontMatrix;
  24278. }
  24279. var fontBBox = topDict.getByName('FontBBox');
  24280. if (fontBBox) {
  24281. // adjusting ascent/descent
  24282. properties.ascent = fontBBox[3];
  24283. properties.descent = fontBBox[1];
  24284. properties.ascentScaled = true;
  24285. }
  24286. var charset, encoding;
  24287. if (cff.isCIDFont) {
  24288. var fdArrayIndex = this.parseIndex(topDict.getByName('FDArray')).obj;
  24289. for (var i = 0, ii = fdArrayIndex.count; i < ii; ++i) {
  24290. var dictRaw = fdArrayIndex.get(i);
  24291. var fontDict = this.createDict(CFFTopDict, this.parseDict(dictRaw),
  24292. cff.strings);
  24293. this.parsePrivateDict(fontDict);
  24294. cff.fdArray.push(fontDict);
  24295. }
  24296. // cid fonts don't have an encoding
  24297. encoding = null;
  24298. charset = this.parseCharsets(topDict.getByName('charset'),
  24299. cff.charStrings.count, cff.strings, true);
  24300. cff.fdSelect = this.parseFDSelect(topDict.getByName('FDSelect'),
  24301. cff.charStrings.count);
  24302. } else {
  24303. charset = this.parseCharsets(topDict.getByName('charset'),
  24304. cff.charStrings.count, cff.strings, false);
  24305. encoding = this.parseEncoding(topDict.getByName('Encoding'),
  24306. properties,
  24307. cff.strings, charset.charset);
  24308. }
  24309. cff.charset = charset;
  24310. cff.encoding = encoding;
  24311. return cff;
  24312. },
  24313. parseHeader: function CFFParser_parseHeader() {
  24314. var bytes = this.bytes;
  24315. var bytesLength = bytes.length;
  24316. var offset = 0;
  24317. // Prevent an infinite loop, by checking that the offset is within the
  24318. // bounds of the bytes array. Necessary in empty, or invalid, font files.
  24319. while (offset < bytesLength && bytes[offset] !== 1) {
  24320. ++offset;
  24321. }
  24322. if (offset >= bytesLength) {
  24323. error('Invalid CFF header');
  24324. } else if (offset !== 0) {
  24325. info('cff data is shifted');
  24326. bytes = bytes.subarray(offset);
  24327. this.bytes = bytes;
  24328. }
  24329. var major = bytes[0];
  24330. var minor = bytes[1];
  24331. var hdrSize = bytes[2];
  24332. var offSize = bytes[3];
  24333. var header = new CFFHeader(major, minor, hdrSize, offSize);
  24334. return { obj: header, endPos: hdrSize };
  24335. },
  24336. parseDict: function CFFParser_parseDict(dict) {
  24337. var pos = 0;
  24338. function parseOperand() {
  24339. var value = dict[pos++];
  24340. if (value === 30) {
  24341. return parseFloatOperand(pos);
  24342. } else if (value === 28) {
  24343. value = dict[pos++];
  24344. value = ((value << 24) | (dict[pos++] << 16)) >> 16;
  24345. return value;
  24346. } else if (value === 29) {
  24347. value = dict[pos++];
  24348. value = (value << 8) | dict[pos++];
  24349. value = (value << 8) | dict[pos++];
  24350. value = (value << 8) | dict[pos++];
  24351. return value;
  24352. } else if (value >= 32 && value <= 246) {
  24353. return value - 139;
  24354. } else if (value >= 247 && value <= 250) {
  24355. return ((value - 247) * 256) + dict[pos++] + 108;
  24356. } else if (value >= 251 && value <= 254) {
  24357. return -((value - 251) * 256) - dict[pos++] - 108;
  24358. } else {
  24359. error('255 is not a valid DICT command');
  24360. }
  24361. return -1;
  24362. }
  24363. function parseFloatOperand() {
  24364. var str = '';
  24365. var eof = 15;
  24366. var lookup = ['0', '1', '2', '3', '4', '5', '6', '7', '8',
  24367. '9', '.', 'E', 'E-', null, '-'];
  24368. var length = dict.length;
  24369. while (pos < length) {
  24370. var b = dict[pos++];
  24371. var b1 = b >> 4;
  24372. var b2 = b & 15;
  24373. if (b1 === eof) {
  24374. break;
  24375. }
  24376. str += lookup[b1];
  24377. if (b2 === eof) {
  24378. break;
  24379. }
  24380. str += lookup[b2];
  24381. }
  24382. return parseFloat(str);
  24383. }
  24384. var operands = [];
  24385. var entries = [];
  24386. pos = 0;
  24387. var end = dict.length;
  24388. while (pos < end) {
  24389. var b = dict[pos];
  24390. if (b <= 21) {
  24391. if (b === 12) {
  24392. b = (b << 8) | dict[++pos];
  24393. }
  24394. entries.push([b, operands]);
  24395. operands = [];
  24396. ++pos;
  24397. } else {
  24398. operands.push(parseOperand());
  24399. }
  24400. }
  24401. return entries;
  24402. },
  24403. parseIndex: function CFFParser_parseIndex(pos) {
  24404. var cffIndex = new CFFIndex();
  24405. var bytes = this.bytes;
  24406. var count = (bytes[pos++] << 8) | bytes[pos++];
  24407. var offsets = [];
  24408. var end = pos;
  24409. var i, ii;
  24410. if (count !== 0) {
  24411. var offsetSize = bytes[pos++];
  24412. // add 1 for offset to determine size of last object
  24413. var startPos = pos + ((count + 1) * offsetSize) - 1;
  24414. for (i = 0, ii = count + 1; i < ii; ++i) {
  24415. var offset = 0;
  24416. for (var j = 0; j < offsetSize; ++j) {
  24417. offset <<= 8;
  24418. offset += bytes[pos++];
  24419. }
  24420. offsets.push(startPos + offset);
  24421. }
  24422. end = offsets[count];
  24423. }
  24424. for (i = 0, ii = offsets.length - 1; i < ii; ++i) {
  24425. var offsetStart = offsets[i];
  24426. var offsetEnd = offsets[i + 1];
  24427. cffIndex.add(bytes.subarray(offsetStart, offsetEnd));
  24428. }
  24429. return {obj: cffIndex, endPos: end};
  24430. },
  24431. parseNameIndex: function CFFParser_parseNameIndex(index) {
  24432. var names = [];
  24433. for (var i = 0, ii = index.count; i < ii; ++i) {
  24434. var name = index.get(i);
  24435. // OTS doesn't allow names to be over 127 characters.
  24436. var length = Math.min(name.length, 127);
  24437. var data = [];
  24438. // OTS also only permits certain characters in the name.
  24439. for (var j = 0; j < length; ++j) {
  24440. var c = name[j];
  24441. if (j === 0 && c === 0) {
  24442. data[j] = c;
  24443. continue;
  24444. }
  24445. if ((c < 33 || c > 126) || c === 91 /* [ */ || c === 93 /* ] */ ||
  24446. c === 40 /* ( */ || c === 41 /* ) */ || c === 123 /* { */ ||
  24447. c === 125 /* } */ || c === 60 /* < */ || c === 62 /* > */ ||
  24448. c === 47 /* / */ || c === 37 /* % */ || c === 35 /* # */) {
  24449. data[j] = 95;
  24450. continue;
  24451. }
  24452. data[j] = c;
  24453. }
  24454. names.push(bytesToString(data));
  24455. }
  24456. return names;
  24457. },
  24458. parseStringIndex: function CFFParser_parseStringIndex(index) {
  24459. var strings = new CFFStrings();
  24460. for (var i = 0, ii = index.count; i < ii; ++i) {
  24461. var data = index.get(i);
  24462. strings.add(bytesToString(data));
  24463. }
  24464. return strings;
  24465. },
  24466. createDict: function CFFParser_createDict(Type, dict, strings) {
  24467. var cffDict = new Type(strings);
  24468. for (var i = 0, ii = dict.length; i < ii; ++i) {
  24469. var pair = dict[i];
  24470. var key = pair[0];
  24471. var value = pair[1];
  24472. cffDict.setByKey(key, value);
  24473. }
  24474. return cffDict;
  24475. },
  24476. parseCharStrings: function CFFParser_parseCharStrings(charStringOffset) {
  24477. var charStrings = this.parseIndex(charStringOffset).obj;
  24478. var seacs = [];
  24479. var widths = [];
  24480. var count = charStrings.count;
  24481. for (var i = 0; i < count; i++) {
  24482. var charstring = charStrings.get(i);
  24483. var stackSize = 0;
  24484. var stack = [];
  24485. var undefStack = true;
  24486. var hints = 0;
  24487. var valid = true;
  24488. var data = charstring;
  24489. var length = data.length;
  24490. var firstStackClearing = true;
  24491. for (var j = 0; j < length;) {
  24492. var value = data[j++];
  24493. var validationCommand = null;
  24494. if (value === 12) {
  24495. var q = data[j++];
  24496. if (q === 0) {
  24497. // The CFF specification state that the 'dotsection' command
  24498. // (12, 0) is deprecated and treated as a no-op, but all Type2
  24499. // charstrings processors should support them. Unfortunately
  24500. // the font sanitizer don't. As a workaround the sequence (12, 0)
  24501. // is replaced by a useless (0, hmoveto).
  24502. data[j - 2] = 139;
  24503. data[j - 1] = 22;
  24504. stackSize = 0;
  24505. } else {
  24506. validationCommand = CharstringValidationData12[q];
  24507. }
  24508. } else if (value === 28) { // number (16 bit)
  24509. stack[stackSize] = ((data[j] << 24) | (data[j + 1] << 16)) >> 16;
  24510. j += 2;
  24511. stackSize++;
  24512. } else if (value === 14) {
  24513. if (stackSize >= 4) {
  24514. stackSize -= 4;
  24515. if (SEAC_ANALYSIS_ENABLED) {
  24516. seacs[i] = stack.slice(stackSize, stackSize + 4);
  24517. valid = false;
  24518. }
  24519. }
  24520. validationCommand = CharstringValidationData[value];
  24521. } else if (value >= 32 && value <= 246) { // number
  24522. stack[stackSize] = value - 139;
  24523. stackSize++;
  24524. } else if (value >= 247 && value <= 254) { // number (+1 bytes)
  24525. stack[stackSize] = (value < 251 ?
  24526. ((value - 247) << 8) + data[j] + 108 :
  24527. -((value - 251) << 8) - data[j] - 108);
  24528. j++;
  24529. stackSize++;
  24530. } else if (value === 255) { // number (32 bit)
  24531. stack[stackSize] = ((data[j] << 24) | (data[j + 1] << 16) |
  24532. (data[j + 2] << 8) | data[j + 3]) / 65536;
  24533. j += 4;
  24534. stackSize++;
  24535. } else if (value === 19 || value === 20) {
  24536. hints += stackSize >> 1;
  24537. j += (hints + 7) >> 3; // skipping right amount of hints flag data
  24538. stackSize %= 2;
  24539. validationCommand = CharstringValidationData[value];
  24540. } else {
  24541. validationCommand = CharstringValidationData[value];
  24542. }
  24543. if (validationCommand) {
  24544. if (validationCommand.stem) {
  24545. hints += stackSize >> 1;
  24546. }
  24547. if ('min' in validationCommand) {
  24548. if (!undefStack && stackSize < validationCommand.min) {
  24549. warn('Not enough parameters for ' + validationCommand.id +
  24550. '; actual: ' + stackSize +
  24551. ', expected: ' + validationCommand.min);
  24552. valid = false;
  24553. break;
  24554. }
  24555. }
  24556. if (firstStackClearing && validationCommand.stackClearing) {
  24557. firstStackClearing = false;
  24558. // the optional character width can be found before the first
  24559. // stack-clearing command arguments
  24560. stackSize -= validationCommand.min;
  24561. if (stackSize >= 2 && validationCommand.stem) {
  24562. // there are even amount of arguments for stem commands
  24563. stackSize %= 2;
  24564. } else if (stackSize > 1) {
  24565. warn('Found too many parameters for stack-clearing command');
  24566. }
  24567. if (stackSize > 0 && stack[stackSize - 1] >= 0) {
  24568. widths[i] = stack[stackSize - 1];
  24569. }
  24570. }
  24571. if ('stackDelta' in validationCommand) {
  24572. if ('stackFn' in validationCommand) {
  24573. validationCommand.stackFn(stack, stackSize);
  24574. }
  24575. stackSize += validationCommand.stackDelta;
  24576. } else if (validationCommand.stackClearing) {
  24577. stackSize = 0;
  24578. } else if (validationCommand.resetStack) {
  24579. stackSize = 0;
  24580. undefStack = false;
  24581. } else if (validationCommand.undefStack) {
  24582. stackSize = 0;
  24583. undefStack = true;
  24584. firstStackClearing = false;
  24585. }
  24586. }
  24587. }
  24588. if (!valid) {
  24589. // resetting invalid charstring to single 'endchar'
  24590. charStrings.set(i, new Uint8Array([14]));
  24591. }
  24592. }
  24593. return { charStrings: charStrings, seacs: seacs, widths: widths };
  24594. },
  24595. emptyPrivateDictionary:
  24596. function CFFParser_emptyPrivateDictionary(parentDict) {
  24597. var privateDict = this.createDict(CFFPrivateDict, [],
  24598. parentDict.strings);
  24599. parentDict.setByKey(18, [0, 0]);
  24600. parentDict.privateDict = privateDict;
  24601. },
  24602. parsePrivateDict: function CFFParser_parsePrivateDict(parentDict) {
  24603. // no private dict, do nothing
  24604. if (!parentDict.hasName('Private')) {
  24605. this.emptyPrivateDictionary(parentDict);
  24606. return;
  24607. }
  24608. var privateOffset = parentDict.getByName('Private');
  24609. // make sure the params are formatted correctly
  24610. if (!isArray(privateOffset) || privateOffset.length !== 2) {
  24611. parentDict.removeByName('Private');
  24612. return;
  24613. }
  24614. var size = privateOffset[0];
  24615. var offset = privateOffset[1];
  24616. // remove empty dicts or ones that refer to invalid location
  24617. if (size === 0 || offset >= this.bytes.length) {
  24618. this.emptyPrivateDictionary(parentDict);
  24619. return;
  24620. }
  24621. var privateDictEnd = offset + size;
  24622. var dictData = this.bytes.subarray(offset, privateDictEnd);
  24623. var dict = this.parseDict(dictData);
  24624. var privateDict = this.createDict(CFFPrivateDict, dict,
  24625. parentDict.strings);
  24626. parentDict.privateDict = privateDict;
  24627. // Parse the Subrs index also since it's relative to the private dict.
  24628. if (!privateDict.getByName('Subrs')) {
  24629. return;
  24630. }
  24631. var subrsOffset = privateDict.getByName('Subrs');
  24632. var relativeOffset = offset + subrsOffset;
  24633. // Validate the offset.
  24634. if (subrsOffset === 0 || relativeOffset >= this.bytes.length) {
  24635. this.emptyPrivateDictionary(parentDict);
  24636. return;
  24637. }
  24638. var subrsIndex = this.parseIndex(relativeOffset);
  24639. privateDict.subrsIndex = subrsIndex.obj;
  24640. },
  24641. parseCharsets: function CFFParser_parseCharsets(pos, length, strings, cid) {
  24642. if (pos === 0) {
  24643. return new CFFCharset(true, CFFCharsetPredefinedTypes.ISO_ADOBE,
  24644. ISOAdobeCharset);
  24645. } else if (pos === 1) {
  24646. return new CFFCharset(true, CFFCharsetPredefinedTypes.EXPERT,
  24647. ExpertCharset);
  24648. } else if (pos === 2) {
  24649. return new CFFCharset(true, CFFCharsetPredefinedTypes.EXPERT_SUBSET,
  24650. ExpertSubsetCharset);
  24651. }
  24652. var bytes = this.bytes;
  24653. var start = pos;
  24654. var format = bytes[pos++];
  24655. var charset = ['.notdef'];
  24656. var id, count, i;
  24657. // subtract 1 for the .notdef glyph
  24658. length -= 1;
  24659. switch (format) {
  24660. case 0:
  24661. for (i = 0; i < length; i++) {
  24662. id = (bytes[pos++] << 8) | bytes[pos++];
  24663. charset.push(cid ? id : strings.get(id));
  24664. }
  24665. break;
  24666. case 1:
  24667. while (charset.length <= length) {
  24668. id = (bytes[pos++] << 8) | bytes[pos++];
  24669. count = bytes[pos++];
  24670. for (i = 0; i <= count; i++) {
  24671. charset.push(cid ? id++ : strings.get(id++));
  24672. }
  24673. }
  24674. break;
  24675. case 2:
  24676. while (charset.length <= length) {
  24677. id = (bytes[pos++] << 8) | bytes[pos++];
  24678. count = (bytes[pos++] << 8) | bytes[pos++];
  24679. for (i = 0; i <= count; i++) {
  24680. charset.push(cid ? id++ : strings.get(id++));
  24681. }
  24682. }
  24683. break;
  24684. default:
  24685. error('Unknown charset format');
  24686. }
  24687. // Raw won't be needed if we actually compile the charset.
  24688. var end = pos;
  24689. var raw = bytes.subarray(start, end);
  24690. return new CFFCharset(false, format, charset, raw);
  24691. },
  24692. parseEncoding: function CFFParser_parseEncoding(pos,
  24693. properties,
  24694. strings,
  24695. charset) {
  24696. var encoding = {};
  24697. var bytes = this.bytes;
  24698. var predefined = false;
  24699. var hasSupplement = false;
  24700. var format, i, ii;
  24701. var raw = null;
  24702. function readSupplement() {
  24703. var supplementsCount = bytes[pos++];
  24704. for (i = 0; i < supplementsCount; i++) {
  24705. var code = bytes[pos++];
  24706. var sid = (bytes[pos++] << 8) + (bytes[pos++] & 0xff);
  24707. encoding[code] = charset.indexOf(strings.get(sid));
  24708. }
  24709. }
  24710. if (pos === 0 || pos === 1) {
  24711. predefined = true;
  24712. format = pos;
  24713. var baseEncoding = pos ? Encodings.ExpertEncoding :
  24714. Encodings.StandardEncoding;
  24715. for (i = 0, ii = charset.length; i < ii; i++) {
  24716. var index = baseEncoding.indexOf(charset[i]);
  24717. if (index !== -1) {
  24718. encoding[index] = i;
  24719. }
  24720. }
  24721. } else {
  24722. var dataStart = pos;
  24723. format = bytes[pos++];
  24724. switch (format & 0x7f) {
  24725. case 0:
  24726. var glyphsCount = bytes[pos++];
  24727. for (i = 1; i <= glyphsCount; i++) {
  24728. encoding[bytes[pos++]] = i;
  24729. }
  24730. break;
  24731. case 1:
  24732. var rangesCount = bytes[pos++];
  24733. var gid = 1;
  24734. for (i = 0; i < rangesCount; i++) {
  24735. var start = bytes[pos++];
  24736. var left = bytes[pos++];
  24737. for (var j = start; j <= start + left; j++) {
  24738. encoding[j] = gid++;
  24739. }
  24740. }
  24741. break;
  24742. default:
  24743. error('Unknow encoding format: ' + format + ' in CFF');
  24744. break;
  24745. }
  24746. var dataEnd = pos;
  24747. if (format & 0x80) {
  24748. // The font sanitizer does not support CFF encoding with a
  24749. // supplement, since the encoding is not really used to map
  24750. // between gid to glyph, let's overwrite what is declared in
  24751. // the top dictionary to let the sanitizer think the font use
  24752. // StandardEncoding, that's a lie but that's ok.
  24753. bytes[dataStart] &= 0x7f;
  24754. readSupplement();
  24755. hasSupplement = true;
  24756. }
  24757. raw = bytes.subarray(dataStart, dataEnd);
  24758. }
  24759. format = format & 0x7f;
  24760. return new CFFEncoding(predefined, format, encoding, raw);
  24761. },
  24762. parseFDSelect: function CFFParser_parseFDSelect(pos, length) {
  24763. var start = pos;
  24764. var bytes = this.bytes;
  24765. var format = bytes[pos++];
  24766. var fdSelect = [];
  24767. var i;
  24768. switch (format) {
  24769. case 0:
  24770. for (i = 0; i < length; ++i) {
  24771. var id = bytes[pos++];
  24772. fdSelect.push(id);
  24773. }
  24774. break;
  24775. case 3:
  24776. var rangesCount = (bytes[pos++] << 8) | bytes[pos++];
  24777. for (i = 0; i < rangesCount; ++i) {
  24778. var first = (bytes[pos++] << 8) | bytes[pos++];
  24779. var fdIndex = bytes[pos++];
  24780. var next = (bytes[pos] << 8) | bytes[pos + 1];
  24781. for (var j = first; j < next; ++j) {
  24782. fdSelect.push(fdIndex);
  24783. }
  24784. }
  24785. // Advance past the sentinel(next).
  24786. pos += 2;
  24787. break;
  24788. default:
  24789. error('Unknown fdselect format ' + format);
  24790. break;
  24791. }
  24792. var end = pos;
  24793. return new CFFFDSelect(fdSelect, bytes.subarray(start, end));
  24794. }
  24795. };
  24796. return CFFParser;
  24797. })();
  24798. // Compact Font Format
  24799. var CFF = (function CFFClosure() {
  24800. function CFF() {
  24801. this.header = null;
  24802. this.names = [];
  24803. this.topDict = null;
  24804. this.strings = new CFFStrings();
  24805. this.globalSubrIndex = null;
  24806. // The following could really be per font, but since we only have one font
  24807. // store them here.
  24808. this.encoding = null;
  24809. this.charset = null;
  24810. this.charStrings = null;
  24811. this.fdArray = [];
  24812. this.fdSelect = null;
  24813. this.isCIDFont = false;
  24814. }
  24815. return CFF;
  24816. })();
  24817. var CFFHeader = (function CFFHeaderClosure() {
  24818. function CFFHeader(major, minor, hdrSize, offSize) {
  24819. this.major = major;
  24820. this.minor = minor;
  24821. this.hdrSize = hdrSize;
  24822. this.offSize = offSize;
  24823. }
  24824. return CFFHeader;
  24825. })();
  24826. var CFFStrings = (function CFFStringsClosure() {
  24827. function CFFStrings() {
  24828. this.strings = [];
  24829. }
  24830. CFFStrings.prototype = {
  24831. get: function CFFStrings_get(index) {
  24832. if (index >= 0 && index <= 390) {
  24833. return CFFStandardStrings[index];
  24834. }
  24835. if (index - 391 <= this.strings.length) {
  24836. return this.strings[index - 391];
  24837. }
  24838. return CFFStandardStrings[0];
  24839. },
  24840. add: function CFFStrings_add(value) {
  24841. this.strings.push(value);
  24842. },
  24843. get count() {
  24844. return this.strings.length;
  24845. }
  24846. };
  24847. return CFFStrings;
  24848. })();
  24849. var CFFIndex = (function CFFIndexClosure() {
  24850. function CFFIndex() {
  24851. this.objects = [];
  24852. this.length = 0;
  24853. }
  24854. CFFIndex.prototype = {
  24855. add: function CFFIndex_add(data) {
  24856. this.length += data.length;
  24857. this.objects.push(data);
  24858. },
  24859. set: function CFFIndex_set(index, data) {
  24860. this.length += data.length - this.objects[index].length;
  24861. this.objects[index] = data;
  24862. },
  24863. get: function CFFIndex_get(index) {
  24864. return this.objects[index];
  24865. },
  24866. get count() {
  24867. return this.objects.length;
  24868. }
  24869. };
  24870. return CFFIndex;
  24871. })();
  24872. var CFFDict = (function CFFDictClosure() {
  24873. function CFFDict(tables, strings) {
  24874. this.keyToNameMap = tables.keyToNameMap;
  24875. this.nameToKeyMap = tables.nameToKeyMap;
  24876. this.defaults = tables.defaults;
  24877. this.types = tables.types;
  24878. this.opcodes = tables.opcodes;
  24879. this.order = tables.order;
  24880. this.strings = strings;
  24881. this.values = {};
  24882. }
  24883. CFFDict.prototype = {
  24884. // value should always be an array
  24885. setByKey: function CFFDict_setByKey(key, value) {
  24886. if (!(key in this.keyToNameMap)) {
  24887. return false;
  24888. }
  24889. // ignore empty values
  24890. if (value.length === 0) {
  24891. return true;
  24892. }
  24893. var type = this.types[key];
  24894. // remove the array wrapping these types of values
  24895. if (type === 'num' || type === 'sid' || type === 'offset') {
  24896. value = value[0];
  24897. }
  24898. this.values[key] = value;
  24899. return true;
  24900. },
  24901. setByName: function CFFDict_setByName(name, value) {
  24902. if (!(name in this.nameToKeyMap)) {
  24903. error('Invalid dictionary name "' + name + '"');
  24904. }
  24905. this.values[this.nameToKeyMap[name]] = value;
  24906. },
  24907. hasName: function CFFDict_hasName(name) {
  24908. return this.nameToKeyMap[name] in this.values;
  24909. },
  24910. getByName: function CFFDict_getByName(name) {
  24911. if (!(name in this.nameToKeyMap)) {
  24912. error('Invalid dictionary name "' + name + '"');
  24913. }
  24914. var key = this.nameToKeyMap[name];
  24915. if (!(key in this.values)) {
  24916. return this.defaults[key];
  24917. }
  24918. return this.values[key];
  24919. },
  24920. removeByName: function CFFDict_removeByName(name) {
  24921. delete this.values[this.nameToKeyMap[name]];
  24922. }
  24923. };
  24924. CFFDict.createTables = function CFFDict_createTables(layout) {
  24925. var tables = {
  24926. keyToNameMap: {},
  24927. nameToKeyMap: {},
  24928. defaults: {},
  24929. types: {},
  24930. opcodes: {},
  24931. order: []
  24932. };
  24933. for (var i = 0, ii = layout.length; i < ii; ++i) {
  24934. var entry = layout[i];
  24935. var key = isArray(entry[0]) ? (entry[0][0] << 8) + entry[0][1] : entry[0];
  24936. tables.keyToNameMap[key] = entry[1];
  24937. tables.nameToKeyMap[entry[1]] = key;
  24938. tables.types[key] = entry[2];
  24939. tables.defaults[key] = entry[3];
  24940. tables.opcodes[key] = isArray(entry[0]) ? entry[0] : [entry[0]];
  24941. tables.order.push(key);
  24942. }
  24943. return tables;
  24944. };
  24945. return CFFDict;
  24946. })();
  24947. var CFFTopDict = (function CFFTopDictClosure() {
  24948. var layout = [
  24949. [[12, 30], 'ROS', ['sid', 'sid', 'num'], null],
  24950. [[12, 20], 'SyntheticBase', 'num', null],
  24951. [0, 'version', 'sid', null],
  24952. [1, 'Notice', 'sid', null],
  24953. [[12, 0], 'Copyright', 'sid', null],
  24954. [2, 'FullName', 'sid', null],
  24955. [3, 'FamilyName', 'sid', null],
  24956. [4, 'Weight', 'sid', null],
  24957. [[12, 1], 'isFixedPitch', 'num', 0],
  24958. [[12, 2], 'ItalicAngle', 'num', 0],
  24959. [[12, 3], 'UnderlinePosition', 'num', -100],
  24960. [[12, 4], 'UnderlineThickness', 'num', 50],
  24961. [[12, 5], 'PaintType', 'num', 0],
  24962. [[12, 6], 'CharstringType', 'num', 2],
  24963. [[12, 7], 'FontMatrix', ['num', 'num', 'num', 'num', 'num', 'num'],
  24964. [0.001, 0, 0, 0.001, 0, 0]],
  24965. [13, 'UniqueID', 'num', null],
  24966. [5, 'FontBBox', ['num', 'num', 'num', 'num'], [0, 0, 0, 0]],
  24967. [[12, 8], 'StrokeWidth', 'num', 0],
  24968. [14, 'XUID', 'array', null],
  24969. [15, 'charset', 'offset', 0],
  24970. [16, 'Encoding', 'offset', 0],
  24971. [17, 'CharStrings', 'offset', 0],
  24972. [18, 'Private', ['offset', 'offset'], null],
  24973. [[12, 21], 'PostScript', 'sid', null],
  24974. [[12, 22], 'BaseFontName', 'sid', null],
  24975. [[12, 23], 'BaseFontBlend', 'delta', null],
  24976. [[12, 31], 'CIDFontVersion', 'num', 0],
  24977. [[12, 32], 'CIDFontRevision', 'num', 0],
  24978. [[12, 33], 'CIDFontType', 'num', 0],
  24979. [[12, 34], 'CIDCount', 'num', 8720],
  24980. [[12, 35], 'UIDBase', 'num', null],
  24981. // XXX: CID Fonts on DirectWrite 6.1 only seem to work if FDSelect comes
  24982. // before FDArray.
  24983. [[12, 37], 'FDSelect', 'offset', null],
  24984. [[12, 36], 'FDArray', 'offset', null],
  24985. [[12, 38], 'FontName', 'sid', null]
  24986. ];
  24987. var tables = null;
  24988. function CFFTopDict(strings) {
  24989. if (tables === null) {
  24990. tables = CFFDict.createTables(layout);
  24991. }
  24992. CFFDict.call(this, tables, strings);
  24993. this.privateDict = null;
  24994. }
  24995. CFFTopDict.prototype = Object.create(CFFDict.prototype);
  24996. return CFFTopDict;
  24997. })();
  24998. var CFFPrivateDict = (function CFFPrivateDictClosure() {
  24999. var layout = [
  25000. [6, 'BlueValues', 'delta', null],
  25001. [7, 'OtherBlues', 'delta', null],
  25002. [8, 'FamilyBlues', 'delta', null],
  25003. [9, 'FamilyOtherBlues', 'delta', null],
  25004. [[12, 9], 'BlueScale', 'num', 0.039625],
  25005. [[12, 10], 'BlueShift', 'num', 7],
  25006. [[12, 11], 'BlueFuzz', 'num', 1],
  25007. [10, 'StdHW', 'num', null],
  25008. [11, 'StdVW', 'num', null],
  25009. [[12, 12], 'StemSnapH', 'delta', null],
  25010. [[12, 13], 'StemSnapV', 'delta', null],
  25011. [[12, 14], 'ForceBold', 'num', 0],
  25012. [[12, 17], 'LanguageGroup', 'num', 0],
  25013. [[12, 18], 'ExpansionFactor', 'num', 0.06],
  25014. [[12, 19], 'initialRandomSeed', 'num', 0],
  25015. [20, 'defaultWidthX', 'num', 0],
  25016. [21, 'nominalWidthX', 'num', 0],
  25017. [19, 'Subrs', 'offset', null]
  25018. ];
  25019. var tables = null;
  25020. function CFFPrivateDict(strings) {
  25021. if (tables === null) {
  25022. tables = CFFDict.createTables(layout);
  25023. }
  25024. CFFDict.call(this, tables, strings);
  25025. this.subrsIndex = null;
  25026. }
  25027. CFFPrivateDict.prototype = Object.create(CFFDict.prototype);
  25028. return CFFPrivateDict;
  25029. })();
  25030. var CFFCharsetPredefinedTypes = {
  25031. ISO_ADOBE: 0,
  25032. EXPERT: 1,
  25033. EXPERT_SUBSET: 2
  25034. };
  25035. var CFFCharset = (function CFFCharsetClosure() {
  25036. function CFFCharset(predefined, format, charset, raw) {
  25037. this.predefined = predefined;
  25038. this.format = format;
  25039. this.charset = charset;
  25040. this.raw = raw;
  25041. }
  25042. return CFFCharset;
  25043. })();
  25044. var CFFEncoding = (function CFFEncodingClosure() {
  25045. function CFFEncoding(predefined, format, encoding, raw) {
  25046. this.predefined = predefined;
  25047. this.format = format;
  25048. this.encoding = encoding;
  25049. this.raw = raw;
  25050. }
  25051. return CFFEncoding;
  25052. })();
  25053. var CFFFDSelect = (function CFFFDSelectClosure() {
  25054. function CFFFDSelect(fdSelect, raw) {
  25055. this.fdSelect = fdSelect;
  25056. this.raw = raw;
  25057. }
  25058. return CFFFDSelect;
  25059. })();
  25060. // Helper class to keep track of where an offset is within the data and helps
  25061. // filling in that offset once it's known.
  25062. var CFFOffsetTracker = (function CFFOffsetTrackerClosure() {
  25063. function CFFOffsetTracker() {
  25064. this.offsets = {};
  25065. }
  25066. CFFOffsetTracker.prototype = {
  25067. isTracking: function CFFOffsetTracker_isTracking(key) {
  25068. return key in this.offsets;
  25069. },
  25070. track: function CFFOffsetTracker_track(key, location) {
  25071. if (key in this.offsets) {
  25072. error('Already tracking location of ' + key);
  25073. }
  25074. this.offsets[key] = location;
  25075. },
  25076. offset: function CFFOffsetTracker_offset(value) {
  25077. for (var key in this.offsets) {
  25078. this.offsets[key] += value;
  25079. }
  25080. },
  25081. setEntryLocation: function CFFOffsetTracker_setEntryLocation(key,
  25082. values,
  25083. output) {
  25084. if (!(key in this.offsets)) {
  25085. error('Not tracking location of ' + key);
  25086. }
  25087. var data = output.data;
  25088. var dataOffset = this.offsets[key];
  25089. var size = 5;
  25090. for (var i = 0, ii = values.length; i < ii; ++i) {
  25091. var offset0 = i * size + dataOffset;
  25092. var offset1 = offset0 + 1;
  25093. var offset2 = offset0 + 2;
  25094. var offset3 = offset0 + 3;
  25095. var offset4 = offset0 + 4;
  25096. // It's easy to screw up offsets so perform this sanity check.
  25097. if (data[offset0] !== 0x1d || data[offset1] !== 0 ||
  25098. data[offset2] !== 0 || data[offset3] !== 0 || data[offset4] !== 0) {
  25099. error('writing to an offset that is not empty');
  25100. }
  25101. var value = values[i];
  25102. data[offset0] = 0x1d;
  25103. data[offset1] = (value >> 24) & 0xFF;
  25104. data[offset2] = (value >> 16) & 0xFF;
  25105. data[offset3] = (value >> 8) & 0xFF;
  25106. data[offset4] = value & 0xFF;
  25107. }
  25108. }
  25109. };
  25110. return CFFOffsetTracker;
  25111. })();
  25112. // Takes a CFF and converts it to the binary representation.
  25113. var CFFCompiler = (function CFFCompilerClosure() {
  25114. function CFFCompiler(cff) {
  25115. this.cff = cff;
  25116. }
  25117. CFFCompiler.prototype = {
  25118. compile: function CFFCompiler_compile() {
  25119. var cff = this.cff;
  25120. var output = {
  25121. data: [],
  25122. length: 0,
  25123. add: function CFFCompiler_add(data) {
  25124. this.data = this.data.concat(data);
  25125. this.length = this.data.length;
  25126. }
  25127. };
  25128. // Compile the five entries that must be in order.
  25129. var header = this.compileHeader(cff.header);
  25130. output.add(header);
  25131. var nameIndex = this.compileNameIndex(cff.names);
  25132. output.add(nameIndex);
  25133. if (cff.isCIDFont) {
  25134. // The spec is unclear on how font matrices should relate to each other
  25135. // when there is one in the main top dict and the sub top dicts.
  25136. // Windows handles this differently than linux and osx so we have to
  25137. // normalize to work on all.
  25138. // Rules based off of some mailing list discussions:
  25139. // - If main font has a matrix and subfont doesn't, use the main matrix.
  25140. // - If no main font matrix and there is a subfont matrix, use the
  25141. // subfont matrix.
  25142. // - If both have matrices, concat together.
  25143. // - If neither have matrices, use default.
  25144. // To make this work on all platforms we move the top matrix into each
  25145. // sub top dict and concat if necessary.
  25146. if (cff.topDict.hasName('FontMatrix')) {
  25147. var base = cff.topDict.getByName('FontMatrix');
  25148. cff.topDict.removeByName('FontMatrix');
  25149. for (var i = 0, ii = cff.fdArray.length; i < ii; i++) {
  25150. var subDict = cff.fdArray[i];
  25151. var matrix = base.slice(0);
  25152. if (subDict.hasName('FontMatrix')) {
  25153. matrix = Util.transform(matrix, subDict.getByName('FontMatrix'));
  25154. }
  25155. subDict.setByName('FontMatrix', matrix);
  25156. }
  25157. }
  25158. }
  25159. var compiled = this.compileTopDicts([cff.topDict],
  25160. output.length,
  25161. cff.isCIDFont);
  25162. output.add(compiled.output);
  25163. var topDictTracker = compiled.trackers[0];
  25164. var stringIndex = this.compileStringIndex(cff.strings.strings);
  25165. output.add(stringIndex);
  25166. var globalSubrIndex = this.compileIndex(cff.globalSubrIndex);
  25167. output.add(globalSubrIndex);
  25168. // Now start on the other entries that have no specfic order.
  25169. if (cff.encoding && cff.topDict.hasName('Encoding')) {
  25170. if (cff.encoding.predefined) {
  25171. topDictTracker.setEntryLocation('Encoding', [cff.encoding.format],
  25172. output);
  25173. } else {
  25174. var encoding = this.compileEncoding(cff.encoding);
  25175. topDictTracker.setEntryLocation('Encoding', [output.length], output);
  25176. output.add(encoding);
  25177. }
  25178. }
  25179. if (cff.charset && cff.topDict.hasName('charset')) {
  25180. if (cff.charset.predefined) {
  25181. topDictTracker.setEntryLocation('charset', [cff.charset.format],
  25182. output);
  25183. } else {
  25184. var charset = this.compileCharset(cff.charset);
  25185. topDictTracker.setEntryLocation('charset', [output.length], output);
  25186. output.add(charset);
  25187. }
  25188. }
  25189. var charStrings = this.compileCharStrings(cff.charStrings);
  25190. topDictTracker.setEntryLocation('CharStrings', [output.length], output);
  25191. output.add(charStrings);
  25192. if (cff.isCIDFont) {
  25193. // For some reason FDSelect must be in front of FDArray on windows. OSX
  25194. // and linux don't seem to care.
  25195. topDictTracker.setEntryLocation('FDSelect', [output.length], output);
  25196. var fdSelect = this.compileFDSelect(cff.fdSelect.raw);
  25197. output.add(fdSelect);
  25198. // It is unclear if the sub font dictionary can have CID related
  25199. // dictionary keys, but the sanitizer doesn't like them so remove them.
  25200. compiled = this.compileTopDicts(cff.fdArray, output.length, true);
  25201. topDictTracker.setEntryLocation('FDArray', [output.length], output);
  25202. output.add(compiled.output);
  25203. var fontDictTrackers = compiled.trackers;
  25204. this.compilePrivateDicts(cff.fdArray, fontDictTrackers, output);
  25205. }
  25206. this.compilePrivateDicts([cff.topDict], [topDictTracker], output);
  25207. // If the font data ends with INDEX whose object data is zero-length,
  25208. // the sanitizer will bail out. Add a dummy byte to avoid that.
  25209. output.add([0]);
  25210. return output.data;
  25211. },
  25212. encodeNumber: function CFFCompiler_encodeNumber(value) {
  25213. if (parseFloat(value) === parseInt(value, 10) && !isNaN(value)) { // isInt
  25214. return this.encodeInteger(value);
  25215. } else {
  25216. return this.encodeFloat(value);
  25217. }
  25218. },
  25219. encodeFloat: function CFFCompiler_encodeFloat(num) {
  25220. var value = num.toString();
  25221. // rounding inaccurate doubles
  25222. var m = /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(value);
  25223. if (m) {
  25224. var epsilon = parseFloat('1e' + ((m[2] ? +m[2] : 0) + m[1].length));
  25225. value = (Math.round(num * epsilon) / epsilon).toString();
  25226. }
  25227. var nibbles = '';
  25228. var i, ii;
  25229. for (i = 0, ii = value.length; i < ii; ++i) {
  25230. var a = value[i];
  25231. if (a === 'e') {
  25232. nibbles += value[++i] === '-' ? 'c' : 'b';
  25233. } else if (a === '.') {
  25234. nibbles += 'a';
  25235. } else if (a === '-') {
  25236. nibbles += 'e';
  25237. } else {
  25238. nibbles += a;
  25239. }
  25240. }
  25241. nibbles += (nibbles.length & 1) ? 'f' : 'ff';
  25242. var out = [30];
  25243. for (i = 0, ii = nibbles.length; i < ii; i += 2) {
  25244. out.push(parseInt(nibbles.substr(i, 2), 16));
  25245. }
  25246. return out;
  25247. },
  25248. encodeInteger: function CFFCompiler_encodeInteger(value) {
  25249. var code;
  25250. if (value >= -107 && value <= 107) {
  25251. code = [value + 139];
  25252. } else if (value >= 108 && value <= 1131) {
  25253. value = [value - 108];
  25254. code = [(value >> 8) + 247, value & 0xFF];
  25255. } else if (value >= -1131 && value <= -108) {
  25256. value = -value - 108;
  25257. code = [(value >> 8) + 251, value & 0xFF];
  25258. } else if (value >= -32768 && value <= 32767) {
  25259. code = [0x1c, (value >> 8) & 0xFF, value & 0xFF];
  25260. } else {
  25261. code = [0x1d,
  25262. (value >> 24) & 0xFF,
  25263. (value >> 16) & 0xFF,
  25264. (value >> 8) & 0xFF,
  25265. value & 0xFF];
  25266. }
  25267. return code;
  25268. },
  25269. compileHeader: function CFFCompiler_compileHeader(header) {
  25270. return [
  25271. header.major,
  25272. header.minor,
  25273. header.hdrSize,
  25274. header.offSize
  25275. ];
  25276. },
  25277. compileNameIndex: function CFFCompiler_compileNameIndex(names) {
  25278. var nameIndex = new CFFIndex();
  25279. for (var i = 0, ii = names.length; i < ii; ++i) {
  25280. nameIndex.add(stringToBytes(names[i]));
  25281. }
  25282. return this.compileIndex(nameIndex);
  25283. },
  25284. compileTopDicts: function CFFCompiler_compileTopDicts(dicts,
  25285. length,
  25286. removeCidKeys) {
  25287. var fontDictTrackers = [];
  25288. var fdArrayIndex = new CFFIndex();
  25289. for (var i = 0, ii = dicts.length; i < ii; ++i) {
  25290. var fontDict = dicts[i];
  25291. if (removeCidKeys) {
  25292. fontDict.removeByName('CIDFontVersion');
  25293. fontDict.removeByName('CIDFontRevision');
  25294. fontDict.removeByName('CIDFontType');
  25295. fontDict.removeByName('CIDCount');
  25296. fontDict.removeByName('UIDBase');
  25297. }
  25298. var fontDictTracker = new CFFOffsetTracker();
  25299. var fontDictData = this.compileDict(fontDict, fontDictTracker);
  25300. fontDictTrackers.push(fontDictTracker);
  25301. fdArrayIndex.add(fontDictData);
  25302. fontDictTracker.offset(length);
  25303. }
  25304. fdArrayIndex = this.compileIndex(fdArrayIndex, fontDictTrackers);
  25305. return {
  25306. trackers: fontDictTrackers,
  25307. output: fdArrayIndex
  25308. };
  25309. },
  25310. compilePrivateDicts: function CFFCompiler_compilePrivateDicts(dicts,
  25311. trackers,
  25312. output) {
  25313. for (var i = 0, ii = dicts.length; i < ii; ++i) {
  25314. var fontDict = dicts[i];
  25315. assert(fontDict.privateDict && fontDict.hasName('Private'),
  25316. 'There must be an private dictionary.');
  25317. var privateDict = fontDict.privateDict;
  25318. var privateDictTracker = new CFFOffsetTracker();
  25319. var privateDictData = this.compileDict(privateDict, privateDictTracker);
  25320. var outputLength = output.length;
  25321. privateDictTracker.offset(outputLength);
  25322. if (!privateDictData.length) {
  25323. // The private dictionary was empty, set the output length to zero to
  25324. // ensure the offset length isn't out of bounds in the eyes of the
  25325. // sanitizer.
  25326. outputLength = 0;
  25327. }
  25328. trackers[i].setEntryLocation('Private',
  25329. [privateDictData.length, outputLength],
  25330. output);
  25331. output.add(privateDictData);
  25332. if (privateDict.subrsIndex && privateDict.hasName('Subrs')) {
  25333. var subrs = this.compileIndex(privateDict.subrsIndex);
  25334. privateDictTracker.setEntryLocation('Subrs', [privateDictData.length],
  25335. output);
  25336. output.add(subrs);
  25337. }
  25338. }
  25339. },
  25340. compileDict: function CFFCompiler_compileDict(dict, offsetTracker) {
  25341. var out = [];
  25342. // The dictionary keys must be in a certain order.
  25343. var order = dict.order;
  25344. for (var i = 0; i < order.length; ++i) {
  25345. var key = order[i];
  25346. if (!(key in dict.values)) {
  25347. continue;
  25348. }
  25349. var values = dict.values[key];
  25350. var types = dict.types[key];
  25351. if (!isArray(types)) {
  25352. types = [types];
  25353. }
  25354. if (!isArray(values)) {
  25355. values = [values];
  25356. }
  25357. // Remove any empty dict values.
  25358. if (values.length === 0) {
  25359. continue;
  25360. }
  25361. for (var j = 0, jj = types.length; j < jj; ++j) {
  25362. var type = types[j];
  25363. var value = values[j];
  25364. switch (type) {
  25365. case 'num':
  25366. case 'sid':
  25367. out = out.concat(this.encodeNumber(value));
  25368. break;
  25369. case 'offset':
  25370. // For offsets we just insert a 32bit integer so we don't have to
  25371. // deal with figuring out the length of the offset when it gets
  25372. // replaced later on by the compiler.
  25373. var name = dict.keyToNameMap[key];
  25374. // Some offsets have the offset and the length, so just record the
  25375. // position of the first one.
  25376. if (!offsetTracker.isTracking(name)) {
  25377. offsetTracker.track(name, out.length);
  25378. }
  25379. out = out.concat([0x1d, 0, 0, 0, 0]);
  25380. break;
  25381. case 'array':
  25382. case 'delta':
  25383. out = out.concat(this.encodeNumber(value));
  25384. for (var k = 1, kk = values.length; k < kk; ++k) {
  25385. out = out.concat(this.encodeNumber(values[k]));
  25386. }
  25387. break;
  25388. default:
  25389. error('Unknown data type of ' + type);
  25390. break;
  25391. }
  25392. }
  25393. out = out.concat(dict.opcodes[key]);
  25394. }
  25395. return out;
  25396. },
  25397. compileStringIndex: function CFFCompiler_compileStringIndex(strings) {
  25398. var stringIndex = new CFFIndex();
  25399. for (var i = 0, ii = strings.length; i < ii; ++i) {
  25400. stringIndex.add(stringToBytes(strings[i]));
  25401. }
  25402. return this.compileIndex(stringIndex);
  25403. },
  25404. compileGlobalSubrIndex: function CFFCompiler_compileGlobalSubrIndex() {
  25405. var globalSubrIndex = this.cff.globalSubrIndex;
  25406. this.out.writeByteArray(this.compileIndex(globalSubrIndex));
  25407. },
  25408. compileCharStrings: function CFFCompiler_compileCharStrings(charStrings) {
  25409. return this.compileIndex(charStrings);
  25410. },
  25411. compileCharset: function CFFCompiler_compileCharset(charset) {
  25412. return this.compileTypedArray(charset.raw);
  25413. },
  25414. compileEncoding: function CFFCompiler_compileEncoding(encoding) {
  25415. return this.compileTypedArray(encoding.raw);
  25416. },
  25417. compileFDSelect: function CFFCompiler_compileFDSelect(fdSelect) {
  25418. return this.compileTypedArray(fdSelect);
  25419. },
  25420. compileTypedArray: function CFFCompiler_compileTypedArray(data) {
  25421. var out = [];
  25422. for (var i = 0, ii = data.length; i < ii; ++i) {
  25423. out[i] = data[i];
  25424. }
  25425. return out;
  25426. },
  25427. compileIndex: function CFFCompiler_compileIndex(index, trackers) {
  25428. trackers = trackers || [];
  25429. var objects = index.objects;
  25430. // First 2 bytes contains the number of objects contained into this index
  25431. var count = objects.length;
  25432. // If there is no object, just create an index. This technically
  25433. // should just be [0, 0] but OTS has an issue with that.
  25434. if (count === 0) {
  25435. return [0, 0, 0];
  25436. }
  25437. var data = [(count >> 8) & 0xFF, count & 0xff];
  25438. var lastOffset = 1, i;
  25439. for (i = 0; i < count; ++i) {
  25440. lastOffset += objects[i].length;
  25441. }
  25442. var offsetSize;
  25443. if (lastOffset < 0x100) {
  25444. offsetSize = 1;
  25445. } else if (lastOffset < 0x10000) {
  25446. offsetSize = 2;
  25447. } else if (lastOffset < 0x1000000) {
  25448. offsetSize = 3;
  25449. } else {
  25450. offsetSize = 4;
  25451. }
  25452. // Next byte contains the offset size use to reference object in the file
  25453. data.push(offsetSize);
  25454. // Add another offset after this one because we need a new offset
  25455. var relativeOffset = 1;
  25456. for (i = 0; i < count + 1; i++) {
  25457. if (offsetSize === 1) {
  25458. data.push(relativeOffset & 0xFF);
  25459. } else if (offsetSize === 2) {
  25460. data.push((relativeOffset >> 8) & 0xFF,
  25461. relativeOffset & 0xFF);
  25462. } else if (offsetSize === 3) {
  25463. data.push((relativeOffset >> 16) & 0xFF,
  25464. (relativeOffset >> 8) & 0xFF,
  25465. relativeOffset & 0xFF);
  25466. } else {
  25467. data.push((relativeOffset >>> 24) & 0xFF,
  25468. (relativeOffset >> 16) & 0xFF,
  25469. (relativeOffset >> 8) & 0xFF,
  25470. relativeOffset & 0xFF);
  25471. }
  25472. if (objects[i]) {
  25473. relativeOffset += objects[i].length;
  25474. }
  25475. }
  25476. for (i = 0; i < count; i++) {
  25477. // Notify the tracker where the object will be offset in the data.
  25478. if (trackers[i]) {
  25479. trackers[i].offset(data.length);
  25480. }
  25481. for (var j = 0, jj = objects[i].length; j < jj; j++) {
  25482. data.push(objects[i][j]);
  25483. }
  25484. }
  25485. return data;
  25486. }
  25487. };
  25488. return CFFCompiler;
  25489. })();
  25490. // Workaround for seac on Windows.
  25491. (function checkSeacSupport() {
  25492. if (/Windows/.test(navigator.userAgent)) {
  25493. SEAC_ANALYSIS_ENABLED = true;
  25494. }
  25495. })();
  25496. // Workaround for Private Use Area characters in Chrome on Windows
  25497. // http://code.google.com/p/chromium/issues/detail?id=122465
  25498. // https://github.com/mozilla/pdf.js/issues/1689
  25499. (function checkChromeWindows() {
  25500. if (/Windows.*Chrome/.test(navigator.userAgent)) {
  25501. SKIP_PRIVATE_USE_RANGE_F000_TO_F01F = true;
  25502. }
  25503. })();
  25504. var FontRendererFactory = (function FontRendererFactoryClosure() {
  25505. function getLong(data, offset) {
  25506. return (data[offset] << 24) | (data[offset + 1] << 16) |
  25507. (data[offset + 2] << 8) | data[offset + 3];
  25508. }
  25509. function getUshort(data, offset) {
  25510. return (data[offset] << 8) | data[offset + 1];
  25511. }
  25512. function parseCmap(data, start, end) {
  25513. var offset = (getUshort(data, start + 2) === 1 ?
  25514. getLong(data, start + 8) : getLong(data, start + 16));
  25515. var format = getUshort(data, start + offset);
  25516. var length, ranges, p, i;
  25517. if (format === 4) {
  25518. length = getUshort(data, start + offset + 2);
  25519. var segCount = getUshort(data, start + offset + 6) >> 1;
  25520. p = start + offset + 14;
  25521. ranges = [];
  25522. for (i = 0; i < segCount; i++, p += 2) {
  25523. ranges[i] = {end: getUshort(data, p)};
  25524. }
  25525. p += 2;
  25526. for (i = 0; i < segCount; i++, p += 2) {
  25527. ranges[i].start = getUshort(data, p);
  25528. }
  25529. for (i = 0; i < segCount; i++, p += 2) {
  25530. ranges[i].idDelta = getUshort(data, p);
  25531. }
  25532. for (i = 0; i < segCount; i++, p += 2) {
  25533. var idOffset = getUshort(data, p);
  25534. if (idOffset === 0) {
  25535. continue;
  25536. }
  25537. ranges[i].ids = [];
  25538. for (var j = 0, jj = ranges[i].end - ranges[i].start + 1; j < jj; j++) {
  25539. ranges[i].ids[j] = getUshort(data, p + idOffset);
  25540. idOffset += 2;
  25541. }
  25542. }
  25543. return ranges;
  25544. } else if (format === 12) {
  25545. length = getLong(data, start + offset + 4);
  25546. var groups = getLong(data, start + offset + 12);
  25547. p = start + offset + 16;
  25548. ranges = [];
  25549. for (i = 0; i < groups; i++) {
  25550. ranges.push({
  25551. start: getLong(data, p),
  25552. end: getLong(data, p + 4),
  25553. idDelta: getLong(data, p + 8) - getLong(data, p)
  25554. });
  25555. p += 12;
  25556. }
  25557. return ranges;
  25558. }
  25559. error('not supported cmap: ' + format);
  25560. }
  25561. function parseCff(data, start, end) {
  25562. var properties = {};
  25563. var parser = new CFFParser(new Stream(data, start, end - start),
  25564. properties);
  25565. var cff = parser.parse();
  25566. return {
  25567. glyphs: cff.charStrings.objects,
  25568. subrs: (cff.topDict.privateDict && cff.topDict.privateDict.subrsIndex &&
  25569. cff.topDict.privateDict.subrsIndex.objects),
  25570. gsubrs: cff.globalSubrIndex && cff.globalSubrIndex.objects
  25571. };
  25572. }
  25573. function parseGlyfTable(glyf, loca, isGlyphLocationsLong) {
  25574. var itemSize, itemDecode;
  25575. if (isGlyphLocationsLong) {
  25576. itemSize = 4;
  25577. itemDecode = function fontItemDecodeLong(data, offset) {
  25578. return (data[offset] << 24) | (data[offset + 1] << 16) |
  25579. (data[offset + 2] << 8) | data[offset + 3];
  25580. };
  25581. } else {
  25582. itemSize = 2;
  25583. itemDecode = function fontItemDecode(data, offset) {
  25584. return (data[offset] << 9) | (data[offset + 1] << 1);
  25585. };
  25586. }
  25587. var glyphs = [];
  25588. var startOffset = itemDecode(loca, 0);
  25589. for (var j = itemSize; j < loca.length; j += itemSize) {
  25590. var endOffset = itemDecode(loca, j);
  25591. glyphs.push(glyf.subarray(startOffset, endOffset));
  25592. startOffset = endOffset;
  25593. }
  25594. return glyphs;
  25595. }
  25596. function lookupCmap(ranges, unicode) {
  25597. var code = unicode.charCodeAt(0);
  25598. var l = 0, r = ranges.length - 1;
  25599. while (l < r) {
  25600. var c = (l + r + 1) >> 1;
  25601. if (code < ranges[c].start) {
  25602. r = c - 1;
  25603. } else {
  25604. l = c;
  25605. }
  25606. }
  25607. if (ranges[l].start <= code && code <= ranges[l].end) {
  25608. return (ranges[l].idDelta + (ranges[l].ids ?
  25609. ranges[l].ids[code - ranges[l].start] : code)) & 0xFFFF;
  25610. }
  25611. return 0;
  25612. }
  25613. function compileGlyf(code, js, font) {
  25614. function moveTo(x, y) {
  25615. js.push('c.moveTo(' + x + ',' + y + ');');
  25616. }
  25617. function lineTo(x, y) {
  25618. js.push('c.lineTo(' + x + ',' + y + ');');
  25619. }
  25620. function quadraticCurveTo(xa, ya, x, y) {
  25621. js.push('c.quadraticCurveTo(' + xa + ',' + ya + ',' +
  25622. x + ',' + y + ');');
  25623. }
  25624. var i = 0;
  25625. var numberOfContours = ((code[i] << 24) | (code[i + 1] << 16)) >> 16;
  25626. var flags;
  25627. var x = 0, y = 0;
  25628. i += 10;
  25629. if (numberOfContours < 0) {
  25630. // composite glyph
  25631. do {
  25632. flags = (code[i] << 8) | code[i + 1];
  25633. var glyphIndex = (code[i + 2] << 8) | code[i + 3];
  25634. i += 4;
  25635. var arg1, arg2;
  25636. if ((flags & 0x01)) {
  25637. arg1 = ((code[i] << 24) | (code[i + 1] << 16)) >> 16;
  25638. arg2 = ((code[i + 2] << 24) | (code[i + 3] << 16)) >> 16;
  25639. i += 4;
  25640. } else {
  25641. arg1 = code[i++]; arg2 = code[i++];
  25642. }
  25643. if ((flags & 0x02)) {
  25644. x = arg1;
  25645. y = arg2;
  25646. } else {
  25647. x = 0; y = 0; // TODO "they are points" ?
  25648. }
  25649. var scaleX = 1, scaleY = 1, scale01 = 0, scale10 = 0;
  25650. if ((flags & 0x08)) {
  25651. scaleX =
  25652. scaleY = ((code[i] << 24) | (code[i + 1] << 16)) / 1073741824;
  25653. i += 2;
  25654. } else if ((flags & 0x40)) {
  25655. scaleX = ((code[i] << 24) | (code[i + 1] << 16)) / 1073741824;
  25656. scaleY = ((code[i + 2] << 24) | (code[i + 3] << 16)) / 1073741824;
  25657. i += 4;
  25658. } else if ((flags & 0x80)) {
  25659. scaleX = ((code[i] << 24) | (code[i + 1] << 16)) / 1073741824;
  25660. scale01 = ((code[i + 2] << 24) | (code[i + 3] << 16)) / 1073741824;
  25661. scale10 = ((code[i + 4] << 24) | (code[i + 5] << 16)) / 1073741824;
  25662. scaleY = ((code[i + 6] << 24) | (code[i + 7] << 16)) / 1073741824;
  25663. i += 8;
  25664. }
  25665. var subglyph = font.glyphs[glyphIndex];
  25666. if (subglyph) {
  25667. js.push('c.save();');
  25668. js.push('c.transform(' + scaleX + ',' + scale01 + ',' +
  25669. scale10 + ',' + scaleY + ',' + x + ',' + y + ');');
  25670. compileGlyf(subglyph, js, font);
  25671. js.push('c.restore();');
  25672. }
  25673. } while ((flags & 0x20));
  25674. } else {
  25675. // simple glyph
  25676. var endPtsOfContours = [];
  25677. var j, jj;
  25678. for (j = 0; j < numberOfContours; j++) {
  25679. endPtsOfContours.push((code[i] << 8) | code[i + 1]);
  25680. i += 2;
  25681. }
  25682. var instructionLength = (code[i] << 8) | code[i + 1];
  25683. i += 2 + instructionLength; // skipping the instructions
  25684. var numberOfPoints = endPtsOfContours[endPtsOfContours.length - 1] + 1;
  25685. var points = [];
  25686. while (points.length < numberOfPoints) {
  25687. flags = code[i++];
  25688. var repeat = 1;
  25689. if ((flags & 0x08)) {
  25690. repeat += code[i++];
  25691. }
  25692. while (repeat-- > 0) {
  25693. points.push({flags: flags});
  25694. }
  25695. }
  25696. for (j = 0; j < numberOfPoints; j++) {
  25697. switch (points[j].flags & 0x12) {
  25698. case 0x00:
  25699. x += ((code[i] << 24) | (code[i + 1] << 16)) >> 16;
  25700. i += 2;
  25701. break;
  25702. case 0x02:
  25703. x -= code[i++];
  25704. break;
  25705. case 0x12:
  25706. x += code[i++];
  25707. break;
  25708. }
  25709. points[j].x = x;
  25710. }
  25711. for (j = 0; j < numberOfPoints; j++) {
  25712. switch (points[j].flags & 0x24) {
  25713. case 0x00:
  25714. y += ((code[i] << 24) | (code[i + 1] << 16)) >> 16;
  25715. i += 2;
  25716. break;
  25717. case 0x04:
  25718. y -= code[i++];
  25719. break;
  25720. case 0x24:
  25721. y += code[i++];
  25722. break;
  25723. }
  25724. points[j].y = y;
  25725. }
  25726. var startPoint = 0;
  25727. for (i = 0; i < numberOfContours; i++) {
  25728. var endPoint = endPtsOfContours[i];
  25729. // contours might have implicit points, which is located in the middle
  25730. // between two neighboring off-curve points
  25731. var contour = points.slice(startPoint, endPoint + 1);
  25732. if ((contour[0].flags & 1)) {
  25733. contour.push(contour[0]); // using start point at the contour end
  25734. } else if ((contour[contour.length - 1].flags & 1)) {
  25735. // first is off-curve point, trying to use one from the end
  25736. contour.unshift(contour[contour.length - 1]);
  25737. } else {
  25738. // start and end are off-curve points, creating implicit one
  25739. var p = {
  25740. flags: 1,
  25741. x: (contour[0].x + contour[contour.length - 1].x) / 2,
  25742. y: (contour[0].y + contour[contour.length - 1].y) / 2
  25743. };
  25744. contour.unshift(p);
  25745. contour.push(p);
  25746. }
  25747. moveTo(contour[0].x, contour[0].y);
  25748. for (j = 1, jj = contour.length; j < jj; j++) {
  25749. if ((contour[j].flags & 1)) {
  25750. lineTo(contour[j].x, contour[j].y);
  25751. } else if ((contour[j + 1].flags & 1)){
  25752. quadraticCurveTo(contour[j].x, contour[j].y,
  25753. contour[j + 1].x, contour[j + 1].y);
  25754. j++;
  25755. } else {
  25756. quadraticCurveTo(contour[j].x, contour[j].y,
  25757. (contour[j].x + contour[j + 1].x) / 2,
  25758. (contour[j].y + contour[j + 1].y) / 2);
  25759. }
  25760. }
  25761. startPoint = endPoint + 1;
  25762. }
  25763. }
  25764. }
  25765. function compileCharString(code, js, font) {
  25766. var stack = [];
  25767. var x = 0, y = 0;
  25768. var stems = 0;
  25769. function moveTo(x, y) {
  25770. js.push('c.moveTo(' + x + ',' + y + ');');
  25771. }
  25772. function lineTo(x, y) {
  25773. js.push('c.lineTo(' + x + ',' + y + ');');
  25774. }
  25775. function bezierCurveTo(x1, y1, x2, y2, x, y) {
  25776. js.push('c.bezierCurveTo(' + x1 + ',' + y1 + ',' + x2 + ',' + y2 + ',' +
  25777. x + ',' + y + ');');
  25778. }
  25779. function parse(code) {
  25780. var i = 0;
  25781. while (i < code.length) {
  25782. var stackClean = false;
  25783. var v = code[i++];
  25784. var xa, xb, ya, yb, y1, y2, y3, n, subrCode;
  25785. switch (v) {
  25786. case 1: // hstem
  25787. stems += stack.length >> 1;
  25788. stackClean = true;
  25789. break;
  25790. case 3: // vstem
  25791. stems += stack.length >> 1;
  25792. stackClean = true;
  25793. break;
  25794. case 4: // vmoveto
  25795. y += stack.pop();
  25796. moveTo(x, y);
  25797. stackClean = true;
  25798. break;
  25799. case 5: // rlineto
  25800. while (stack.length > 0) {
  25801. x += stack.shift();
  25802. y += stack.shift();
  25803. lineTo(x, y);
  25804. }
  25805. break;
  25806. case 6: // hlineto
  25807. while (stack.length > 0) {
  25808. x += stack.shift();
  25809. lineTo(x, y);
  25810. if (stack.length === 0) {
  25811. break;
  25812. }
  25813. y += stack.shift();
  25814. lineTo(x, y);
  25815. }
  25816. break;
  25817. case 7: // vlineto
  25818. while (stack.length > 0) {
  25819. y += stack.shift();
  25820. lineTo(x, y);
  25821. if (stack.length === 0) {
  25822. break;
  25823. }
  25824. x += stack.shift();
  25825. lineTo(x, y);
  25826. }
  25827. break;
  25828. case 8: // rrcurveto
  25829. while (stack.length > 0) {
  25830. xa = x + stack.shift(); ya = y + stack.shift();
  25831. xb = xa + stack.shift(); yb = ya + stack.shift();
  25832. x = xb + stack.shift(); y = yb + stack.shift();
  25833. bezierCurveTo(xa, ya, xb, yb, x, y);
  25834. }
  25835. break;
  25836. case 10: // callsubr
  25837. n = stack.pop() + font.subrsBias;
  25838. subrCode = font.subrs[n];
  25839. if (subrCode) {
  25840. parse(subrCode);
  25841. }
  25842. break;
  25843. case 11: // return
  25844. return;
  25845. case 12:
  25846. v = code[i++];
  25847. switch (v) {
  25848. case 34: // flex
  25849. xa = x + stack.shift();
  25850. xb = xa + stack.shift(); y1 = y + stack.shift();
  25851. x = xb + stack.shift();
  25852. bezierCurveTo(xa, y, xb, y1, x, y1);
  25853. xa = x + stack.shift();
  25854. xb = xa + stack.shift();
  25855. x = xb + stack.shift();
  25856. bezierCurveTo(xa, y1, xb, y, x, y);
  25857. break;
  25858. case 35: // flex
  25859. xa = x + stack.shift(); ya = y + stack.shift();
  25860. xb = xa + stack.shift(); yb = ya + stack.shift();
  25861. x = xb + stack.shift(); y = yb + stack.shift();
  25862. bezierCurveTo(xa, ya, xb, yb, x, y);
  25863. xa = x + stack.shift(); ya = y + stack.shift();
  25864. xb = xa + stack.shift(); yb = ya + stack.shift();
  25865. x = xb + stack.shift(); y = yb + stack.shift();
  25866. bezierCurveTo(xa, ya, xb, yb, x, y);
  25867. stack.pop(); // fd
  25868. break;
  25869. case 36: // hflex1
  25870. xa = x + stack.shift(); y1 = y + stack.shift();
  25871. xb = xa + stack.shift(); y2 = y1 + stack.shift();
  25872. x = xb + stack.shift();
  25873. bezierCurveTo(xa, y1, xb, y2, x, y2);
  25874. xa = x + stack.shift();
  25875. xb = xa + stack.shift(); y3 = y2 + stack.shift();
  25876. x = xb + stack.shift();
  25877. bezierCurveTo(xa, y2, xb, y3, x, y);
  25878. break;
  25879. case 37: // flex1
  25880. var x0 = x, y0 = y;
  25881. xa = x + stack.shift(); ya = y + stack.shift();
  25882. xb = xa + stack.shift(); yb = ya + stack.shift();
  25883. x = xb + stack.shift(); y = yb + stack.shift();
  25884. bezierCurveTo(xa, ya, xb, yb, x, y);
  25885. xa = x + stack.shift(); ya = y + stack.shift();
  25886. xb = xa + stack.shift(); yb = ya + stack.shift();
  25887. x = xb; y = yb;
  25888. if (Math.abs(x - x0) > Math.abs(y - y0)) {
  25889. x += stack.shift();
  25890. } else {
  25891. y += stack.shift();
  25892. }
  25893. bezierCurveTo(xa, ya, xb, yb, x, y);
  25894. break;
  25895. default:
  25896. error('unknown operator: 12 ' + v);
  25897. }
  25898. break;
  25899. case 14: // endchar
  25900. if (stack.length >= 4) {
  25901. var achar = stack.pop();
  25902. var bchar = stack.pop();
  25903. y = stack.pop();
  25904. x = stack.pop();
  25905. js.push('c.save();');
  25906. js.push('c.translate('+ x + ',' + y + ');');
  25907. var gid = lookupCmap(font.cmap, String.fromCharCode(
  25908. font.glyphNameMap[Encodings.StandardEncoding[achar]]));
  25909. compileCharString(font.glyphs[gid], js, font);
  25910. js.push('c.restore();');
  25911. gid = lookupCmap(font.cmap, String.fromCharCode(
  25912. font.glyphNameMap[Encodings.StandardEncoding[bchar]]));
  25913. compileCharString(font.glyphs[gid], js, font);
  25914. }
  25915. return;
  25916. case 18: // hstemhm
  25917. stems += stack.length >> 1;
  25918. stackClean = true;
  25919. break;
  25920. case 19: // hintmask
  25921. stems += stack.length >> 1;
  25922. i += (stems + 7) >> 3;
  25923. stackClean = true;
  25924. break;
  25925. case 20: // cntrmask
  25926. stems += stack.length >> 1;
  25927. i += (stems + 7) >> 3;
  25928. stackClean = true;
  25929. break;
  25930. case 21: // rmoveto
  25931. y += stack.pop();
  25932. x += stack.pop();
  25933. moveTo(x, y);
  25934. stackClean = true;
  25935. break;
  25936. case 22: // hmoveto
  25937. x += stack.pop();
  25938. moveTo(x, y);
  25939. stackClean = true;
  25940. break;
  25941. case 23: // vstemhm
  25942. stems += stack.length >> 1;
  25943. stackClean = true;
  25944. break;
  25945. case 24: // rcurveline
  25946. while (stack.length > 2) {
  25947. xa = x + stack.shift(); ya = y + stack.shift();
  25948. xb = xa + stack.shift(); yb = ya + stack.shift();
  25949. x = xb + stack.shift(); y = yb + stack.shift();
  25950. bezierCurveTo(xa, ya, xb, yb, x, y);
  25951. }
  25952. x += stack.shift();
  25953. y += stack.shift();
  25954. lineTo(x, y);
  25955. break;
  25956. case 25: // rlinecurve
  25957. while (stack.length > 6) {
  25958. x += stack.shift();
  25959. y += stack.shift();
  25960. lineTo(x, y);
  25961. }
  25962. xa = x + stack.shift(); ya = y + stack.shift();
  25963. xb = xa + stack.shift(); yb = ya + stack.shift();
  25964. x = xb + stack.shift(); y = yb + stack.shift();
  25965. bezierCurveTo(xa, ya, xb, yb, x, y);
  25966. break;
  25967. case 26: // vvcurveto
  25968. if (stack.length % 2) {
  25969. x += stack.shift();
  25970. }
  25971. while (stack.length > 0) {
  25972. xa = x; ya = y + stack.shift();
  25973. xb = xa + stack.shift(); yb = ya + stack.shift();
  25974. x = xb; y = yb + stack.shift();
  25975. bezierCurveTo(xa, ya, xb, yb, x, y);
  25976. }
  25977. break;
  25978. case 27: // hhcurveto
  25979. if (stack.length % 2) {
  25980. y += stack.shift();
  25981. }
  25982. while (stack.length > 0) {
  25983. xa = x + stack.shift(); ya = y;
  25984. xb = xa + stack.shift(); yb = ya + stack.shift();
  25985. x = xb + stack.shift(); y = yb;
  25986. bezierCurveTo(xa, ya, xb, yb, x, y);
  25987. }
  25988. break;
  25989. case 28:
  25990. stack.push(((code[i] << 24) | (code[i + 1] << 16)) >> 16);
  25991. i += 2;
  25992. break;
  25993. case 29: // callgsubr
  25994. n = stack.pop() + font.gsubrsBias;
  25995. subrCode = font.gsubrs[n];
  25996. if (subrCode) {
  25997. parse(subrCode);
  25998. }
  25999. break;
  26000. case 30: // vhcurveto
  26001. while (stack.length > 0) {
  26002. xa = x; ya = y + stack.shift();
  26003. xb = xa + stack.shift(); yb = ya + stack.shift();
  26004. x = xb + stack.shift();
  26005. y = yb + (stack.length === 1 ? stack.shift() : 0);
  26006. bezierCurveTo(xa, ya, xb, yb, x, y);
  26007. if (stack.length === 0) {
  26008. break;
  26009. }
  26010. xa = x + stack.shift(); ya = y;
  26011. xb = xa + stack.shift(); yb = ya + stack.shift();
  26012. y = yb + stack.shift();
  26013. x = xb + (stack.length === 1 ? stack.shift() : 0);
  26014. bezierCurveTo(xa, ya, xb, yb, x, y);
  26015. }
  26016. break;
  26017. case 31: // hvcurveto
  26018. while (stack.length > 0) {
  26019. xa = x + stack.shift(); ya = y;
  26020. xb = xa + stack.shift(); yb = ya + stack.shift();
  26021. y = yb + stack.shift();
  26022. x = xb + (stack.length === 1 ? stack.shift() : 0);
  26023. bezierCurveTo(xa, ya, xb, yb, x, y);
  26024. if (stack.length === 0) {
  26025. break;
  26026. }
  26027. xa = x; ya = y + stack.shift();
  26028. xb = xa + stack.shift(); yb = ya + stack.shift();
  26029. x = xb + stack.shift();
  26030. y = yb + (stack.length === 1 ? stack.shift() : 0);
  26031. bezierCurveTo(xa, ya, xb, yb, x, y);
  26032. }
  26033. break;
  26034. default:
  26035. if (v < 32) {
  26036. error('unknown operator: ' + v);
  26037. }
  26038. if (v < 247) {
  26039. stack.push(v - 139);
  26040. } else if (v < 251) {
  26041. stack.push((v - 247) * 256 + code[i++] + 108);
  26042. } else if (v < 255) {
  26043. stack.push(-(v - 251) * 256 - code[i++] - 108);
  26044. } else {
  26045. stack.push(((code[i] << 24) | (code[i + 1] << 16) |
  26046. (code[i + 2] << 8) | code[i + 3]) / 65536);
  26047. i += 4;
  26048. }
  26049. break;
  26050. }
  26051. if (stackClean) {
  26052. stack.length = 0;
  26053. }
  26054. }
  26055. }
  26056. parse(code);
  26057. }
  26058. var noop = '';
  26059. function CompiledFont(fontMatrix) {
  26060. this.compiledGlyphs = {};
  26061. this.fontMatrix = fontMatrix;
  26062. }
  26063. CompiledFont.prototype = {
  26064. getPathJs: function (unicode) {
  26065. var gid = lookupCmap(this.cmap, unicode);
  26066. var fn = this.compiledGlyphs[gid];
  26067. if (!fn) {
  26068. this.compiledGlyphs[gid] = fn = this.compileGlyph(this.glyphs[gid]);
  26069. }
  26070. return fn;
  26071. },
  26072. compileGlyph: function (code) {
  26073. if (!code || code.length === 0 || code[0] === 14) {
  26074. return noop;
  26075. }
  26076. var js = [];
  26077. js.push('c.save();');
  26078. js.push('c.transform(' + this.fontMatrix.join(',') + ');');
  26079. js.push('c.scale(size, -size);');
  26080. this.compileGlyphImpl(code, js);
  26081. js.push('c.restore();');
  26082. return js.join('\n');
  26083. },
  26084. compileGlyphImpl: function () {
  26085. error('Children classes should implement this.');
  26086. },
  26087. hasBuiltPath: function (unicode) {
  26088. var gid = lookupCmap(this.cmap, unicode);
  26089. return gid in this.compiledGlyphs;
  26090. }
  26091. };
  26092. function TrueTypeCompiled(glyphs, cmap, fontMatrix) {
  26093. fontMatrix = fontMatrix || [0.000488, 0, 0, 0.000488, 0, 0];
  26094. CompiledFont.call(this, fontMatrix);
  26095. this.glyphs = glyphs;
  26096. this.cmap = cmap;
  26097. this.compiledGlyphs = [];
  26098. }
  26099. Util.inherit(TrueTypeCompiled, CompiledFont, {
  26100. compileGlyphImpl: function (code, js) {
  26101. compileGlyf(code, js, this);
  26102. }
  26103. });
  26104. function Type2Compiled(cffInfo, cmap, fontMatrix, glyphNameMap) {
  26105. fontMatrix = fontMatrix || [0.001, 0, 0, 0.001, 0, 0];
  26106. CompiledFont.call(this, fontMatrix);
  26107. this.glyphs = cffInfo.glyphs;
  26108. this.gsubrs = cffInfo.gsubrs || [];
  26109. this.subrs = cffInfo.subrs || [];
  26110. this.cmap = cmap;
  26111. this.glyphNameMap = glyphNameMap || GlyphsUnicode;
  26112. this.compiledGlyphs = [];
  26113. this.gsubrsBias = (this.gsubrs.length < 1240 ?
  26114. 107 : (this.gsubrs.length < 33900 ? 1131 : 32768));
  26115. this.subrsBias = (this.subrs.length < 1240 ?
  26116. 107 : (this.subrs.length < 33900 ? 1131 : 32768));
  26117. }
  26118. Util.inherit(Type2Compiled, CompiledFont, {
  26119. compileGlyphImpl: function (code, js) {
  26120. compileCharString(code, js, this);
  26121. }
  26122. });
  26123. return {
  26124. create: function FontRendererFactory_create(font) {
  26125. var data = new Uint8Array(font.data);
  26126. var cmap, glyf, loca, cff, indexToLocFormat, unitsPerEm;
  26127. var numTables = getUshort(data, 4);
  26128. for (var i = 0, p = 12; i < numTables; i++, p += 16) {
  26129. var tag = bytesToString(data.subarray(p, p + 4));
  26130. var offset = getLong(data, p + 8);
  26131. var length = getLong(data, p + 12);
  26132. switch (tag) {
  26133. case 'cmap':
  26134. cmap = parseCmap(data, offset, offset + length);
  26135. break;
  26136. case 'glyf':
  26137. glyf = data.subarray(offset, offset + length);
  26138. break;
  26139. case 'loca':
  26140. loca = data.subarray(offset, offset + length);
  26141. break;
  26142. case 'head':
  26143. unitsPerEm = getUshort(data, offset + 18);
  26144. indexToLocFormat = getUshort(data, offset + 50);
  26145. break;
  26146. case 'CFF ':
  26147. cff = parseCff(data, offset, offset + length);
  26148. break;
  26149. }
  26150. }
  26151. if (glyf) {
  26152. var fontMatrix = (!unitsPerEm ? font.fontMatrix :
  26153. [1 / unitsPerEm, 0, 0, 1 / unitsPerEm, 0, 0]);
  26154. return new TrueTypeCompiled(
  26155. parseGlyfTable(glyf, loca, indexToLocFormat), cmap, fontMatrix);
  26156. } else {
  26157. return new Type2Compiled(cff, cmap, font.fontMatrix, font.glyphNameMap);
  26158. }
  26159. }
  26160. };
  26161. })();
  26162. var GlyphsUnicode = {
  26163. A: 0x0041,
  26164. AE: 0x00C6,
  26165. AEacute: 0x01FC,
  26166. AEmacron: 0x01E2,
  26167. AEsmall: 0xF7E6,
  26168. Aacute: 0x00C1,
  26169. Aacutesmall: 0xF7E1,
  26170. Abreve: 0x0102,
  26171. Abreveacute: 0x1EAE,
  26172. Abrevecyrillic: 0x04D0,
  26173. Abrevedotbelow: 0x1EB6,
  26174. Abrevegrave: 0x1EB0,
  26175. Abrevehookabove: 0x1EB2,
  26176. Abrevetilde: 0x1EB4,
  26177. Acaron: 0x01CD,
  26178. Acircle: 0x24B6,
  26179. Acircumflex: 0x00C2,
  26180. Acircumflexacute: 0x1EA4,
  26181. Acircumflexdotbelow: 0x1EAC,
  26182. Acircumflexgrave: 0x1EA6,
  26183. Acircumflexhookabove: 0x1EA8,
  26184. Acircumflexsmall: 0xF7E2,
  26185. Acircumflextilde: 0x1EAA,
  26186. Acute: 0xF6C9,
  26187. Acutesmall: 0xF7B4,
  26188. Acyrillic: 0x0410,
  26189. Adblgrave: 0x0200,
  26190. Adieresis: 0x00C4,
  26191. Adieresiscyrillic: 0x04D2,
  26192. Adieresismacron: 0x01DE,
  26193. Adieresissmall: 0xF7E4,
  26194. Adotbelow: 0x1EA0,
  26195. Adotmacron: 0x01E0,
  26196. Agrave: 0x00C0,
  26197. Agravesmall: 0xF7E0,
  26198. Ahookabove: 0x1EA2,
  26199. Aiecyrillic: 0x04D4,
  26200. Ainvertedbreve: 0x0202,
  26201. Alpha: 0x0391,
  26202. Alphatonos: 0x0386,
  26203. Amacron: 0x0100,
  26204. Amonospace: 0xFF21,
  26205. Aogonek: 0x0104,
  26206. Aring: 0x00C5,
  26207. Aringacute: 0x01FA,
  26208. Aringbelow: 0x1E00,
  26209. Aringsmall: 0xF7E5,
  26210. Asmall: 0xF761,
  26211. Atilde: 0x00C3,
  26212. Atildesmall: 0xF7E3,
  26213. Aybarmenian: 0x0531,
  26214. B: 0x0042,
  26215. Bcircle: 0x24B7,
  26216. Bdotaccent: 0x1E02,
  26217. Bdotbelow: 0x1E04,
  26218. Becyrillic: 0x0411,
  26219. Benarmenian: 0x0532,
  26220. Beta: 0x0392,
  26221. Bhook: 0x0181,
  26222. Blinebelow: 0x1E06,
  26223. Bmonospace: 0xFF22,
  26224. Brevesmall: 0xF6F4,
  26225. Bsmall: 0xF762,
  26226. Btopbar: 0x0182,
  26227. C: 0x0043,
  26228. Caarmenian: 0x053E,
  26229. Cacute: 0x0106,
  26230. Caron: 0xF6CA,
  26231. Caronsmall: 0xF6F5,
  26232. Ccaron: 0x010C,
  26233. Ccedilla: 0x00C7,
  26234. Ccedillaacute: 0x1E08,
  26235. Ccedillasmall: 0xF7E7,
  26236. Ccircle: 0x24B8,
  26237. Ccircumflex: 0x0108,
  26238. Cdot: 0x010A,
  26239. Cdotaccent: 0x010A,
  26240. Cedillasmall: 0xF7B8,
  26241. Chaarmenian: 0x0549,
  26242. Cheabkhasiancyrillic: 0x04BC,
  26243. Checyrillic: 0x0427,
  26244. Chedescenderabkhasiancyrillic: 0x04BE,
  26245. Chedescendercyrillic: 0x04B6,
  26246. Chedieresiscyrillic: 0x04F4,
  26247. Cheharmenian: 0x0543,
  26248. Chekhakassiancyrillic: 0x04CB,
  26249. Cheverticalstrokecyrillic: 0x04B8,
  26250. Chi: 0x03A7,
  26251. Chook: 0x0187,
  26252. Circumflexsmall: 0xF6F6,
  26253. Cmonospace: 0xFF23,
  26254. Coarmenian: 0x0551,
  26255. Csmall: 0xF763,
  26256. D: 0x0044,
  26257. DZ: 0x01F1,
  26258. DZcaron: 0x01C4,
  26259. Daarmenian: 0x0534,
  26260. Dafrican: 0x0189,
  26261. Dcaron: 0x010E,
  26262. Dcedilla: 0x1E10,
  26263. Dcircle: 0x24B9,
  26264. Dcircumflexbelow: 0x1E12,
  26265. Dcroat: 0x0110,
  26266. Ddotaccent: 0x1E0A,
  26267. Ddotbelow: 0x1E0C,
  26268. Decyrillic: 0x0414,
  26269. Deicoptic: 0x03EE,
  26270. Delta: 0x2206,
  26271. Deltagreek: 0x0394,
  26272. Dhook: 0x018A,
  26273. Dieresis: 0xF6CB,
  26274. DieresisAcute: 0xF6CC,
  26275. DieresisGrave: 0xF6CD,
  26276. Dieresissmall: 0xF7A8,
  26277. Digammagreek: 0x03DC,
  26278. Djecyrillic: 0x0402,
  26279. Dlinebelow: 0x1E0E,
  26280. Dmonospace: 0xFF24,
  26281. Dotaccentsmall: 0xF6F7,
  26282. Dslash: 0x0110,
  26283. Dsmall: 0xF764,
  26284. Dtopbar: 0x018B,
  26285. Dz: 0x01F2,
  26286. Dzcaron: 0x01C5,
  26287. Dzeabkhasiancyrillic: 0x04E0,
  26288. Dzecyrillic: 0x0405,
  26289. Dzhecyrillic: 0x040F,
  26290. E: 0x0045,
  26291. Eacute: 0x00C9,
  26292. Eacutesmall: 0xF7E9,
  26293. Ebreve: 0x0114,
  26294. Ecaron: 0x011A,
  26295. Ecedillabreve: 0x1E1C,
  26296. Echarmenian: 0x0535,
  26297. Ecircle: 0x24BA,
  26298. Ecircumflex: 0x00CA,
  26299. Ecircumflexacute: 0x1EBE,
  26300. Ecircumflexbelow: 0x1E18,
  26301. Ecircumflexdotbelow: 0x1EC6,
  26302. Ecircumflexgrave: 0x1EC0,
  26303. Ecircumflexhookabove: 0x1EC2,
  26304. Ecircumflexsmall: 0xF7EA,
  26305. Ecircumflextilde: 0x1EC4,
  26306. Ecyrillic: 0x0404,
  26307. Edblgrave: 0x0204,
  26308. Edieresis: 0x00CB,
  26309. Edieresissmall: 0xF7EB,
  26310. Edot: 0x0116,
  26311. Edotaccent: 0x0116,
  26312. Edotbelow: 0x1EB8,
  26313. Efcyrillic: 0x0424,
  26314. Egrave: 0x00C8,
  26315. Egravesmall: 0xF7E8,
  26316. Eharmenian: 0x0537,
  26317. Ehookabove: 0x1EBA,
  26318. Eightroman: 0x2167,
  26319. Einvertedbreve: 0x0206,
  26320. Eiotifiedcyrillic: 0x0464,
  26321. Elcyrillic: 0x041B,
  26322. Elevenroman: 0x216A,
  26323. Emacron: 0x0112,
  26324. Emacronacute: 0x1E16,
  26325. Emacrongrave: 0x1E14,
  26326. Emcyrillic: 0x041C,
  26327. Emonospace: 0xFF25,
  26328. Encyrillic: 0x041D,
  26329. Endescendercyrillic: 0x04A2,
  26330. Eng: 0x014A,
  26331. Enghecyrillic: 0x04A4,
  26332. Enhookcyrillic: 0x04C7,
  26333. Eogonek: 0x0118,
  26334. Eopen: 0x0190,
  26335. Epsilon: 0x0395,
  26336. Epsilontonos: 0x0388,
  26337. Ercyrillic: 0x0420,
  26338. Ereversed: 0x018E,
  26339. Ereversedcyrillic: 0x042D,
  26340. Escyrillic: 0x0421,
  26341. Esdescendercyrillic: 0x04AA,
  26342. Esh: 0x01A9,
  26343. Esmall: 0xF765,
  26344. Eta: 0x0397,
  26345. Etarmenian: 0x0538,
  26346. Etatonos: 0x0389,
  26347. Eth: 0x00D0,
  26348. Ethsmall: 0xF7F0,
  26349. Etilde: 0x1EBC,
  26350. Etildebelow: 0x1E1A,
  26351. Euro: 0x20AC,
  26352. Ezh: 0x01B7,
  26353. Ezhcaron: 0x01EE,
  26354. Ezhreversed: 0x01B8,
  26355. F: 0x0046,
  26356. Fcircle: 0x24BB,
  26357. Fdotaccent: 0x1E1E,
  26358. Feharmenian: 0x0556,
  26359. Feicoptic: 0x03E4,
  26360. Fhook: 0x0191,
  26361. Fitacyrillic: 0x0472,
  26362. Fiveroman: 0x2164,
  26363. Fmonospace: 0xFF26,
  26364. Fourroman: 0x2163,
  26365. Fsmall: 0xF766,
  26366. G: 0x0047,
  26367. GBsquare: 0x3387,
  26368. Gacute: 0x01F4,
  26369. Gamma: 0x0393,
  26370. Gammaafrican: 0x0194,
  26371. Gangiacoptic: 0x03EA,
  26372. Gbreve: 0x011E,
  26373. Gcaron: 0x01E6,
  26374. Gcedilla: 0x0122,
  26375. Gcircle: 0x24BC,
  26376. Gcircumflex: 0x011C,
  26377. Gcommaaccent: 0x0122,
  26378. Gdot: 0x0120,
  26379. Gdotaccent: 0x0120,
  26380. Gecyrillic: 0x0413,
  26381. Ghadarmenian: 0x0542,
  26382. Ghemiddlehookcyrillic: 0x0494,
  26383. Ghestrokecyrillic: 0x0492,
  26384. Gheupturncyrillic: 0x0490,
  26385. Ghook: 0x0193,
  26386. Gimarmenian: 0x0533,
  26387. Gjecyrillic: 0x0403,
  26388. Gmacron: 0x1E20,
  26389. Gmonospace: 0xFF27,
  26390. Grave: 0xF6CE,
  26391. Gravesmall: 0xF760,
  26392. Gsmall: 0xF767,
  26393. Gsmallhook: 0x029B,
  26394. Gstroke: 0x01E4,
  26395. H: 0x0048,
  26396. H18533: 0x25CF,
  26397. H18543: 0x25AA,
  26398. H18551: 0x25AB,
  26399. H22073: 0x25A1,
  26400. HPsquare: 0x33CB,
  26401. Haabkhasiancyrillic: 0x04A8,
  26402. Hadescendercyrillic: 0x04B2,
  26403. Hardsigncyrillic: 0x042A,
  26404. Hbar: 0x0126,
  26405. Hbrevebelow: 0x1E2A,
  26406. Hcedilla: 0x1E28,
  26407. Hcircle: 0x24BD,
  26408. Hcircumflex: 0x0124,
  26409. Hdieresis: 0x1E26,
  26410. Hdotaccent: 0x1E22,
  26411. Hdotbelow: 0x1E24,
  26412. Hmonospace: 0xFF28,
  26413. Hoarmenian: 0x0540,
  26414. Horicoptic: 0x03E8,
  26415. Hsmall: 0xF768,
  26416. Hungarumlaut: 0xF6CF,
  26417. Hungarumlautsmall: 0xF6F8,
  26418. Hzsquare: 0x3390,
  26419. I: 0x0049,
  26420. IAcyrillic: 0x042F,
  26421. IJ: 0x0132,
  26422. IUcyrillic: 0x042E,
  26423. Iacute: 0x00CD,
  26424. Iacutesmall: 0xF7ED,
  26425. Ibreve: 0x012C,
  26426. Icaron: 0x01CF,
  26427. Icircle: 0x24BE,
  26428. Icircumflex: 0x00CE,
  26429. Icircumflexsmall: 0xF7EE,
  26430. Icyrillic: 0x0406,
  26431. Idblgrave: 0x0208,
  26432. Idieresis: 0x00CF,
  26433. Idieresisacute: 0x1E2E,
  26434. Idieresiscyrillic: 0x04E4,
  26435. Idieresissmall: 0xF7EF,
  26436. Idot: 0x0130,
  26437. Idotaccent: 0x0130,
  26438. Idotbelow: 0x1ECA,
  26439. Iebrevecyrillic: 0x04D6,
  26440. Iecyrillic: 0x0415,
  26441. Ifraktur: 0x2111,
  26442. Igrave: 0x00CC,
  26443. Igravesmall: 0xF7EC,
  26444. Ihookabove: 0x1EC8,
  26445. Iicyrillic: 0x0418,
  26446. Iinvertedbreve: 0x020A,
  26447. Iishortcyrillic: 0x0419,
  26448. Imacron: 0x012A,
  26449. Imacroncyrillic: 0x04E2,
  26450. Imonospace: 0xFF29,
  26451. Iniarmenian: 0x053B,
  26452. Iocyrillic: 0x0401,
  26453. Iogonek: 0x012E,
  26454. Iota: 0x0399,
  26455. Iotaafrican: 0x0196,
  26456. Iotadieresis: 0x03AA,
  26457. Iotatonos: 0x038A,
  26458. Ismall: 0xF769,
  26459. Istroke: 0x0197,
  26460. Itilde: 0x0128,
  26461. Itildebelow: 0x1E2C,
  26462. Izhitsacyrillic: 0x0474,
  26463. Izhitsadblgravecyrillic: 0x0476,
  26464. J: 0x004A,
  26465. Jaarmenian: 0x0541,
  26466. Jcircle: 0x24BF,
  26467. Jcircumflex: 0x0134,
  26468. Jecyrillic: 0x0408,
  26469. Jheharmenian: 0x054B,
  26470. Jmonospace: 0xFF2A,
  26471. Jsmall: 0xF76A,
  26472. K: 0x004B,
  26473. KBsquare: 0x3385,
  26474. KKsquare: 0x33CD,
  26475. Kabashkircyrillic: 0x04A0,
  26476. Kacute: 0x1E30,
  26477. Kacyrillic: 0x041A,
  26478. Kadescendercyrillic: 0x049A,
  26479. Kahookcyrillic: 0x04C3,
  26480. Kappa: 0x039A,
  26481. Kastrokecyrillic: 0x049E,
  26482. Kaverticalstrokecyrillic: 0x049C,
  26483. Kcaron: 0x01E8,
  26484. Kcedilla: 0x0136,
  26485. Kcircle: 0x24C0,
  26486. Kcommaaccent: 0x0136,
  26487. Kdotbelow: 0x1E32,
  26488. Keharmenian: 0x0554,
  26489. Kenarmenian: 0x053F,
  26490. Khacyrillic: 0x0425,
  26491. Kheicoptic: 0x03E6,
  26492. Khook: 0x0198,
  26493. Kjecyrillic: 0x040C,
  26494. Klinebelow: 0x1E34,
  26495. Kmonospace: 0xFF2B,
  26496. Koppacyrillic: 0x0480,
  26497. Koppagreek: 0x03DE,
  26498. Ksicyrillic: 0x046E,
  26499. Ksmall: 0xF76B,
  26500. L: 0x004C,
  26501. LJ: 0x01C7,
  26502. LL: 0xF6BF,
  26503. Lacute: 0x0139,
  26504. Lambda: 0x039B,
  26505. Lcaron: 0x013D,
  26506. Lcedilla: 0x013B,
  26507. Lcircle: 0x24C1,
  26508. Lcircumflexbelow: 0x1E3C,
  26509. Lcommaaccent: 0x013B,
  26510. Ldot: 0x013F,
  26511. Ldotaccent: 0x013F,
  26512. Ldotbelow: 0x1E36,
  26513. Ldotbelowmacron: 0x1E38,
  26514. Liwnarmenian: 0x053C,
  26515. Lj: 0x01C8,
  26516. Ljecyrillic: 0x0409,
  26517. Llinebelow: 0x1E3A,
  26518. Lmonospace: 0xFF2C,
  26519. Lslash: 0x0141,
  26520. Lslashsmall: 0xF6F9,
  26521. Lsmall: 0xF76C,
  26522. M: 0x004D,
  26523. MBsquare: 0x3386,
  26524. Macron: 0xF6D0,
  26525. Macronsmall: 0xF7AF,
  26526. Macute: 0x1E3E,
  26527. Mcircle: 0x24C2,
  26528. Mdotaccent: 0x1E40,
  26529. Mdotbelow: 0x1E42,
  26530. Menarmenian: 0x0544,
  26531. Mmonospace: 0xFF2D,
  26532. Msmall: 0xF76D,
  26533. Mturned: 0x019C,
  26534. Mu: 0x039C,
  26535. N: 0x004E,
  26536. NJ: 0x01CA,
  26537. Nacute: 0x0143,
  26538. Ncaron: 0x0147,
  26539. Ncedilla: 0x0145,
  26540. Ncircle: 0x24C3,
  26541. Ncircumflexbelow: 0x1E4A,
  26542. Ncommaaccent: 0x0145,
  26543. Ndotaccent: 0x1E44,
  26544. Ndotbelow: 0x1E46,
  26545. Nhookleft: 0x019D,
  26546. Nineroman: 0x2168,
  26547. Nj: 0x01CB,
  26548. Njecyrillic: 0x040A,
  26549. Nlinebelow: 0x1E48,
  26550. Nmonospace: 0xFF2E,
  26551. Nowarmenian: 0x0546,
  26552. Nsmall: 0xF76E,
  26553. Ntilde: 0x00D1,
  26554. Ntildesmall: 0xF7F1,
  26555. Nu: 0x039D,
  26556. O: 0x004F,
  26557. OE: 0x0152,
  26558. OEsmall: 0xF6FA,
  26559. Oacute: 0x00D3,
  26560. Oacutesmall: 0xF7F3,
  26561. Obarredcyrillic: 0x04E8,
  26562. Obarreddieresiscyrillic: 0x04EA,
  26563. Obreve: 0x014E,
  26564. Ocaron: 0x01D1,
  26565. Ocenteredtilde: 0x019F,
  26566. Ocircle: 0x24C4,
  26567. Ocircumflex: 0x00D4,
  26568. Ocircumflexacute: 0x1ED0,
  26569. Ocircumflexdotbelow: 0x1ED8,
  26570. Ocircumflexgrave: 0x1ED2,
  26571. Ocircumflexhookabove: 0x1ED4,
  26572. Ocircumflexsmall: 0xF7F4,
  26573. Ocircumflextilde: 0x1ED6,
  26574. Ocyrillic: 0x041E,
  26575. Odblacute: 0x0150,
  26576. Odblgrave: 0x020C,
  26577. Odieresis: 0x00D6,
  26578. Odieresiscyrillic: 0x04E6,
  26579. Odieresissmall: 0xF7F6,
  26580. Odotbelow: 0x1ECC,
  26581. Ogoneksmall: 0xF6FB,
  26582. Ograve: 0x00D2,
  26583. Ogravesmall: 0xF7F2,
  26584. Oharmenian: 0x0555,
  26585. Ohm: 0x2126,
  26586. Ohookabove: 0x1ECE,
  26587. Ohorn: 0x01A0,
  26588. Ohornacute: 0x1EDA,
  26589. Ohorndotbelow: 0x1EE2,
  26590. Ohorngrave: 0x1EDC,
  26591. Ohornhookabove: 0x1EDE,
  26592. Ohorntilde: 0x1EE0,
  26593. Ohungarumlaut: 0x0150,
  26594. Oi: 0x01A2,
  26595. Oinvertedbreve: 0x020E,
  26596. Omacron: 0x014C,
  26597. Omacronacute: 0x1E52,
  26598. Omacrongrave: 0x1E50,
  26599. Omega: 0x2126,
  26600. Omegacyrillic: 0x0460,
  26601. Omegagreek: 0x03A9,
  26602. Omegaroundcyrillic: 0x047A,
  26603. Omegatitlocyrillic: 0x047C,
  26604. Omegatonos: 0x038F,
  26605. Omicron: 0x039F,
  26606. Omicrontonos: 0x038C,
  26607. Omonospace: 0xFF2F,
  26608. Oneroman: 0x2160,
  26609. Oogonek: 0x01EA,
  26610. Oogonekmacron: 0x01EC,
  26611. Oopen: 0x0186,
  26612. Oslash: 0x00D8,
  26613. Oslashacute: 0x01FE,
  26614. Oslashsmall: 0xF7F8,
  26615. Osmall: 0xF76F,
  26616. Ostrokeacute: 0x01FE,
  26617. Otcyrillic: 0x047E,
  26618. Otilde: 0x00D5,
  26619. Otildeacute: 0x1E4C,
  26620. Otildedieresis: 0x1E4E,
  26621. Otildesmall: 0xF7F5,
  26622. P: 0x0050,
  26623. Pacute: 0x1E54,
  26624. Pcircle: 0x24C5,
  26625. Pdotaccent: 0x1E56,
  26626. Pecyrillic: 0x041F,
  26627. Peharmenian: 0x054A,
  26628. Pemiddlehookcyrillic: 0x04A6,
  26629. Phi: 0x03A6,
  26630. Phook: 0x01A4,
  26631. Pi: 0x03A0,
  26632. Piwrarmenian: 0x0553,
  26633. Pmonospace: 0xFF30,
  26634. Psi: 0x03A8,
  26635. Psicyrillic: 0x0470,
  26636. Psmall: 0xF770,
  26637. Q: 0x0051,
  26638. Qcircle: 0x24C6,
  26639. Qmonospace: 0xFF31,
  26640. Qsmall: 0xF771,
  26641. R: 0x0052,
  26642. Raarmenian: 0x054C,
  26643. Racute: 0x0154,
  26644. Rcaron: 0x0158,
  26645. Rcedilla: 0x0156,
  26646. Rcircle: 0x24C7,
  26647. Rcommaaccent: 0x0156,
  26648. Rdblgrave: 0x0210,
  26649. Rdotaccent: 0x1E58,
  26650. Rdotbelow: 0x1E5A,
  26651. Rdotbelowmacron: 0x1E5C,
  26652. Reharmenian: 0x0550,
  26653. Rfraktur: 0x211C,
  26654. Rho: 0x03A1,
  26655. Ringsmall: 0xF6FC,
  26656. Rinvertedbreve: 0x0212,
  26657. Rlinebelow: 0x1E5E,
  26658. Rmonospace: 0xFF32,
  26659. Rsmall: 0xF772,
  26660. Rsmallinverted: 0x0281,
  26661. Rsmallinvertedsuperior: 0x02B6,
  26662. S: 0x0053,
  26663. SF010000: 0x250C,
  26664. SF020000: 0x2514,
  26665. SF030000: 0x2510,
  26666. SF040000: 0x2518,
  26667. SF050000: 0x253C,
  26668. SF060000: 0x252C,
  26669. SF070000: 0x2534,
  26670. SF080000: 0x251C,
  26671. SF090000: 0x2524,
  26672. SF100000: 0x2500,
  26673. SF110000: 0x2502,
  26674. SF190000: 0x2561,
  26675. SF200000: 0x2562,
  26676. SF210000: 0x2556,
  26677. SF220000: 0x2555,
  26678. SF230000: 0x2563,
  26679. SF240000: 0x2551,
  26680. SF250000: 0x2557,
  26681. SF260000: 0x255D,
  26682. SF270000: 0x255C,
  26683. SF280000: 0x255B,
  26684. SF360000: 0x255E,
  26685. SF370000: 0x255F,
  26686. SF380000: 0x255A,
  26687. SF390000: 0x2554,
  26688. SF400000: 0x2569,
  26689. SF410000: 0x2566,
  26690. SF420000: 0x2560,
  26691. SF430000: 0x2550,
  26692. SF440000: 0x256C,
  26693. SF450000: 0x2567,
  26694. SF460000: 0x2568,
  26695. SF470000: 0x2564,
  26696. SF480000: 0x2565,
  26697. SF490000: 0x2559,
  26698. SF500000: 0x2558,
  26699. SF510000: 0x2552,
  26700. SF520000: 0x2553,
  26701. SF530000: 0x256B,
  26702. SF540000: 0x256A,
  26703. Sacute: 0x015A,
  26704. Sacutedotaccent: 0x1E64,
  26705. Sampigreek: 0x03E0,
  26706. Scaron: 0x0160,
  26707. Scarondotaccent: 0x1E66,
  26708. Scaronsmall: 0xF6FD,
  26709. Scedilla: 0x015E,
  26710. Schwa: 0x018F,
  26711. Schwacyrillic: 0x04D8,
  26712. Schwadieresiscyrillic: 0x04DA,
  26713. Scircle: 0x24C8,
  26714. Scircumflex: 0x015C,
  26715. Scommaaccent: 0x0218,
  26716. Sdotaccent: 0x1E60,
  26717. Sdotbelow: 0x1E62,
  26718. Sdotbelowdotaccent: 0x1E68,
  26719. Seharmenian: 0x054D,
  26720. Sevenroman: 0x2166,
  26721. Shaarmenian: 0x0547,
  26722. Shacyrillic: 0x0428,
  26723. Shchacyrillic: 0x0429,
  26724. Sheicoptic: 0x03E2,
  26725. Shhacyrillic: 0x04BA,
  26726. Shimacoptic: 0x03EC,
  26727. Sigma: 0x03A3,
  26728. Sixroman: 0x2165,
  26729. Smonospace: 0xFF33,
  26730. Softsigncyrillic: 0x042C,
  26731. Ssmall: 0xF773,
  26732. Stigmagreek: 0x03DA,
  26733. T: 0x0054,
  26734. Tau: 0x03A4,
  26735. Tbar: 0x0166,
  26736. Tcaron: 0x0164,
  26737. Tcedilla: 0x0162,
  26738. Tcircle: 0x24C9,
  26739. Tcircumflexbelow: 0x1E70,
  26740. Tcommaaccent: 0x0162,
  26741. Tdotaccent: 0x1E6A,
  26742. Tdotbelow: 0x1E6C,
  26743. Tecyrillic: 0x0422,
  26744. Tedescendercyrillic: 0x04AC,
  26745. Tenroman: 0x2169,
  26746. Tetsecyrillic: 0x04B4,
  26747. Theta: 0x0398,
  26748. Thook: 0x01AC,
  26749. Thorn: 0x00DE,
  26750. Thornsmall: 0xF7FE,
  26751. Threeroman: 0x2162,
  26752. Tildesmall: 0xF6FE,
  26753. Tiwnarmenian: 0x054F,
  26754. Tlinebelow: 0x1E6E,
  26755. Tmonospace: 0xFF34,
  26756. Toarmenian: 0x0539,
  26757. Tonefive: 0x01BC,
  26758. Tonesix: 0x0184,
  26759. Tonetwo: 0x01A7,
  26760. Tretroflexhook: 0x01AE,
  26761. Tsecyrillic: 0x0426,
  26762. Tshecyrillic: 0x040B,
  26763. Tsmall: 0xF774,
  26764. Twelveroman: 0x216B,
  26765. Tworoman: 0x2161,
  26766. U: 0x0055,
  26767. Uacute: 0x00DA,
  26768. Uacutesmall: 0xF7FA,
  26769. Ubreve: 0x016C,
  26770. Ucaron: 0x01D3,
  26771. Ucircle: 0x24CA,
  26772. Ucircumflex: 0x00DB,
  26773. Ucircumflexbelow: 0x1E76,
  26774. Ucircumflexsmall: 0xF7FB,
  26775. Ucyrillic: 0x0423,
  26776. Udblacute: 0x0170,
  26777. Udblgrave: 0x0214,
  26778. Udieresis: 0x00DC,
  26779. Udieresisacute: 0x01D7,
  26780. Udieresisbelow: 0x1E72,
  26781. Udieresiscaron: 0x01D9,
  26782. Udieresiscyrillic: 0x04F0,
  26783. Udieresisgrave: 0x01DB,
  26784. Udieresismacron: 0x01D5,
  26785. Udieresissmall: 0xF7FC,
  26786. Udotbelow: 0x1EE4,
  26787. Ugrave: 0x00D9,
  26788. Ugravesmall: 0xF7F9,
  26789. Uhookabove: 0x1EE6,
  26790. Uhorn: 0x01AF,
  26791. Uhornacute: 0x1EE8,
  26792. Uhorndotbelow: 0x1EF0,
  26793. Uhorngrave: 0x1EEA,
  26794. Uhornhookabove: 0x1EEC,
  26795. Uhorntilde: 0x1EEE,
  26796. Uhungarumlaut: 0x0170,
  26797. Uhungarumlautcyrillic: 0x04F2,
  26798. Uinvertedbreve: 0x0216,
  26799. Ukcyrillic: 0x0478,
  26800. Umacron: 0x016A,
  26801. Umacroncyrillic: 0x04EE,
  26802. Umacrondieresis: 0x1E7A,
  26803. Umonospace: 0xFF35,
  26804. Uogonek: 0x0172,
  26805. Upsilon: 0x03A5,
  26806. Upsilon1: 0x03D2,
  26807. Upsilonacutehooksymbolgreek: 0x03D3,
  26808. Upsilonafrican: 0x01B1,
  26809. Upsilondieresis: 0x03AB,
  26810. Upsilondieresishooksymbolgreek: 0x03D4,
  26811. Upsilonhooksymbol: 0x03D2,
  26812. Upsilontonos: 0x038E,
  26813. Uring: 0x016E,
  26814. Ushortcyrillic: 0x040E,
  26815. Usmall: 0xF775,
  26816. Ustraightcyrillic: 0x04AE,
  26817. Ustraightstrokecyrillic: 0x04B0,
  26818. Utilde: 0x0168,
  26819. Utildeacute: 0x1E78,
  26820. Utildebelow: 0x1E74,
  26821. V: 0x0056,
  26822. Vcircle: 0x24CB,
  26823. Vdotbelow: 0x1E7E,
  26824. Vecyrillic: 0x0412,
  26825. Vewarmenian: 0x054E,
  26826. Vhook: 0x01B2,
  26827. Vmonospace: 0xFF36,
  26828. Voarmenian: 0x0548,
  26829. Vsmall: 0xF776,
  26830. Vtilde: 0x1E7C,
  26831. W: 0x0057,
  26832. Wacute: 0x1E82,
  26833. Wcircle: 0x24CC,
  26834. Wcircumflex: 0x0174,
  26835. Wdieresis: 0x1E84,
  26836. Wdotaccent: 0x1E86,
  26837. Wdotbelow: 0x1E88,
  26838. Wgrave: 0x1E80,
  26839. Wmonospace: 0xFF37,
  26840. Wsmall: 0xF777,
  26841. X: 0x0058,
  26842. Xcircle: 0x24CD,
  26843. Xdieresis: 0x1E8C,
  26844. Xdotaccent: 0x1E8A,
  26845. Xeharmenian: 0x053D,
  26846. Xi: 0x039E,
  26847. Xmonospace: 0xFF38,
  26848. Xsmall: 0xF778,
  26849. Y: 0x0059,
  26850. Yacute: 0x00DD,
  26851. Yacutesmall: 0xF7FD,
  26852. Yatcyrillic: 0x0462,
  26853. Ycircle: 0x24CE,
  26854. Ycircumflex: 0x0176,
  26855. Ydieresis: 0x0178,
  26856. Ydieresissmall: 0xF7FF,
  26857. Ydotaccent: 0x1E8E,
  26858. Ydotbelow: 0x1EF4,
  26859. Yericyrillic: 0x042B,
  26860. Yerudieresiscyrillic: 0x04F8,
  26861. Ygrave: 0x1EF2,
  26862. Yhook: 0x01B3,
  26863. Yhookabove: 0x1EF6,
  26864. Yiarmenian: 0x0545,
  26865. Yicyrillic: 0x0407,
  26866. Yiwnarmenian: 0x0552,
  26867. Ymonospace: 0xFF39,
  26868. Ysmall: 0xF779,
  26869. Ytilde: 0x1EF8,
  26870. Yusbigcyrillic: 0x046A,
  26871. Yusbigiotifiedcyrillic: 0x046C,
  26872. Yuslittlecyrillic: 0x0466,
  26873. Yuslittleiotifiedcyrillic: 0x0468,
  26874. Z: 0x005A,
  26875. Zaarmenian: 0x0536,
  26876. Zacute: 0x0179,
  26877. Zcaron: 0x017D,
  26878. Zcaronsmall: 0xF6FF,
  26879. Zcircle: 0x24CF,
  26880. Zcircumflex: 0x1E90,
  26881. Zdot: 0x017B,
  26882. Zdotaccent: 0x017B,
  26883. Zdotbelow: 0x1E92,
  26884. Zecyrillic: 0x0417,
  26885. Zedescendercyrillic: 0x0498,
  26886. Zedieresiscyrillic: 0x04DE,
  26887. Zeta: 0x0396,
  26888. Zhearmenian: 0x053A,
  26889. Zhebrevecyrillic: 0x04C1,
  26890. Zhecyrillic: 0x0416,
  26891. Zhedescendercyrillic: 0x0496,
  26892. Zhedieresiscyrillic: 0x04DC,
  26893. Zlinebelow: 0x1E94,
  26894. Zmonospace: 0xFF3A,
  26895. Zsmall: 0xF77A,
  26896. Zstroke: 0x01B5,
  26897. a: 0x0061,
  26898. aabengali: 0x0986,
  26899. aacute: 0x00E1,
  26900. aadeva: 0x0906,
  26901. aagujarati: 0x0A86,
  26902. aagurmukhi: 0x0A06,
  26903. aamatragurmukhi: 0x0A3E,
  26904. aarusquare: 0x3303,
  26905. aavowelsignbengali: 0x09BE,
  26906. aavowelsigndeva: 0x093E,
  26907. aavowelsigngujarati: 0x0ABE,
  26908. abbreviationmarkarmenian: 0x055F,
  26909. abbreviationsigndeva: 0x0970,
  26910. abengali: 0x0985,
  26911. abopomofo: 0x311A,
  26912. abreve: 0x0103,
  26913. abreveacute: 0x1EAF,
  26914. abrevecyrillic: 0x04D1,
  26915. abrevedotbelow: 0x1EB7,
  26916. abrevegrave: 0x1EB1,
  26917. abrevehookabove: 0x1EB3,
  26918. abrevetilde: 0x1EB5,
  26919. acaron: 0x01CE,
  26920. acircle: 0x24D0,
  26921. acircumflex: 0x00E2,
  26922. acircumflexacute: 0x1EA5,
  26923. acircumflexdotbelow: 0x1EAD,
  26924. acircumflexgrave: 0x1EA7,
  26925. acircumflexhookabove: 0x1EA9,
  26926. acircumflextilde: 0x1EAB,
  26927. acute: 0x00B4,
  26928. acutebelowcmb: 0x0317,
  26929. acutecmb: 0x0301,
  26930. acutecomb: 0x0301,
  26931. acutedeva: 0x0954,
  26932. acutelowmod: 0x02CF,
  26933. acutetonecmb: 0x0341,
  26934. acyrillic: 0x0430,
  26935. adblgrave: 0x0201,
  26936. addakgurmukhi: 0x0A71,
  26937. adeva: 0x0905,
  26938. adieresis: 0x00E4,
  26939. adieresiscyrillic: 0x04D3,
  26940. adieresismacron: 0x01DF,
  26941. adotbelow: 0x1EA1,
  26942. adotmacron: 0x01E1,
  26943. ae: 0x00E6,
  26944. aeacute: 0x01FD,
  26945. aekorean: 0x3150,
  26946. aemacron: 0x01E3,
  26947. afii00208: 0x2015,
  26948. afii08941: 0x20A4,
  26949. afii10017: 0x0410,
  26950. afii10018: 0x0411,
  26951. afii10019: 0x0412,
  26952. afii10020: 0x0413,
  26953. afii10021: 0x0414,
  26954. afii10022: 0x0415,
  26955. afii10023: 0x0401,
  26956. afii10024: 0x0416,
  26957. afii10025: 0x0417,
  26958. afii10026: 0x0418,
  26959. afii10027: 0x0419,
  26960. afii10028: 0x041A,
  26961. afii10029: 0x041B,
  26962. afii10030: 0x041C,
  26963. afii10031: 0x041D,
  26964. afii10032: 0x041E,
  26965. afii10033: 0x041F,
  26966. afii10034: 0x0420,
  26967. afii10035: 0x0421,
  26968. afii10036: 0x0422,
  26969. afii10037: 0x0423,
  26970. afii10038: 0x0424,
  26971. afii10039: 0x0425,
  26972. afii10040: 0x0426,
  26973. afii10041: 0x0427,
  26974. afii10042: 0x0428,
  26975. afii10043: 0x0429,
  26976. afii10044: 0x042A,
  26977. afii10045: 0x042B,
  26978. afii10046: 0x042C,
  26979. afii10047: 0x042D,
  26980. afii10048: 0x042E,
  26981. afii10049: 0x042F,
  26982. afii10050: 0x0490,
  26983. afii10051: 0x0402,
  26984. afii10052: 0x0403,
  26985. afii10053: 0x0404,
  26986. afii10054: 0x0405,
  26987. afii10055: 0x0406,
  26988. afii10056: 0x0407,
  26989. afii10057: 0x0408,
  26990. afii10058: 0x0409,
  26991. afii10059: 0x040A,
  26992. afii10060: 0x040B,
  26993. afii10061: 0x040C,
  26994. afii10062: 0x040E,
  26995. afii10063: 0xF6C4,
  26996. afii10064: 0xF6C5,
  26997. afii10065: 0x0430,
  26998. afii10066: 0x0431,
  26999. afii10067: 0x0432,
  27000. afii10068: 0x0433,
  27001. afii10069: 0x0434,
  27002. afii10070: 0x0435,
  27003. afii10071: 0x0451,
  27004. afii10072: 0x0436,
  27005. afii10073: 0x0437,
  27006. afii10074: 0x0438,
  27007. afii10075: 0x0439,
  27008. afii10076: 0x043A,
  27009. afii10077: 0x043B,
  27010. afii10078: 0x043C,
  27011. afii10079: 0x043D,
  27012. afii10080: 0x043E,
  27013. afii10081: 0x043F,
  27014. afii10082: 0x0440,
  27015. afii10083: 0x0441,
  27016. afii10084: 0x0442,
  27017. afii10085: 0x0443,
  27018. afii10086: 0x0444,
  27019. afii10087: 0x0445,
  27020. afii10088: 0x0446,
  27021. afii10089: 0x0447,
  27022. afii10090: 0x0448,
  27023. afii10091: 0x0449,
  27024. afii10092: 0x044A,
  27025. afii10093: 0x044B,
  27026. afii10094: 0x044C,
  27027. afii10095: 0x044D,
  27028. afii10096: 0x044E,
  27029. afii10097: 0x044F,
  27030. afii10098: 0x0491,
  27031. afii10099: 0x0452,
  27032. afii10100: 0x0453,
  27033. afii10101: 0x0454,
  27034. afii10102: 0x0455,
  27035. afii10103: 0x0456,
  27036. afii10104: 0x0457,
  27037. afii10105: 0x0458,
  27038. afii10106: 0x0459,
  27039. afii10107: 0x045A,
  27040. afii10108: 0x045B,
  27041. afii10109: 0x045C,
  27042. afii10110: 0x045E,
  27043. afii10145: 0x040F,
  27044. afii10146: 0x0462,
  27045. afii10147: 0x0472,
  27046. afii10148: 0x0474,
  27047. afii10192: 0xF6C6,
  27048. afii10193: 0x045F,
  27049. afii10194: 0x0463,
  27050. afii10195: 0x0473,
  27051. afii10196: 0x0475,
  27052. afii10831: 0xF6C7,
  27053. afii10832: 0xF6C8,
  27054. afii10846: 0x04D9,
  27055. afii299: 0x200E,
  27056. afii300: 0x200F,
  27057. afii301: 0x200D,
  27058. afii57381: 0x066A,
  27059. afii57388: 0x060C,
  27060. afii57392: 0x0660,
  27061. afii57393: 0x0661,
  27062. afii57394: 0x0662,
  27063. afii57395: 0x0663,
  27064. afii57396: 0x0664,
  27065. afii57397: 0x0665,
  27066. afii57398: 0x0666,
  27067. afii57399: 0x0667,
  27068. afii57400: 0x0668,
  27069. afii57401: 0x0669,
  27070. afii57403: 0x061B,
  27071. afii57407: 0x061F,
  27072. afii57409: 0x0621,
  27073. afii57410: 0x0622,
  27074. afii57411: 0x0623,
  27075. afii57412: 0x0624,
  27076. afii57413: 0x0625,
  27077. afii57414: 0x0626,
  27078. afii57415: 0x0627,
  27079. afii57416: 0x0628,
  27080. afii57417: 0x0629,
  27081. afii57418: 0x062A,
  27082. afii57419: 0x062B,
  27083. afii57420: 0x062C,
  27084. afii57421: 0x062D,
  27085. afii57422: 0x062E,
  27086. afii57423: 0x062F,
  27087. afii57424: 0x0630,
  27088. afii57425: 0x0631,
  27089. afii57426: 0x0632,
  27090. afii57427: 0x0633,
  27091. afii57428: 0x0634,
  27092. afii57429: 0x0635,
  27093. afii57430: 0x0636,
  27094. afii57431: 0x0637,
  27095. afii57432: 0x0638,
  27096. afii57433: 0x0639,
  27097. afii57434: 0x063A,
  27098. afii57440: 0x0640,
  27099. afii57441: 0x0641,
  27100. afii57442: 0x0642,
  27101. afii57443: 0x0643,
  27102. afii57444: 0x0644,
  27103. afii57445: 0x0645,
  27104. afii57446: 0x0646,
  27105. afii57448: 0x0648,
  27106. afii57449: 0x0649,
  27107. afii57450: 0x064A,
  27108. afii57451: 0x064B,
  27109. afii57452: 0x064C,
  27110. afii57453: 0x064D,
  27111. afii57454: 0x064E,
  27112. afii57455: 0x064F,
  27113. afii57456: 0x0650,
  27114. afii57457: 0x0651,
  27115. afii57458: 0x0652,
  27116. afii57470: 0x0647,
  27117. afii57505: 0x06A4,
  27118. afii57506: 0x067E,
  27119. afii57507: 0x0686,
  27120. afii57508: 0x0698,
  27121. afii57509: 0x06AF,
  27122. afii57511: 0x0679,
  27123. afii57512: 0x0688,
  27124. afii57513: 0x0691,
  27125. afii57514: 0x06BA,
  27126. afii57519: 0x06D2,
  27127. afii57534: 0x06D5,
  27128. afii57636: 0x20AA,
  27129. afii57645: 0x05BE,
  27130. afii57658: 0x05C3,
  27131. afii57664: 0x05D0,
  27132. afii57665: 0x05D1,
  27133. afii57666: 0x05D2,
  27134. afii57667: 0x05D3,
  27135. afii57668: 0x05D4,
  27136. afii57669: 0x05D5,
  27137. afii57670: 0x05D6,
  27138. afii57671: 0x05D7,
  27139. afii57672: 0x05D8,
  27140. afii57673: 0x05D9,
  27141. afii57674: 0x05DA,
  27142. afii57675: 0x05DB,
  27143. afii57676: 0x05DC,
  27144. afii57677: 0x05DD,
  27145. afii57678: 0x05DE,
  27146. afii57679: 0x05DF,
  27147. afii57680: 0x05E0,
  27148. afii57681: 0x05E1,
  27149. afii57682: 0x05E2,
  27150. afii57683: 0x05E3,
  27151. afii57684: 0x05E4,
  27152. afii57685: 0x05E5,
  27153. afii57686: 0x05E6,
  27154. afii57687: 0x05E7,
  27155. afii57688: 0x05E8,
  27156. afii57689: 0x05E9,
  27157. afii57690: 0x05EA,
  27158. afii57694: 0xFB2A,
  27159. afii57695: 0xFB2B,
  27160. afii57700: 0xFB4B,
  27161. afii57705: 0xFB1F,
  27162. afii57716: 0x05F0,
  27163. afii57717: 0x05F1,
  27164. afii57718: 0x05F2,
  27165. afii57723: 0xFB35,
  27166. afii57793: 0x05B4,
  27167. afii57794: 0x05B5,
  27168. afii57795: 0x05B6,
  27169. afii57796: 0x05BB,
  27170. afii57797: 0x05B8,
  27171. afii57798: 0x05B7,
  27172. afii57799: 0x05B0,
  27173. afii57800: 0x05B2,
  27174. afii57801: 0x05B1,
  27175. afii57802: 0x05B3,
  27176. afii57803: 0x05C2,
  27177. afii57804: 0x05C1,
  27178. afii57806: 0x05B9,
  27179. afii57807: 0x05BC,
  27180. afii57839: 0x05BD,
  27181. afii57841: 0x05BF,
  27182. afii57842: 0x05C0,
  27183. afii57929: 0x02BC,
  27184. afii61248: 0x2105,
  27185. afii61289: 0x2113,
  27186. afii61352: 0x2116,
  27187. afii61573: 0x202C,
  27188. afii61574: 0x202D,
  27189. afii61575: 0x202E,
  27190. afii61664: 0x200C,
  27191. afii63167: 0x066D,
  27192. afii64937: 0x02BD,
  27193. agrave: 0x00E0,
  27194. agujarati: 0x0A85,
  27195. agurmukhi: 0x0A05,
  27196. ahiragana: 0x3042,
  27197. ahookabove: 0x1EA3,
  27198. aibengali: 0x0990,
  27199. aibopomofo: 0x311E,
  27200. aideva: 0x0910,
  27201. aiecyrillic: 0x04D5,
  27202. aigujarati: 0x0A90,
  27203. aigurmukhi: 0x0A10,
  27204. aimatragurmukhi: 0x0A48,
  27205. ainarabic: 0x0639,
  27206. ainfinalarabic: 0xFECA,
  27207. aininitialarabic: 0xFECB,
  27208. ainmedialarabic: 0xFECC,
  27209. ainvertedbreve: 0x0203,
  27210. aivowelsignbengali: 0x09C8,
  27211. aivowelsigndeva: 0x0948,
  27212. aivowelsigngujarati: 0x0AC8,
  27213. akatakana: 0x30A2,
  27214. akatakanahalfwidth: 0xFF71,
  27215. akorean: 0x314F,
  27216. alef: 0x05D0,
  27217. alefarabic: 0x0627,
  27218. alefdageshhebrew: 0xFB30,
  27219. aleffinalarabic: 0xFE8E,
  27220. alefhamzaabovearabic: 0x0623,
  27221. alefhamzaabovefinalarabic: 0xFE84,
  27222. alefhamzabelowarabic: 0x0625,
  27223. alefhamzabelowfinalarabic: 0xFE88,
  27224. alefhebrew: 0x05D0,
  27225. aleflamedhebrew: 0xFB4F,
  27226. alefmaddaabovearabic: 0x0622,
  27227. alefmaddaabovefinalarabic: 0xFE82,
  27228. alefmaksuraarabic: 0x0649,
  27229. alefmaksurafinalarabic: 0xFEF0,
  27230. alefmaksurainitialarabic: 0xFEF3,
  27231. alefmaksuramedialarabic: 0xFEF4,
  27232. alefpatahhebrew: 0xFB2E,
  27233. alefqamatshebrew: 0xFB2F,
  27234. aleph: 0x2135,
  27235. allequal: 0x224C,
  27236. alpha: 0x03B1,
  27237. alphatonos: 0x03AC,
  27238. amacron: 0x0101,
  27239. amonospace: 0xFF41,
  27240. ampersand: 0x0026,
  27241. ampersandmonospace: 0xFF06,
  27242. ampersandsmall: 0xF726,
  27243. amsquare: 0x33C2,
  27244. anbopomofo: 0x3122,
  27245. angbopomofo: 0x3124,
  27246. angbracketleft: 0x3008, // This glyph is missing from Adobe's original list.
  27247. angbracketright: 0x3009, // This glyph is missing from Adobe's original list.
  27248. angkhankhuthai: 0x0E5A,
  27249. angle: 0x2220,
  27250. anglebracketleft: 0x3008,
  27251. anglebracketleftvertical: 0xFE3F,
  27252. anglebracketright: 0x3009,
  27253. anglebracketrightvertical: 0xFE40,
  27254. angleleft: 0x2329,
  27255. angleright: 0x232A,
  27256. angstrom: 0x212B,
  27257. anoteleia: 0x0387,
  27258. anudattadeva: 0x0952,
  27259. anusvarabengali: 0x0982,
  27260. anusvaradeva: 0x0902,
  27261. anusvaragujarati: 0x0A82,
  27262. aogonek: 0x0105,
  27263. apaatosquare: 0x3300,
  27264. aparen: 0x249C,
  27265. apostrophearmenian: 0x055A,
  27266. apostrophemod: 0x02BC,
  27267. apple: 0xF8FF,
  27268. approaches: 0x2250,
  27269. approxequal: 0x2248,
  27270. approxequalorimage: 0x2252,
  27271. approximatelyequal: 0x2245,
  27272. araeaekorean: 0x318E,
  27273. araeakorean: 0x318D,
  27274. arc: 0x2312,
  27275. arighthalfring: 0x1E9A,
  27276. aring: 0x00E5,
  27277. aringacute: 0x01FB,
  27278. aringbelow: 0x1E01,
  27279. arrowboth: 0x2194,
  27280. arrowdashdown: 0x21E3,
  27281. arrowdashleft: 0x21E0,
  27282. arrowdashright: 0x21E2,
  27283. arrowdashup: 0x21E1,
  27284. arrowdblboth: 0x21D4,
  27285. arrowdbldown: 0x21D3,
  27286. arrowdblleft: 0x21D0,
  27287. arrowdblright: 0x21D2,
  27288. arrowdblup: 0x21D1,
  27289. arrowdown: 0x2193,
  27290. arrowdownleft: 0x2199,
  27291. arrowdownright: 0x2198,
  27292. arrowdownwhite: 0x21E9,
  27293. arrowheaddownmod: 0x02C5,
  27294. arrowheadleftmod: 0x02C2,
  27295. arrowheadrightmod: 0x02C3,
  27296. arrowheadupmod: 0x02C4,
  27297. arrowhorizex: 0xF8E7,
  27298. arrowleft: 0x2190,
  27299. arrowleftdbl: 0x21D0,
  27300. arrowleftdblstroke: 0x21CD,
  27301. arrowleftoverright: 0x21C6,
  27302. arrowleftwhite: 0x21E6,
  27303. arrowright: 0x2192,
  27304. arrowrightdblstroke: 0x21CF,
  27305. arrowrightheavy: 0x279E,
  27306. arrowrightoverleft: 0x21C4,
  27307. arrowrightwhite: 0x21E8,
  27308. arrowtableft: 0x21E4,
  27309. arrowtabright: 0x21E5,
  27310. arrowup: 0x2191,
  27311. arrowupdn: 0x2195,
  27312. arrowupdnbse: 0x21A8,
  27313. arrowupdownbase: 0x21A8,
  27314. arrowupleft: 0x2196,
  27315. arrowupleftofdown: 0x21C5,
  27316. arrowupright: 0x2197,
  27317. arrowupwhite: 0x21E7,
  27318. arrowvertex: 0xF8E6,
  27319. asciicircum: 0x005E,
  27320. asciicircummonospace: 0xFF3E,
  27321. asciitilde: 0x007E,
  27322. asciitildemonospace: 0xFF5E,
  27323. ascript: 0x0251,
  27324. ascriptturned: 0x0252,
  27325. asmallhiragana: 0x3041,
  27326. asmallkatakana: 0x30A1,
  27327. asmallkatakanahalfwidth: 0xFF67,
  27328. asterisk: 0x002A,
  27329. asteriskaltonearabic: 0x066D,
  27330. asteriskarabic: 0x066D,
  27331. asteriskmath: 0x2217,
  27332. asteriskmonospace: 0xFF0A,
  27333. asterisksmall: 0xFE61,
  27334. asterism: 0x2042,
  27335. asuperior: 0xF6E9,
  27336. asymptoticallyequal: 0x2243,
  27337. at: 0x0040,
  27338. atilde: 0x00E3,
  27339. atmonospace: 0xFF20,
  27340. atsmall: 0xFE6B,
  27341. aturned: 0x0250,
  27342. aubengali: 0x0994,
  27343. aubopomofo: 0x3120,
  27344. audeva: 0x0914,
  27345. augujarati: 0x0A94,
  27346. augurmukhi: 0x0A14,
  27347. aulengthmarkbengali: 0x09D7,
  27348. aumatragurmukhi: 0x0A4C,
  27349. auvowelsignbengali: 0x09CC,
  27350. auvowelsigndeva: 0x094C,
  27351. auvowelsigngujarati: 0x0ACC,
  27352. avagrahadeva: 0x093D,
  27353. aybarmenian: 0x0561,
  27354. ayin: 0x05E2,
  27355. ayinaltonehebrew: 0xFB20,
  27356. ayinhebrew: 0x05E2,
  27357. b: 0x0062,
  27358. babengali: 0x09AC,
  27359. backslash: 0x005C,
  27360. backslashmonospace: 0xFF3C,
  27361. badeva: 0x092C,
  27362. bagujarati: 0x0AAC,
  27363. bagurmukhi: 0x0A2C,
  27364. bahiragana: 0x3070,
  27365. bahtthai: 0x0E3F,
  27366. bakatakana: 0x30D0,
  27367. bar: 0x007C,
  27368. barmonospace: 0xFF5C,
  27369. bbopomofo: 0x3105,
  27370. bcircle: 0x24D1,
  27371. bdotaccent: 0x1E03,
  27372. bdotbelow: 0x1E05,
  27373. beamedsixteenthnotes: 0x266C,
  27374. because: 0x2235,
  27375. becyrillic: 0x0431,
  27376. beharabic: 0x0628,
  27377. behfinalarabic: 0xFE90,
  27378. behinitialarabic: 0xFE91,
  27379. behiragana: 0x3079,
  27380. behmedialarabic: 0xFE92,
  27381. behmeeminitialarabic: 0xFC9F,
  27382. behmeemisolatedarabic: 0xFC08,
  27383. behnoonfinalarabic: 0xFC6D,
  27384. bekatakana: 0x30D9,
  27385. benarmenian: 0x0562,
  27386. bet: 0x05D1,
  27387. beta: 0x03B2,
  27388. betasymbolgreek: 0x03D0,
  27389. betdagesh: 0xFB31,
  27390. betdageshhebrew: 0xFB31,
  27391. bethebrew: 0x05D1,
  27392. betrafehebrew: 0xFB4C,
  27393. bhabengali: 0x09AD,
  27394. bhadeva: 0x092D,
  27395. bhagujarati: 0x0AAD,
  27396. bhagurmukhi: 0x0A2D,
  27397. bhook: 0x0253,
  27398. bihiragana: 0x3073,
  27399. bikatakana: 0x30D3,
  27400. bilabialclick: 0x0298,
  27401. bindigurmukhi: 0x0A02,
  27402. birusquare: 0x3331,
  27403. blackcircle: 0x25CF,
  27404. blackdiamond: 0x25C6,
  27405. blackdownpointingtriangle: 0x25BC,
  27406. blackleftpointingpointer: 0x25C4,
  27407. blackleftpointingtriangle: 0x25C0,
  27408. blacklenticularbracketleft: 0x3010,
  27409. blacklenticularbracketleftvertical: 0xFE3B,
  27410. blacklenticularbracketright: 0x3011,
  27411. blacklenticularbracketrightvertical: 0xFE3C,
  27412. blacklowerlefttriangle: 0x25E3,
  27413. blacklowerrighttriangle: 0x25E2,
  27414. blackrectangle: 0x25AC,
  27415. blackrightpointingpointer: 0x25BA,
  27416. blackrightpointingtriangle: 0x25B6,
  27417. blacksmallsquare: 0x25AA,
  27418. blacksmilingface: 0x263B,
  27419. blacksquare: 0x25A0,
  27420. blackstar: 0x2605,
  27421. blackupperlefttriangle: 0x25E4,
  27422. blackupperrighttriangle: 0x25E5,
  27423. blackuppointingsmalltriangle: 0x25B4,
  27424. blackuppointingtriangle: 0x25B2,
  27425. blank: 0x2423,
  27426. blinebelow: 0x1E07,
  27427. block: 0x2588,
  27428. bmonospace: 0xFF42,
  27429. bobaimaithai: 0x0E1A,
  27430. bohiragana: 0x307C,
  27431. bokatakana: 0x30DC,
  27432. bparen: 0x249D,
  27433. bqsquare: 0x33C3,
  27434. braceex: 0xF8F4,
  27435. braceleft: 0x007B,
  27436. braceleftbt: 0xF8F3,
  27437. braceleftmid: 0xF8F2,
  27438. braceleftmonospace: 0xFF5B,
  27439. braceleftsmall: 0xFE5B,
  27440. bracelefttp: 0xF8F1,
  27441. braceleftvertical: 0xFE37,
  27442. braceright: 0x007D,
  27443. bracerightbt: 0xF8FE,
  27444. bracerightmid: 0xF8FD,
  27445. bracerightmonospace: 0xFF5D,
  27446. bracerightsmall: 0xFE5C,
  27447. bracerighttp: 0xF8FC,
  27448. bracerightvertical: 0xFE38,
  27449. bracketleft: 0x005B,
  27450. bracketleftbt: 0xF8F0,
  27451. bracketleftex: 0xF8EF,
  27452. bracketleftmonospace: 0xFF3B,
  27453. bracketlefttp: 0xF8EE,
  27454. bracketright: 0x005D,
  27455. bracketrightbt: 0xF8FB,
  27456. bracketrightex: 0xF8FA,
  27457. bracketrightmonospace: 0xFF3D,
  27458. bracketrighttp: 0xF8F9,
  27459. breve: 0x02D8,
  27460. brevebelowcmb: 0x032E,
  27461. brevecmb: 0x0306,
  27462. breveinvertedbelowcmb: 0x032F,
  27463. breveinvertedcmb: 0x0311,
  27464. breveinverteddoublecmb: 0x0361,
  27465. bridgebelowcmb: 0x032A,
  27466. bridgeinvertedbelowcmb: 0x033A,
  27467. brokenbar: 0x00A6,
  27468. bstroke: 0x0180,
  27469. bsuperior: 0xF6EA,
  27470. btopbar: 0x0183,
  27471. buhiragana: 0x3076,
  27472. bukatakana: 0x30D6,
  27473. bullet: 0x2022,
  27474. bulletinverse: 0x25D8,
  27475. bulletoperator: 0x2219,
  27476. bullseye: 0x25CE,
  27477. c: 0x0063,
  27478. caarmenian: 0x056E,
  27479. cabengali: 0x099A,
  27480. cacute: 0x0107,
  27481. cadeva: 0x091A,
  27482. cagujarati: 0x0A9A,
  27483. cagurmukhi: 0x0A1A,
  27484. calsquare: 0x3388,
  27485. candrabindubengali: 0x0981,
  27486. candrabinducmb: 0x0310,
  27487. candrabindudeva: 0x0901,
  27488. candrabindugujarati: 0x0A81,
  27489. capslock: 0x21EA,
  27490. careof: 0x2105,
  27491. caron: 0x02C7,
  27492. caronbelowcmb: 0x032C,
  27493. caroncmb: 0x030C,
  27494. carriagereturn: 0x21B5,
  27495. cbopomofo: 0x3118,
  27496. ccaron: 0x010D,
  27497. ccedilla: 0x00E7,
  27498. ccedillaacute: 0x1E09,
  27499. ccircle: 0x24D2,
  27500. ccircumflex: 0x0109,
  27501. ccurl: 0x0255,
  27502. cdot: 0x010B,
  27503. cdotaccent: 0x010B,
  27504. cdsquare: 0x33C5,
  27505. cedilla: 0x00B8,
  27506. cedillacmb: 0x0327,
  27507. cent: 0x00A2,
  27508. centigrade: 0x2103,
  27509. centinferior: 0xF6DF,
  27510. centmonospace: 0xFFE0,
  27511. centoldstyle: 0xF7A2,
  27512. centsuperior: 0xF6E0,
  27513. chaarmenian: 0x0579,
  27514. chabengali: 0x099B,
  27515. chadeva: 0x091B,
  27516. chagujarati: 0x0A9B,
  27517. chagurmukhi: 0x0A1B,
  27518. chbopomofo: 0x3114,
  27519. cheabkhasiancyrillic: 0x04BD,
  27520. checkmark: 0x2713,
  27521. checyrillic: 0x0447,
  27522. chedescenderabkhasiancyrillic: 0x04BF,
  27523. chedescendercyrillic: 0x04B7,
  27524. chedieresiscyrillic: 0x04F5,
  27525. cheharmenian: 0x0573,
  27526. chekhakassiancyrillic: 0x04CC,
  27527. cheverticalstrokecyrillic: 0x04B9,
  27528. chi: 0x03C7,
  27529. chieuchacirclekorean: 0x3277,
  27530. chieuchaparenkorean: 0x3217,
  27531. chieuchcirclekorean: 0x3269,
  27532. chieuchkorean: 0x314A,
  27533. chieuchparenkorean: 0x3209,
  27534. chochangthai: 0x0E0A,
  27535. chochanthai: 0x0E08,
  27536. chochingthai: 0x0E09,
  27537. chochoethai: 0x0E0C,
  27538. chook: 0x0188,
  27539. cieucacirclekorean: 0x3276,
  27540. cieucaparenkorean: 0x3216,
  27541. cieuccirclekorean: 0x3268,
  27542. cieuckorean: 0x3148,
  27543. cieucparenkorean: 0x3208,
  27544. cieucuparenkorean: 0x321C,
  27545. circle: 0x25CB,
  27546. circlecopyrt: 0x00A9, // This glyph is missing from Adobe's original list.
  27547. circlemultiply: 0x2297,
  27548. circleot: 0x2299,
  27549. circleplus: 0x2295,
  27550. circlepostalmark: 0x3036,
  27551. circlewithlefthalfblack: 0x25D0,
  27552. circlewithrighthalfblack: 0x25D1,
  27553. circumflex: 0x02C6,
  27554. circumflexbelowcmb: 0x032D,
  27555. circumflexcmb: 0x0302,
  27556. clear: 0x2327,
  27557. clickalveolar: 0x01C2,
  27558. clickdental: 0x01C0,
  27559. clicklateral: 0x01C1,
  27560. clickretroflex: 0x01C3,
  27561. club: 0x2663,
  27562. clubsuitblack: 0x2663,
  27563. clubsuitwhite: 0x2667,
  27564. cmcubedsquare: 0x33A4,
  27565. cmonospace: 0xFF43,
  27566. cmsquaredsquare: 0x33A0,
  27567. coarmenian: 0x0581,
  27568. colon: 0x003A,
  27569. colonmonetary: 0x20A1,
  27570. colonmonospace: 0xFF1A,
  27571. colonsign: 0x20A1,
  27572. colonsmall: 0xFE55,
  27573. colontriangularhalfmod: 0x02D1,
  27574. colontriangularmod: 0x02D0,
  27575. comma: 0x002C,
  27576. commaabovecmb: 0x0313,
  27577. commaaboverightcmb: 0x0315,
  27578. commaaccent: 0xF6C3,
  27579. commaarabic: 0x060C,
  27580. commaarmenian: 0x055D,
  27581. commainferior: 0xF6E1,
  27582. commamonospace: 0xFF0C,
  27583. commareversedabovecmb: 0x0314,
  27584. commareversedmod: 0x02BD,
  27585. commasmall: 0xFE50,
  27586. commasuperior: 0xF6E2,
  27587. commaturnedabovecmb: 0x0312,
  27588. commaturnedmod: 0x02BB,
  27589. compass: 0x263C,
  27590. congruent: 0x2245,
  27591. contourintegral: 0x222E,
  27592. control: 0x2303,
  27593. controlACK: 0x0006,
  27594. controlBEL: 0x0007,
  27595. controlBS: 0x0008,
  27596. controlCAN: 0x0018,
  27597. controlCR: 0x000D,
  27598. controlDC1: 0x0011,
  27599. controlDC2: 0x0012,
  27600. controlDC3: 0x0013,
  27601. controlDC4: 0x0014,
  27602. controlDEL: 0x007F,
  27603. controlDLE: 0x0010,
  27604. controlEM: 0x0019,
  27605. controlENQ: 0x0005,
  27606. controlEOT: 0x0004,
  27607. controlESC: 0x001B,
  27608. controlETB: 0x0017,
  27609. controlETX: 0x0003,
  27610. controlFF: 0x000C,
  27611. controlFS: 0x001C,
  27612. controlGS: 0x001D,
  27613. controlHT: 0x0009,
  27614. controlLF: 0x000A,
  27615. controlNAK: 0x0015,
  27616. controlRS: 0x001E,
  27617. controlSI: 0x000F,
  27618. controlSO: 0x000E,
  27619. controlSOT: 0x0002,
  27620. controlSTX: 0x0001,
  27621. controlSUB: 0x001A,
  27622. controlSYN: 0x0016,
  27623. controlUS: 0x001F,
  27624. controlVT: 0x000B,
  27625. copyright: 0x00A9,
  27626. copyrightsans: 0xF8E9,
  27627. copyrightserif: 0xF6D9,
  27628. cornerbracketleft: 0x300C,
  27629. cornerbracketlefthalfwidth: 0xFF62,
  27630. cornerbracketleftvertical: 0xFE41,
  27631. cornerbracketright: 0x300D,
  27632. cornerbracketrighthalfwidth: 0xFF63,
  27633. cornerbracketrightvertical: 0xFE42,
  27634. corporationsquare: 0x337F,
  27635. cosquare: 0x33C7,
  27636. coverkgsquare: 0x33C6,
  27637. cparen: 0x249E,
  27638. cruzeiro: 0x20A2,
  27639. cstretched: 0x0297,
  27640. curlyand: 0x22CF,
  27641. curlyor: 0x22CE,
  27642. currency: 0x00A4,
  27643. cyrBreve: 0xF6D1,
  27644. cyrFlex: 0xF6D2,
  27645. cyrbreve: 0xF6D4,
  27646. cyrflex: 0xF6D5,
  27647. d: 0x0064,
  27648. daarmenian: 0x0564,
  27649. dabengali: 0x09A6,
  27650. dadarabic: 0x0636,
  27651. dadeva: 0x0926,
  27652. dadfinalarabic: 0xFEBE,
  27653. dadinitialarabic: 0xFEBF,
  27654. dadmedialarabic: 0xFEC0,
  27655. dagesh: 0x05BC,
  27656. dageshhebrew: 0x05BC,
  27657. dagger: 0x2020,
  27658. daggerdbl: 0x2021,
  27659. dagujarati: 0x0AA6,
  27660. dagurmukhi: 0x0A26,
  27661. dahiragana: 0x3060,
  27662. dakatakana: 0x30C0,
  27663. dalarabic: 0x062F,
  27664. dalet: 0x05D3,
  27665. daletdagesh: 0xFB33,
  27666. daletdageshhebrew: 0xFB33,
  27667. dalethebrew: 0x05D3,
  27668. dalfinalarabic: 0xFEAA,
  27669. dammaarabic: 0x064F,
  27670. dammalowarabic: 0x064F,
  27671. dammatanaltonearabic: 0x064C,
  27672. dammatanarabic: 0x064C,
  27673. danda: 0x0964,
  27674. dargahebrew: 0x05A7,
  27675. dargalefthebrew: 0x05A7,
  27676. dasiapneumatacyrilliccmb: 0x0485,
  27677. dblGrave: 0xF6D3,
  27678. dblanglebracketleft: 0x300A,
  27679. dblanglebracketleftvertical: 0xFE3D,
  27680. dblanglebracketright: 0x300B,
  27681. dblanglebracketrightvertical: 0xFE3E,
  27682. dblarchinvertedbelowcmb: 0x032B,
  27683. dblarrowleft: 0x21D4,
  27684. dblarrowright: 0x21D2,
  27685. dbldanda: 0x0965,
  27686. dblgrave: 0xF6D6,
  27687. dblgravecmb: 0x030F,
  27688. dblintegral: 0x222C,
  27689. dbllowline: 0x2017,
  27690. dbllowlinecmb: 0x0333,
  27691. dbloverlinecmb: 0x033F,
  27692. dblprimemod: 0x02BA,
  27693. dblverticalbar: 0x2016,
  27694. dblverticallineabovecmb: 0x030E,
  27695. dbopomofo: 0x3109,
  27696. dbsquare: 0x33C8,
  27697. dcaron: 0x010F,
  27698. dcedilla: 0x1E11,
  27699. dcircle: 0x24D3,
  27700. dcircumflexbelow: 0x1E13,
  27701. dcroat: 0x0111,
  27702. ddabengali: 0x09A1,
  27703. ddadeva: 0x0921,
  27704. ddagujarati: 0x0AA1,
  27705. ddagurmukhi: 0x0A21,
  27706. ddalarabic: 0x0688,
  27707. ddalfinalarabic: 0xFB89,
  27708. dddhadeva: 0x095C,
  27709. ddhabengali: 0x09A2,
  27710. ddhadeva: 0x0922,
  27711. ddhagujarati: 0x0AA2,
  27712. ddhagurmukhi: 0x0A22,
  27713. ddotaccent: 0x1E0B,
  27714. ddotbelow: 0x1E0D,
  27715. decimalseparatorarabic: 0x066B,
  27716. decimalseparatorpersian: 0x066B,
  27717. decyrillic: 0x0434,
  27718. degree: 0x00B0,
  27719. dehihebrew: 0x05AD,
  27720. dehiragana: 0x3067,
  27721. deicoptic: 0x03EF,
  27722. dekatakana: 0x30C7,
  27723. deleteleft: 0x232B,
  27724. deleteright: 0x2326,
  27725. delta: 0x03B4,
  27726. deltaturned: 0x018D,
  27727. denominatorminusonenumeratorbengali: 0x09F8,
  27728. dezh: 0x02A4,
  27729. dhabengali: 0x09A7,
  27730. dhadeva: 0x0927,
  27731. dhagujarati: 0x0AA7,
  27732. dhagurmukhi: 0x0A27,
  27733. dhook: 0x0257,
  27734. dialytikatonos: 0x0385,
  27735. dialytikatonoscmb: 0x0344,
  27736. diamond: 0x2666,
  27737. diamondsuitwhite: 0x2662,
  27738. dieresis: 0x00A8,
  27739. dieresisacute: 0xF6D7,
  27740. dieresisbelowcmb: 0x0324,
  27741. dieresiscmb: 0x0308,
  27742. dieresisgrave: 0xF6D8,
  27743. dieresistonos: 0x0385,
  27744. dihiragana: 0x3062,
  27745. dikatakana: 0x30C2,
  27746. dittomark: 0x3003,
  27747. divide: 0x00F7,
  27748. divides: 0x2223,
  27749. divisionslash: 0x2215,
  27750. djecyrillic: 0x0452,
  27751. dkshade: 0x2593,
  27752. dlinebelow: 0x1E0F,
  27753. dlsquare: 0x3397,
  27754. dmacron: 0x0111,
  27755. dmonospace: 0xFF44,
  27756. dnblock: 0x2584,
  27757. dochadathai: 0x0E0E,
  27758. dodekthai: 0x0E14,
  27759. dohiragana: 0x3069,
  27760. dokatakana: 0x30C9,
  27761. dollar: 0x0024,
  27762. dollarinferior: 0xF6E3,
  27763. dollarmonospace: 0xFF04,
  27764. dollaroldstyle: 0xF724,
  27765. dollarsmall: 0xFE69,
  27766. dollarsuperior: 0xF6E4,
  27767. dong: 0x20AB,
  27768. dorusquare: 0x3326,
  27769. dotaccent: 0x02D9,
  27770. dotaccentcmb: 0x0307,
  27771. dotbelowcmb: 0x0323,
  27772. dotbelowcomb: 0x0323,
  27773. dotkatakana: 0x30FB,
  27774. dotlessi: 0x0131,
  27775. dotlessj: 0xF6BE,
  27776. dotlessjstrokehook: 0x0284,
  27777. dotmath: 0x22C5,
  27778. dottedcircle: 0x25CC,
  27779. doubleyodpatah: 0xFB1F,
  27780. doubleyodpatahhebrew: 0xFB1F,
  27781. downtackbelowcmb: 0x031E,
  27782. downtackmod: 0x02D5,
  27783. dparen: 0x249F,
  27784. dsuperior: 0xF6EB,
  27785. dtail: 0x0256,
  27786. dtopbar: 0x018C,
  27787. duhiragana: 0x3065,
  27788. dukatakana: 0x30C5,
  27789. dz: 0x01F3,
  27790. dzaltone: 0x02A3,
  27791. dzcaron: 0x01C6,
  27792. dzcurl: 0x02A5,
  27793. dzeabkhasiancyrillic: 0x04E1,
  27794. dzecyrillic: 0x0455,
  27795. dzhecyrillic: 0x045F,
  27796. e: 0x0065,
  27797. eacute: 0x00E9,
  27798. earth: 0x2641,
  27799. ebengali: 0x098F,
  27800. ebopomofo: 0x311C,
  27801. ebreve: 0x0115,
  27802. ecandradeva: 0x090D,
  27803. ecandragujarati: 0x0A8D,
  27804. ecandravowelsigndeva: 0x0945,
  27805. ecandravowelsigngujarati: 0x0AC5,
  27806. ecaron: 0x011B,
  27807. ecedillabreve: 0x1E1D,
  27808. echarmenian: 0x0565,
  27809. echyiwnarmenian: 0x0587,
  27810. ecircle: 0x24D4,
  27811. ecircumflex: 0x00EA,
  27812. ecircumflexacute: 0x1EBF,
  27813. ecircumflexbelow: 0x1E19,
  27814. ecircumflexdotbelow: 0x1EC7,
  27815. ecircumflexgrave: 0x1EC1,
  27816. ecircumflexhookabove: 0x1EC3,
  27817. ecircumflextilde: 0x1EC5,
  27818. ecyrillic: 0x0454,
  27819. edblgrave: 0x0205,
  27820. edeva: 0x090F,
  27821. edieresis: 0x00EB,
  27822. edot: 0x0117,
  27823. edotaccent: 0x0117,
  27824. edotbelow: 0x1EB9,
  27825. eegurmukhi: 0x0A0F,
  27826. eematragurmukhi: 0x0A47,
  27827. efcyrillic: 0x0444,
  27828. egrave: 0x00E8,
  27829. egujarati: 0x0A8F,
  27830. eharmenian: 0x0567,
  27831. ehbopomofo: 0x311D,
  27832. ehiragana: 0x3048,
  27833. ehookabove: 0x1EBB,
  27834. eibopomofo: 0x311F,
  27835. eight: 0x0038,
  27836. eightarabic: 0x0668,
  27837. eightbengali: 0x09EE,
  27838. eightcircle: 0x2467,
  27839. eightcircleinversesansserif: 0x2791,
  27840. eightdeva: 0x096E,
  27841. eighteencircle: 0x2471,
  27842. eighteenparen: 0x2485,
  27843. eighteenperiod: 0x2499,
  27844. eightgujarati: 0x0AEE,
  27845. eightgurmukhi: 0x0A6E,
  27846. eighthackarabic: 0x0668,
  27847. eighthangzhou: 0x3028,
  27848. eighthnotebeamed: 0x266B,
  27849. eightideographicparen: 0x3227,
  27850. eightinferior: 0x2088,
  27851. eightmonospace: 0xFF18,
  27852. eightoldstyle: 0xF738,
  27853. eightparen: 0x247B,
  27854. eightperiod: 0x248F,
  27855. eightpersian: 0x06F8,
  27856. eightroman: 0x2177,
  27857. eightsuperior: 0x2078,
  27858. eightthai: 0x0E58,
  27859. einvertedbreve: 0x0207,
  27860. eiotifiedcyrillic: 0x0465,
  27861. ekatakana: 0x30A8,
  27862. ekatakanahalfwidth: 0xFF74,
  27863. ekonkargurmukhi: 0x0A74,
  27864. ekorean: 0x3154,
  27865. elcyrillic: 0x043B,
  27866. element: 0x2208,
  27867. elevencircle: 0x246A,
  27868. elevenparen: 0x247E,
  27869. elevenperiod: 0x2492,
  27870. elevenroman: 0x217A,
  27871. ellipsis: 0x2026,
  27872. ellipsisvertical: 0x22EE,
  27873. emacron: 0x0113,
  27874. emacronacute: 0x1E17,
  27875. emacrongrave: 0x1E15,
  27876. emcyrillic: 0x043C,
  27877. emdash: 0x2014,
  27878. emdashvertical: 0xFE31,
  27879. emonospace: 0xFF45,
  27880. emphasismarkarmenian: 0x055B,
  27881. emptyset: 0x2205,
  27882. enbopomofo: 0x3123,
  27883. encyrillic: 0x043D,
  27884. endash: 0x2013,
  27885. endashvertical: 0xFE32,
  27886. endescendercyrillic: 0x04A3,
  27887. eng: 0x014B,
  27888. engbopomofo: 0x3125,
  27889. enghecyrillic: 0x04A5,
  27890. enhookcyrillic: 0x04C8,
  27891. enspace: 0x2002,
  27892. eogonek: 0x0119,
  27893. eokorean: 0x3153,
  27894. eopen: 0x025B,
  27895. eopenclosed: 0x029A,
  27896. eopenreversed: 0x025C,
  27897. eopenreversedclosed: 0x025E,
  27898. eopenreversedhook: 0x025D,
  27899. eparen: 0x24A0,
  27900. epsilon: 0x03B5,
  27901. epsilontonos: 0x03AD,
  27902. equal: 0x003D,
  27903. equalmonospace: 0xFF1D,
  27904. equalsmall: 0xFE66,
  27905. equalsuperior: 0x207C,
  27906. equivalence: 0x2261,
  27907. erbopomofo: 0x3126,
  27908. ercyrillic: 0x0440,
  27909. ereversed: 0x0258,
  27910. ereversedcyrillic: 0x044D,
  27911. escyrillic: 0x0441,
  27912. esdescendercyrillic: 0x04AB,
  27913. esh: 0x0283,
  27914. eshcurl: 0x0286,
  27915. eshortdeva: 0x090E,
  27916. eshortvowelsigndeva: 0x0946,
  27917. eshreversedloop: 0x01AA,
  27918. eshsquatreversed: 0x0285,
  27919. esmallhiragana: 0x3047,
  27920. esmallkatakana: 0x30A7,
  27921. esmallkatakanahalfwidth: 0xFF6A,
  27922. estimated: 0x212E,
  27923. esuperior: 0xF6EC,
  27924. eta: 0x03B7,
  27925. etarmenian: 0x0568,
  27926. etatonos: 0x03AE,
  27927. eth: 0x00F0,
  27928. etilde: 0x1EBD,
  27929. etildebelow: 0x1E1B,
  27930. etnahtafoukhhebrew: 0x0591,
  27931. etnahtafoukhlefthebrew: 0x0591,
  27932. etnahtahebrew: 0x0591,
  27933. etnahtalefthebrew: 0x0591,
  27934. eturned: 0x01DD,
  27935. eukorean: 0x3161,
  27936. euro: 0x20AC,
  27937. evowelsignbengali: 0x09C7,
  27938. evowelsigndeva: 0x0947,
  27939. evowelsigngujarati: 0x0AC7,
  27940. exclam: 0x0021,
  27941. exclamarmenian: 0x055C,
  27942. exclamdbl: 0x203C,
  27943. exclamdown: 0x00A1,
  27944. exclamdownsmall: 0xF7A1,
  27945. exclammonospace: 0xFF01,
  27946. exclamsmall: 0xF721,
  27947. existential: 0x2203,
  27948. ezh: 0x0292,
  27949. ezhcaron: 0x01EF,
  27950. ezhcurl: 0x0293,
  27951. ezhreversed: 0x01B9,
  27952. ezhtail: 0x01BA,
  27953. f: 0x0066,
  27954. fadeva: 0x095E,
  27955. fagurmukhi: 0x0A5E,
  27956. fahrenheit: 0x2109,
  27957. fathaarabic: 0x064E,
  27958. fathalowarabic: 0x064E,
  27959. fathatanarabic: 0x064B,
  27960. fbopomofo: 0x3108,
  27961. fcircle: 0x24D5,
  27962. fdotaccent: 0x1E1F,
  27963. feharabic: 0x0641,
  27964. feharmenian: 0x0586,
  27965. fehfinalarabic: 0xFED2,
  27966. fehinitialarabic: 0xFED3,
  27967. fehmedialarabic: 0xFED4,
  27968. feicoptic: 0x03E5,
  27969. female: 0x2640,
  27970. ff: 0xFB00,
  27971. ffi: 0xFB03,
  27972. ffl: 0xFB04,
  27973. fi: 0xFB01,
  27974. fifteencircle: 0x246E,
  27975. fifteenparen: 0x2482,
  27976. fifteenperiod: 0x2496,
  27977. figuredash: 0x2012,
  27978. filledbox: 0x25A0,
  27979. filledrect: 0x25AC,
  27980. finalkaf: 0x05DA,
  27981. finalkafdagesh: 0xFB3A,
  27982. finalkafdageshhebrew: 0xFB3A,
  27983. finalkafhebrew: 0x05DA,
  27984. finalmem: 0x05DD,
  27985. finalmemhebrew: 0x05DD,
  27986. finalnun: 0x05DF,
  27987. finalnunhebrew: 0x05DF,
  27988. finalpe: 0x05E3,
  27989. finalpehebrew: 0x05E3,
  27990. finaltsadi: 0x05E5,
  27991. finaltsadihebrew: 0x05E5,
  27992. firsttonechinese: 0x02C9,
  27993. fisheye: 0x25C9,
  27994. fitacyrillic: 0x0473,
  27995. five: 0x0035,
  27996. fivearabic: 0x0665,
  27997. fivebengali: 0x09EB,
  27998. fivecircle: 0x2464,
  27999. fivecircleinversesansserif: 0x278E,
  28000. fivedeva: 0x096B,
  28001. fiveeighths: 0x215D,
  28002. fivegujarati: 0x0AEB,
  28003. fivegurmukhi: 0x0A6B,
  28004. fivehackarabic: 0x0665,
  28005. fivehangzhou: 0x3025,
  28006. fiveideographicparen: 0x3224,
  28007. fiveinferior: 0x2085,
  28008. fivemonospace: 0xFF15,
  28009. fiveoldstyle: 0xF735,
  28010. fiveparen: 0x2478,
  28011. fiveperiod: 0x248C,
  28012. fivepersian: 0x06F5,
  28013. fiveroman: 0x2174,
  28014. fivesuperior: 0x2075,
  28015. fivethai: 0x0E55,
  28016. fl: 0xFB02,
  28017. florin: 0x0192,
  28018. fmonospace: 0xFF46,
  28019. fmsquare: 0x3399,
  28020. fofanthai: 0x0E1F,
  28021. fofathai: 0x0E1D,
  28022. fongmanthai: 0x0E4F,
  28023. forall: 0x2200,
  28024. four: 0x0034,
  28025. fourarabic: 0x0664,
  28026. fourbengali: 0x09EA,
  28027. fourcircle: 0x2463,
  28028. fourcircleinversesansserif: 0x278D,
  28029. fourdeva: 0x096A,
  28030. fourgujarati: 0x0AEA,
  28031. fourgurmukhi: 0x0A6A,
  28032. fourhackarabic: 0x0664,
  28033. fourhangzhou: 0x3024,
  28034. fourideographicparen: 0x3223,
  28035. fourinferior: 0x2084,
  28036. fourmonospace: 0xFF14,
  28037. fournumeratorbengali: 0x09F7,
  28038. fouroldstyle: 0xF734,
  28039. fourparen: 0x2477,
  28040. fourperiod: 0x248B,
  28041. fourpersian: 0x06F4,
  28042. fourroman: 0x2173,
  28043. foursuperior: 0x2074,
  28044. fourteencircle: 0x246D,
  28045. fourteenparen: 0x2481,
  28046. fourteenperiod: 0x2495,
  28047. fourthai: 0x0E54,
  28048. fourthtonechinese: 0x02CB,
  28049. fparen: 0x24A1,
  28050. fraction: 0x2044,
  28051. franc: 0x20A3,
  28052. g: 0x0067,
  28053. gabengali: 0x0997,
  28054. gacute: 0x01F5,
  28055. gadeva: 0x0917,
  28056. gafarabic: 0x06AF,
  28057. gaffinalarabic: 0xFB93,
  28058. gafinitialarabic: 0xFB94,
  28059. gafmedialarabic: 0xFB95,
  28060. gagujarati: 0x0A97,
  28061. gagurmukhi: 0x0A17,
  28062. gahiragana: 0x304C,
  28063. gakatakana: 0x30AC,
  28064. gamma: 0x03B3,
  28065. gammalatinsmall: 0x0263,
  28066. gammasuperior: 0x02E0,
  28067. gangiacoptic: 0x03EB,
  28068. gbopomofo: 0x310D,
  28069. gbreve: 0x011F,
  28070. gcaron: 0x01E7,
  28071. gcedilla: 0x0123,
  28072. gcircle: 0x24D6,
  28073. gcircumflex: 0x011D,
  28074. gcommaaccent: 0x0123,
  28075. gdot: 0x0121,
  28076. gdotaccent: 0x0121,
  28077. gecyrillic: 0x0433,
  28078. gehiragana: 0x3052,
  28079. gekatakana: 0x30B2,
  28080. geometricallyequal: 0x2251,
  28081. gereshaccenthebrew: 0x059C,
  28082. gereshhebrew: 0x05F3,
  28083. gereshmuqdamhebrew: 0x059D,
  28084. germandbls: 0x00DF,
  28085. gershayimaccenthebrew: 0x059E,
  28086. gershayimhebrew: 0x05F4,
  28087. getamark: 0x3013,
  28088. ghabengali: 0x0998,
  28089. ghadarmenian: 0x0572,
  28090. ghadeva: 0x0918,
  28091. ghagujarati: 0x0A98,
  28092. ghagurmukhi: 0x0A18,
  28093. ghainarabic: 0x063A,
  28094. ghainfinalarabic: 0xFECE,
  28095. ghaininitialarabic: 0xFECF,
  28096. ghainmedialarabic: 0xFED0,
  28097. ghemiddlehookcyrillic: 0x0495,
  28098. ghestrokecyrillic: 0x0493,
  28099. gheupturncyrillic: 0x0491,
  28100. ghhadeva: 0x095A,
  28101. ghhagurmukhi: 0x0A5A,
  28102. ghook: 0x0260,
  28103. ghzsquare: 0x3393,
  28104. gihiragana: 0x304E,
  28105. gikatakana: 0x30AE,
  28106. gimarmenian: 0x0563,
  28107. gimel: 0x05D2,
  28108. gimeldagesh: 0xFB32,
  28109. gimeldageshhebrew: 0xFB32,
  28110. gimelhebrew: 0x05D2,
  28111. gjecyrillic: 0x0453,
  28112. glottalinvertedstroke: 0x01BE,
  28113. glottalstop: 0x0294,
  28114. glottalstopinverted: 0x0296,
  28115. glottalstopmod: 0x02C0,
  28116. glottalstopreversed: 0x0295,
  28117. glottalstopreversedmod: 0x02C1,
  28118. glottalstopreversedsuperior: 0x02E4,
  28119. glottalstopstroke: 0x02A1,
  28120. glottalstopstrokereversed: 0x02A2,
  28121. gmacron: 0x1E21,
  28122. gmonospace: 0xFF47,
  28123. gohiragana: 0x3054,
  28124. gokatakana: 0x30B4,
  28125. gparen: 0x24A2,
  28126. gpasquare: 0x33AC,
  28127. gradient: 0x2207,
  28128. grave: 0x0060,
  28129. gravebelowcmb: 0x0316,
  28130. gravecmb: 0x0300,
  28131. gravecomb: 0x0300,
  28132. gravedeva: 0x0953,
  28133. gravelowmod: 0x02CE,
  28134. gravemonospace: 0xFF40,
  28135. gravetonecmb: 0x0340,
  28136. greater: 0x003E,
  28137. greaterequal: 0x2265,
  28138. greaterequalorless: 0x22DB,
  28139. greatermonospace: 0xFF1E,
  28140. greaterorequivalent: 0x2273,
  28141. greaterorless: 0x2277,
  28142. greateroverequal: 0x2267,
  28143. greatersmall: 0xFE65,
  28144. gscript: 0x0261,
  28145. gstroke: 0x01E5,
  28146. guhiragana: 0x3050,
  28147. guillemotleft: 0x00AB,
  28148. guillemotright: 0x00BB,
  28149. guilsinglleft: 0x2039,
  28150. guilsinglright: 0x203A,
  28151. gukatakana: 0x30B0,
  28152. guramusquare: 0x3318,
  28153. gysquare: 0x33C9,
  28154. h: 0x0068,
  28155. haabkhasiancyrillic: 0x04A9,
  28156. haaltonearabic: 0x06C1,
  28157. habengali: 0x09B9,
  28158. hadescendercyrillic: 0x04B3,
  28159. hadeva: 0x0939,
  28160. hagujarati: 0x0AB9,
  28161. hagurmukhi: 0x0A39,
  28162. haharabic: 0x062D,
  28163. hahfinalarabic: 0xFEA2,
  28164. hahinitialarabic: 0xFEA3,
  28165. hahiragana: 0x306F,
  28166. hahmedialarabic: 0xFEA4,
  28167. haitusquare: 0x332A,
  28168. hakatakana: 0x30CF,
  28169. hakatakanahalfwidth: 0xFF8A,
  28170. halantgurmukhi: 0x0A4D,
  28171. hamzaarabic: 0x0621,
  28172. hamzalowarabic: 0x0621,
  28173. hangulfiller: 0x3164,
  28174. hardsigncyrillic: 0x044A,
  28175. harpoonleftbarbup: 0x21BC,
  28176. harpoonrightbarbup: 0x21C0,
  28177. hasquare: 0x33CA,
  28178. hatafpatah: 0x05B2,
  28179. hatafpatah16: 0x05B2,
  28180. hatafpatah23: 0x05B2,
  28181. hatafpatah2f: 0x05B2,
  28182. hatafpatahhebrew: 0x05B2,
  28183. hatafpatahnarrowhebrew: 0x05B2,
  28184. hatafpatahquarterhebrew: 0x05B2,
  28185. hatafpatahwidehebrew: 0x05B2,
  28186. hatafqamats: 0x05B3,
  28187. hatafqamats1b: 0x05B3,
  28188. hatafqamats28: 0x05B3,
  28189. hatafqamats34: 0x05B3,
  28190. hatafqamatshebrew: 0x05B3,
  28191. hatafqamatsnarrowhebrew: 0x05B3,
  28192. hatafqamatsquarterhebrew: 0x05B3,
  28193. hatafqamatswidehebrew: 0x05B3,
  28194. hatafsegol: 0x05B1,
  28195. hatafsegol17: 0x05B1,
  28196. hatafsegol24: 0x05B1,
  28197. hatafsegol30: 0x05B1,
  28198. hatafsegolhebrew: 0x05B1,
  28199. hatafsegolnarrowhebrew: 0x05B1,
  28200. hatafsegolquarterhebrew: 0x05B1,
  28201. hatafsegolwidehebrew: 0x05B1,
  28202. hbar: 0x0127,
  28203. hbopomofo: 0x310F,
  28204. hbrevebelow: 0x1E2B,
  28205. hcedilla: 0x1E29,
  28206. hcircle: 0x24D7,
  28207. hcircumflex: 0x0125,
  28208. hdieresis: 0x1E27,
  28209. hdotaccent: 0x1E23,
  28210. hdotbelow: 0x1E25,
  28211. he: 0x05D4,
  28212. heart: 0x2665,
  28213. heartsuitblack: 0x2665,
  28214. heartsuitwhite: 0x2661,
  28215. hedagesh: 0xFB34,
  28216. hedageshhebrew: 0xFB34,
  28217. hehaltonearabic: 0x06C1,
  28218. heharabic: 0x0647,
  28219. hehebrew: 0x05D4,
  28220. hehfinalaltonearabic: 0xFBA7,
  28221. hehfinalalttwoarabic: 0xFEEA,
  28222. hehfinalarabic: 0xFEEA,
  28223. hehhamzaabovefinalarabic: 0xFBA5,
  28224. hehhamzaaboveisolatedarabic: 0xFBA4,
  28225. hehinitialaltonearabic: 0xFBA8,
  28226. hehinitialarabic: 0xFEEB,
  28227. hehiragana: 0x3078,
  28228. hehmedialaltonearabic: 0xFBA9,
  28229. hehmedialarabic: 0xFEEC,
  28230. heiseierasquare: 0x337B,
  28231. hekatakana: 0x30D8,
  28232. hekatakanahalfwidth: 0xFF8D,
  28233. hekutaarusquare: 0x3336,
  28234. henghook: 0x0267,
  28235. herutusquare: 0x3339,
  28236. het: 0x05D7,
  28237. hethebrew: 0x05D7,
  28238. hhook: 0x0266,
  28239. hhooksuperior: 0x02B1,
  28240. hieuhacirclekorean: 0x327B,
  28241. hieuhaparenkorean: 0x321B,
  28242. hieuhcirclekorean: 0x326D,
  28243. hieuhkorean: 0x314E,
  28244. hieuhparenkorean: 0x320D,
  28245. hihiragana: 0x3072,
  28246. hikatakana: 0x30D2,
  28247. hikatakanahalfwidth: 0xFF8B,
  28248. hiriq: 0x05B4,
  28249. hiriq14: 0x05B4,
  28250. hiriq21: 0x05B4,
  28251. hiriq2d: 0x05B4,
  28252. hiriqhebrew: 0x05B4,
  28253. hiriqnarrowhebrew: 0x05B4,
  28254. hiriqquarterhebrew: 0x05B4,
  28255. hiriqwidehebrew: 0x05B4,
  28256. hlinebelow: 0x1E96,
  28257. hmonospace: 0xFF48,
  28258. hoarmenian: 0x0570,
  28259. hohipthai: 0x0E2B,
  28260. hohiragana: 0x307B,
  28261. hokatakana: 0x30DB,
  28262. hokatakanahalfwidth: 0xFF8E,
  28263. holam: 0x05B9,
  28264. holam19: 0x05B9,
  28265. holam26: 0x05B9,
  28266. holam32: 0x05B9,
  28267. holamhebrew: 0x05B9,
  28268. holamnarrowhebrew: 0x05B9,
  28269. holamquarterhebrew: 0x05B9,
  28270. holamwidehebrew: 0x05B9,
  28271. honokhukthai: 0x0E2E,
  28272. hookabovecomb: 0x0309,
  28273. hookcmb: 0x0309,
  28274. hookpalatalizedbelowcmb: 0x0321,
  28275. hookretroflexbelowcmb: 0x0322,
  28276. hoonsquare: 0x3342,
  28277. horicoptic: 0x03E9,
  28278. horizontalbar: 0x2015,
  28279. horncmb: 0x031B,
  28280. hotsprings: 0x2668,
  28281. house: 0x2302,
  28282. hparen: 0x24A3,
  28283. hsuperior: 0x02B0,
  28284. hturned: 0x0265,
  28285. huhiragana: 0x3075,
  28286. huiitosquare: 0x3333,
  28287. hukatakana: 0x30D5,
  28288. hukatakanahalfwidth: 0xFF8C,
  28289. hungarumlaut: 0x02DD,
  28290. hungarumlautcmb: 0x030B,
  28291. hv: 0x0195,
  28292. hyphen: 0x002D,
  28293. hypheninferior: 0xF6E5,
  28294. hyphenmonospace: 0xFF0D,
  28295. hyphensmall: 0xFE63,
  28296. hyphensuperior: 0xF6E6,
  28297. hyphentwo: 0x2010,
  28298. i: 0x0069,
  28299. iacute: 0x00ED,
  28300. iacyrillic: 0x044F,
  28301. ibengali: 0x0987,
  28302. ibopomofo: 0x3127,
  28303. ibreve: 0x012D,
  28304. icaron: 0x01D0,
  28305. icircle: 0x24D8,
  28306. icircumflex: 0x00EE,
  28307. icyrillic: 0x0456,
  28308. idblgrave: 0x0209,
  28309. ideographearthcircle: 0x328F,
  28310. ideographfirecircle: 0x328B,
  28311. ideographicallianceparen: 0x323F,
  28312. ideographiccallparen: 0x323A,
  28313. ideographiccentrecircle: 0x32A5,
  28314. ideographicclose: 0x3006,
  28315. ideographiccomma: 0x3001,
  28316. ideographiccommaleft: 0xFF64,
  28317. ideographiccongratulationparen: 0x3237,
  28318. ideographiccorrectcircle: 0x32A3,
  28319. ideographicearthparen: 0x322F,
  28320. ideographicenterpriseparen: 0x323D,
  28321. ideographicexcellentcircle: 0x329D,
  28322. ideographicfestivalparen: 0x3240,
  28323. ideographicfinancialcircle: 0x3296,
  28324. ideographicfinancialparen: 0x3236,
  28325. ideographicfireparen: 0x322B,
  28326. ideographichaveparen: 0x3232,
  28327. ideographichighcircle: 0x32A4,
  28328. ideographiciterationmark: 0x3005,
  28329. ideographiclaborcircle: 0x3298,
  28330. ideographiclaborparen: 0x3238,
  28331. ideographicleftcircle: 0x32A7,
  28332. ideographiclowcircle: 0x32A6,
  28333. ideographicmedicinecircle: 0x32A9,
  28334. ideographicmetalparen: 0x322E,
  28335. ideographicmoonparen: 0x322A,
  28336. ideographicnameparen: 0x3234,
  28337. ideographicperiod: 0x3002,
  28338. ideographicprintcircle: 0x329E,
  28339. ideographicreachparen: 0x3243,
  28340. ideographicrepresentparen: 0x3239,
  28341. ideographicresourceparen: 0x323E,
  28342. ideographicrightcircle: 0x32A8,
  28343. ideographicsecretcircle: 0x3299,
  28344. ideographicselfparen: 0x3242,
  28345. ideographicsocietyparen: 0x3233,
  28346. ideographicspace: 0x3000,
  28347. ideographicspecialparen: 0x3235,
  28348. ideographicstockparen: 0x3231,
  28349. ideographicstudyparen: 0x323B,
  28350. ideographicsunparen: 0x3230,
  28351. ideographicsuperviseparen: 0x323C,
  28352. ideographicwaterparen: 0x322C,
  28353. ideographicwoodparen: 0x322D,
  28354. ideographiczero: 0x3007,
  28355. ideographmetalcircle: 0x328E,
  28356. ideographmooncircle: 0x328A,
  28357. ideographnamecircle: 0x3294,
  28358. ideographsuncircle: 0x3290,
  28359. ideographwatercircle: 0x328C,
  28360. ideographwoodcircle: 0x328D,
  28361. ideva: 0x0907,
  28362. idieresis: 0x00EF,
  28363. idieresisacute: 0x1E2F,
  28364. idieresiscyrillic: 0x04E5,
  28365. idotbelow: 0x1ECB,
  28366. iebrevecyrillic: 0x04D7,
  28367. iecyrillic: 0x0435,
  28368. ieungacirclekorean: 0x3275,
  28369. ieungaparenkorean: 0x3215,
  28370. ieungcirclekorean: 0x3267,
  28371. ieungkorean: 0x3147,
  28372. ieungparenkorean: 0x3207,
  28373. igrave: 0x00EC,
  28374. igujarati: 0x0A87,
  28375. igurmukhi: 0x0A07,
  28376. ihiragana: 0x3044,
  28377. ihookabove: 0x1EC9,
  28378. iibengali: 0x0988,
  28379. iicyrillic: 0x0438,
  28380. iideva: 0x0908,
  28381. iigujarati: 0x0A88,
  28382. iigurmukhi: 0x0A08,
  28383. iimatragurmukhi: 0x0A40,
  28384. iinvertedbreve: 0x020B,
  28385. iishortcyrillic: 0x0439,
  28386. iivowelsignbengali: 0x09C0,
  28387. iivowelsigndeva: 0x0940,
  28388. iivowelsigngujarati: 0x0AC0,
  28389. ij: 0x0133,
  28390. ikatakana: 0x30A4,
  28391. ikatakanahalfwidth: 0xFF72,
  28392. ikorean: 0x3163,
  28393. ilde: 0x02DC,
  28394. iluyhebrew: 0x05AC,
  28395. imacron: 0x012B,
  28396. imacroncyrillic: 0x04E3,
  28397. imageorapproximatelyequal: 0x2253,
  28398. imatragurmukhi: 0x0A3F,
  28399. imonospace: 0xFF49,
  28400. increment: 0x2206,
  28401. infinity: 0x221E,
  28402. iniarmenian: 0x056B,
  28403. integral: 0x222B,
  28404. integralbottom: 0x2321,
  28405. integralbt: 0x2321,
  28406. integralex: 0xF8F5,
  28407. integraltop: 0x2320,
  28408. integraltp: 0x2320,
  28409. intersection: 0x2229,
  28410. intisquare: 0x3305,
  28411. invbullet: 0x25D8,
  28412. invcircle: 0x25D9,
  28413. invsmileface: 0x263B,
  28414. iocyrillic: 0x0451,
  28415. iogonek: 0x012F,
  28416. iota: 0x03B9,
  28417. iotadieresis: 0x03CA,
  28418. iotadieresistonos: 0x0390,
  28419. iotalatin: 0x0269,
  28420. iotatonos: 0x03AF,
  28421. iparen: 0x24A4,
  28422. irigurmukhi: 0x0A72,
  28423. ismallhiragana: 0x3043,
  28424. ismallkatakana: 0x30A3,
  28425. ismallkatakanahalfwidth: 0xFF68,
  28426. issharbengali: 0x09FA,
  28427. istroke: 0x0268,
  28428. isuperior: 0xF6ED,
  28429. iterationhiragana: 0x309D,
  28430. iterationkatakana: 0x30FD,
  28431. itilde: 0x0129,
  28432. itildebelow: 0x1E2D,
  28433. iubopomofo: 0x3129,
  28434. iucyrillic: 0x044E,
  28435. ivowelsignbengali: 0x09BF,
  28436. ivowelsigndeva: 0x093F,
  28437. ivowelsigngujarati: 0x0ABF,
  28438. izhitsacyrillic: 0x0475,
  28439. izhitsadblgravecyrillic: 0x0477,
  28440. j: 0x006A,
  28441. jaarmenian: 0x0571,
  28442. jabengali: 0x099C,
  28443. jadeva: 0x091C,
  28444. jagujarati: 0x0A9C,
  28445. jagurmukhi: 0x0A1C,
  28446. jbopomofo: 0x3110,
  28447. jcaron: 0x01F0,
  28448. jcircle: 0x24D9,
  28449. jcircumflex: 0x0135,
  28450. jcrossedtail: 0x029D,
  28451. jdotlessstroke: 0x025F,
  28452. jecyrillic: 0x0458,
  28453. jeemarabic: 0x062C,
  28454. jeemfinalarabic: 0xFE9E,
  28455. jeeminitialarabic: 0xFE9F,
  28456. jeemmedialarabic: 0xFEA0,
  28457. jeharabic: 0x0698,
  28458. jehfinalarabic: 0xFB8B,
  28459. jhabengali: 0x099D,
  28460. jhadeva: 0x091D,
  28461. jhagujarati: 0x0A9D,
  28462. jhagurmukhi: 0x0A1D,
  28463. jheharmenian: 0x057B,
  28464. jis: 0x3004,
  28465. jmonospace: 0xFF4A,
  28466. jparen: 0x24A5,
  28467. jsuperior: 0x02B2,
  28468. k: 0x006B,
  28469. kabashkircyrillic: 0x04A1,
  28470. kabengali: 0x0995,
  28471. kacute: 0x1E31,
  28472. kacyrillic: 0x043A,
  28473. kadescendercyrillic: 0x049B,
  28474. kadeva: 0x0915,
  28475. kaf: 0x05DB,
  28476. kafarabic: 0x0643,
  28477. kafdagesh: 0xFB3B,
  28478. kafdageshhebrew: 0xFB3B,
  28479. kaffinalarabic: 0xFEDA,
  28480. kafhebrew: 0x05DB,
  28481. kafinitialarabic: 0xFEDB,
  28482. kafmedialarabic: 0xFEDC,
  28483. kafrafehebrew: 0xFB4D,
  28484. kagujarati: 0x0A95,
  28485. kagurmukhi: 0x0A15,
  28486. kahiragana: 0x304B,
  28487. kahookcyrillic: 0x04C4,
  28488. kakatakana: 0x30AB,
  28489. kakatakanahalfwidth: 0xFF76,
  28490. kappa: 0x03BA,
  28491. kappasymbolgreek: 0x03F0,
  28492. kapyeounmieumkorean: 0x3171,
  28493. kapyeounphieuphkorean: 0x3184,
  28494. kapyeounpieupkorean: 0x3178,
  28495. kapyeounssangpieupkorean: 0x3179,
  28496. karoriisquare: 0x330D,
  28497. kashidaautoarabic: 0x0640,
  28498. kashidaautonosidebearingarabic: 0x0640,
  28499. kasmallkatakana: 0x30F5,
  28500. kasquare: 0x3384,
  28501. kasraarabic: 0x0650,
  28502. kasratanarabic: 0x064D,
  28503. kastrokecyrillic: 0x049F,
  28504. katahiraprolongmarkhalfwidth: 0xFF70,
  28505. kaverticalstrokecyrillic: 0x049D,
  28506. kbopomofo: 0x310E,
  28507. kcalsquare: 0x3389,
  28508. kcaron: 0x01E9,
  28509. kcedilla: 0x0137,
  28510. kcircle: 0x24DA,
  28511. kcommaaccent: 0x0137,
  28512. kdotbelow: 0x1E33,
  28513. keharmenian: 0x0584,
  28514. kehiragana: 0x3051,
  28515. kekatakana: 0x30B1,
  28516. kekatakanahalfwidth: 0xFF79,
  28517. kenarmenian: 0x056F,
  28518. kesmallkatakana: 0x30F6,
  28519. kgreenlandic: 0x0138,
  28520. khabengali: 0x0996,
  28521. khacyrillic: 0x0445,
  28522. khadeva: 0x0916,
  28523. khagujarati: 0x0A96,
  28524. khagurmukhi: 0x0A16,
  28525. khaharabic: 0x062E,
  28526. khahfinalarabic: 0xFEA6,
  28527. khahinitialarabic: 0xFEA7,
  28528. khahmedialarabic: 0xFEA8,
  28529. kheicoptic: 0x03E7,
  28530. khhadeva: 0x0959,
  28531. khhagurmukhi: 0x0A59,
  28532. khieukhacirclekorean: 0x3278,
  28533. khieukhaparenkorean: 0x3218,
  28534. khieukhcirclekorean: 0x326A,
  28535. khieukhkorean: 0x314B,
  28536. khieukhparenkorean: 0x320A,
  28537. khokhaithai: 0x0E02,
  28538. khokhonthai: 0x0E05,
  28539. khokhuatthai: 0x0E03,
  28540. khokhwaithai: 0x0E04,
  28541. khomutthai: 0x0E5B,
  28542. khook: 0x0199,
  28543. khorakhangthai: 0x0E06,
  28544. khzsquare: 0x3391,
  28545. kihiragana: 0x304D,
  28546. kikatakana: 0x30AD,
  28547. kikatakanahalfwidth: 0xFF77,
  28548. kiroguramusquare: 0x3315,
  28549. kiromeetorusquare: 0x3316,
  28550. kirosquare: 0x3314,
  28551. kiyeokacirclekorean: 0x326E,
  28552. kiyeokaparenkorean: 0x320E,
  28553. kiyeokcirclekorean: 0x3260,
  28554. kiyeokkorean: 0x3131,
  28555. kiyeokparenkorean: 0x3200,
  28556. kiyeoksioskorean: 0x3133,
  28557. kjecyrillic: 0x045C,
  28558. klinebelow: 0x1E35,
  28559. klsquare: 0x3398,
  28560. kmcubedsquare: 0x33A6,
  28561. kmonospace: 0xFF4B,
  28562. kmsquaredsquare: 0x33A2,
  28563. kohiragana: 0x3053,
  28564. kohmsquare: 0x33C0,
  28565. kokaithai: 0x0E01,
  28566. kokatakana: 0x30B3,
  28567. kokatakanahalfwidth: 0xFF7A,
  28568. kooposquare: 0x331E,
  28569. koppacyrillic: 0x0481,
  28570. koreanstandardsymbol: 0x327F,
  28571. koroniscmb: 0x0343,
  28572. kparen: 0x24A6,
  28573. kpasquare: 0x33AA,
  28574. ksicyrillic: 0x046F,
  28575. ktsquare: 0x33CF,
  28576. kturned: 0x029E,
  28577. kuhiragana: 0x304F,
  28578. kukatakana: 0x30AF,
  28579. kukatakanahalfwidth: 0xFF78,
  28580. kvsquare: 0x33B8,
  28581. kwsquare: 0x33BE,
  28582. l: 0x006C,
  28583. labengali: 0x09B2,
  28584. lacute: 0x013A,
  28585. ladeva: 0x0932,
  28586. lagujarati: 0x0AB2,
  28587. lagurmukhi: 0x0A32,
  28588. lakkhangyaothai: 0x0E45,
  28589. lamaleffinalarabic: 0xFEFC,
  28590. lamalefhamzaabovefinalarabic: 0xFEF8,
  28591. lamalefhamzaaboveisolatedarabic: 0xFEF7,
  28592. lamalefhamzabelowfinalarabic: 0xFEFA,
  28593. lamalefhamzabelowisolatedarabic: 0xFEF9,
  28594. lamalefisolatedarabic: 0xFEFB,
  28595. lamalefmaddaabovefinalarabic: 0xFEF6,
  28596. lamalefmaddaaboveisolatedarabic: 0xFEF5,
  28597. lamarabic: 0x0644,
  28598. lambda: 0x03BB,
  28599. lambdastroke: 0x019B,
  28600. lamed: 0x05DC,
  28601. lameddagesh: 0xFB3C,
  28602. lameddageshhebrew: 0xFB3C,
  28603. lamedhebrew: 0x05DC,
  28604. lamfinalarabic: 0xFEDE,
  28605. lamhahinitialarabic: 0xFCCA,
  28606. laminitialarabic: 0xFEDF,
  28607. lamjeeminitialarabic: 0xFCC9,
  28608. lamkhahinitialarabic: 0xFCCB,
  28609. lamlamhehisolatedarabic: 0xFDF2,
  28610. lammedialarabic: 0xFEE0,
  28611. lammeemhahinitialarabic: 0xFD88,
  28612. lammeeminitialarabic: 0xFCCC,
  28613. largecircle: 0x25EF,
  28614. lbar: 0x019A,
  28615. lbelt: 0x026C,
  28616. lbopomofo: 0x310C,
  28617. lcaron: 0x013E,
  28618. lcedilla: 0x013C,
  28619. lcircle: 0x24DB,
  28620. lcircumflexbelow: 0x1E3D,
  28621. lcommaaccent: 0x013C,
  28622. ldot: 0x0140,
  28623. ldotaccent: 0x0140,
  28624. ldotbelow: 0x1E37,
  28625. ldotbelowmacron: 0x1E39,
  28626. leftangleabovecmb: 0x031A,
  28627. lefttackbelowcmb: 0x0318,
  28628. less: 0x003C,
  28629. lessequal: 0x2264,
  28630. lessequalorgreater: 0x22DA,
  28631. lessmonospace: 0xFF1C,
  28632. lessorequivalent: 0x2272,
  28633. lessorgreater: 0x2276,
  28634. lessoverequal: 0x2266,
  28635. lesssmall: 0xFE64,
  28636. lezh: 0x026E,
  28637. lfblock: 0x258C,
  28638. lhookretroflex: 0x026D,
  28639. lira: 0x20A4,
  28640. liwnarmenian: 0x056C,
  28641. lj: 0x01C9,
  28642. ljecyrillic: 0x0459,
  28643. ll: 0xF6C0,
  28644. lladeva: 0x0933,
  28645. llagujarati: 0x0AB3,
  28646. llinebelow: 0x1E3B,
  28647. llladeva: 0x0934,
  28648. llvocalicbengali: 0x09E1,
  28649. llvocalicdeva: 0x0961,
  28650. llvocalicvowelsignbengali: 0x09E3,
  28651. llvocalicvowelsigndeva: 0x0963,
  28652. lmiddletilde: 0x026B,
  28653. lmonospace: 0xFF4C,
  28654. lmsquare: 0x33D0,
  28655. lochulathai: 0x0E2C,
  28656. logicaland: 0x2227,
  28657. logicalnot: 0x00AC,
  28658. logicalnotreversed: 0x2310,
  28659. logicalor: 0x2228,
  28660. lolingthai: 0x0E25,
  28661. longs: 0x017F,
  28662. lowlinecenterline: 0xFE4E,
  28663. lowlinecmb: 0x0332,
  28664. lowlinedashed: 0xFE4D,
  28665. lozenge: 0x25CA,
  28666. lparen: 0x24A7,
  28667. lslash: 0x0142,
  28668. lsquare: 0x2113,
  28669. lsuperior: 0xF6EE,
  28670. ltshade: 0x2591,
  28671. luthai: 0x0E26,
  28672. lvocalicbengali: 0x098C,
  28673. lvocalicdeva: 0x090C,
  28674. lvocalicvowelsignbengali: 0x09E2,
  28675. lvocalicvowelsigndeva: 0x0962,
  28676. lxsquare: 0x33D3,
  28677. m: 0x006D,
  28678. mabengali: 0x09AE,
  28679. macron: 0x00AF,
  28680. macronbelowcmb: 0x0331,
  28681. macroncmb: 0x0304,
  28682. macronlowmod: 0x02CD,
  28683. macronmonospace: 0xFFE3,
  28684. macute: 0x1E3F,
  28685. madeva: 0x092E,
  28686. magujarati: 0x0AAE,
  28687. magurmukhi: 0x0A2E,
  28688. mahapakhhebrew: 0x05A4,
  28689. mahapakhlefthebrew: 0x05A4,
  28690. mahiragana: 0x307E,
  28691. maichattawalowleftthai: 0xF895,
  28692. maichattawalowrightthai: 0xF894,
  28693. maichattawathai: 0x0E4B,
  28694. maichattawaupperleftthai: 0xF893,
  28695. maieklowleftthai: 0xF88C,
  28696. maieklowrightthai: 0xF88B,
  28697. maiekthai: 0x0E48,
  28698. maiekupperleftthai: 0xF88A,
  28699. maihanakatleftthai: 0xF884,
  28700. maihanakatthai: 0x0E31,
  28701. maitaikhuleftthai: 0xF889,
  28702. maitaikhuthai: 0x0E47,
  28703. maitholowleftthai: 0xF88F,
  28704. maitholowrightthai: 0xF88E,
  28705. maithothai: 0x0E49,
  28706. maithoupperleftthai: 0xF88D,
  28707. maitrilowleftthai: 0xF892,
  28708. maitrilowrightthai: 0xF891,
  28709. maitrithai: 0x0E4A,
  28710. maitriupperleftthai: 0xF890,
  28711. maiyamokthai: 0x0E46,
  28712. makatakana: 0x30DE,
  28713. makatakanahalfwidth: 0xFF8F,
  28714. male: 0x2642,
  28715. mansyonsquare: 0x3347,
  28716. maqafhebrew: 0x05BE,
  28717. mars: 0x2642,
  28718. masoracirclehebrew: 0x05AF,
  28719. masquare: 0x3383,
  28720. mbopomofo: 0x3107,
  28721. mbsquare: 0x33D4,
  28722. mcircle: 0x24DC,
  28723. mcubedsquare: 0x33A5,
  28724. mdotaccent: 0x1E41,
  28725. mdotbelow: 0x1E43,
  28726. meemarabic: 0x0645,
  28727. meemfinalarabic: 0xFEE2,
  28728. meeminitialarabic: 0xFEE3,
  28729. meemmedialarabic: 0xFEE4,
  28730. meemmeeminitialarabic: 0xFCD1,
  28731. meemmeemisolatedarabic: 0xFC48,
  28732. meetorusquare: 0x334D,
  28733. mehiragana: 0x3081,
  28734. meizierasquare: 0x337E,
  28735. mekatakana: 0x30E1,
  28736. mekatakanahalfwidth: 0xFF92,
  28737. mem: 0x05DE,
  28738. memdagesh: 0xFB3E,
  28739. memdageshhebrew: 0xFB3E,
  28740. memhebrew: 0x05DE,
  28741. menarmenian: 0x0574,
  28742. merkhahebrew: 0x05A5,
  28743. merkhakefulahebrew: 0x05A6,
  28744. merkhakefulalefthebrew: 0x05A6,
  28745. merkhalefthebrew: 0x05A5,
  28746. mhook: 0x0271,
  28747. mhzsquare: 0x3392,
  28748. middledotkatakanahalfwidth: 0xFF65,
  28749. middot: 0x00B7,
  28750. mieumacirclekorean: 0x3272,
  28751. mieumaparenkorean: 0x3212,
  28752. mieumcirclekorean: 0x3264,
  28753. mieumkorean: 0x3141,
  28754. mieumpansioskorean: 0x3170,
  28755. mieumparenkorean: 0x3204,
  28756. mieumpieupkorean: 0x316E,
  28757. mieumsioskorean: 0x316F,
  28758. mihiragana: 0x307F,
  28759. mikatakana: 0x30DF,
  28760. mikatakanahalfwidth: 0xFF90,
  28761. minus: 0x2212,
  28762. minusbelowcmb: 0x0320,
  28763. minuscircle: 0x2296,
  28764. minusmod: 0x02D7,
  28765. minusplus: 0x2213,
  28766. minute: 0x2032,
  28767. miribaarusquare: 0x334A,
  28768. mirisquare: 0x3349,
  28769. mlonglegturned: 0x0270,
  28770. mlsquare: 0x3396,
  28771. mmcubedsquare: 0x33A3,
  28772. mmonospace: 0xFF4D,
  28773. mmsquaredsquare: 0x339F,
  28774. mohiragana: 0x3082,
  28775. mohmsquare: 0x33C1,
  28776. mokatakana: 0x30E2,
  28777. mokatakanahalfwidth: 0xFF93,
  28778. molsquare: 0x33D6,
  28779. momathai: 0x0E21,
  28780. moverssquare: 0x33A7,
  28781. moverssquaredsquare: 0x33A8,
  28782. mparen: 0x24A8,
  28783. mpasquare: 0x33AB,
  28784. mssquare: 0x33B3,
  28785. msuperior: 0xF6EF,
  28786. mturned: 0x026F,
  28787. mu: 0x00B5,
  28788. mu1: 0x00B5,
  28789. muasquare: 0x3382,
  28790. muchgreater: 0x226B,
  28791. muchless: 0x226A,
  28792. mufsquare: 0x338C,
  28793. mugreek: 0x03BC,
  28794. mugsquare: 0x338D,
  28795. muhiragana: 0x3080,
  28796. mukatakana: 0x30E0,
  28797. mukatakanahalfwidth: 0xFF91,
  28798. mulsquare: 0x3395,
  28799. multiply: 0x00D7,
  28800. mumsquare: 0x339B,
  28801. munahhebrew: 0x05A3,
  28802. munahlefthebrew: 0x05A3,
  28803. musicalnote: 0x266A,
  28804. musicalnotedbl: 0x266B,
  28805. musicflatsign: 0x266D,
  28806. musicsharpsign: 0x266F,
  28807. mussquare: 0x33B2,
  28808. muvsquare: 0x33B6,
  28809. muwsquare: 0x33BC,
  28810. mvmegasquare: 0x33B9,
  28811. mvsquare: 0x33B7,
  28812. mwmegasquare: 0x33BF,
  28813. mwsquare: 0x33BD,
  28814. n: 0x006E,
  28815. nabengali: 0x09A8,
  28816. nabla: 0x2207,
  28817. nacute: 0x0144,
  28818. nadeva: 0x0928,
  28819. nagujarati: 0x0AA8,
  28820. nagurmukhi: 0x0A28,
  28821. nahiragana: 0x306A,
  28822. nakatakana: 0x30CA,
  28823. nakatakanahalfwidth: 0xFF85,
  28824. napostrophe: 0x0149,
  28825. nasquare: 0x3381,
  28826. nbopomofo: 0x310B,
  28827. nbspace: 0x00A0,
  28828. ncaron: 0x0148,
  28829. ncedilla: 0x0146,
  28830. ncircle: 0x24DD,
  28831. ncircumflexbelow: 0x1E4B,
  28832. ncommaaccent: 0x0146,
  28833. ndotaccent: 0x1E45,
  28834. ndotbelow: 0x1E47,
  28835. nehiragana: 0x306D,
  28836. nekatakana: 0x30CD,
  28837. nekatakanahalfwidth: 0xFF88,
  28838. newsheqelsign: 0x20AA,
  28839. nfsquare: 0x338B,
  28840. ngabengali: 0x0999,
  28841. ngadeva: 0x0919,
  28842. ngagujarati: 0x0A99,
  28843. ngagurmukhi: 0x0A19,
  28844. ngonguthai: 0x0E07,
  28845. nhiragana: 0x3093,
  28846. nhookleft: 0x0272,
  28847. nhookretroflex: 0x0273,
  28848. nieunacirclekorean: 0x326F,
  28849. nieunaparenkorean: 0x320F,
  28850. nieuncieuckorean: 0x3135,
  28851. nieuncirclekorean: 0x3261,
  28852. nieunhieuhkorean: 0x3136,
  28853. nieunkorean: 0x3134,
  28854. nieunpansioskorean: 0x3168,
  28855. nieunparenkorean: 0x3201,
  28856. nieunsioskorean: 0x3167,
  28857. nieuntikeutkorean: 0x3166,
  28858. nihiragana: 0x306B,
  28859. nikatakana: 0x30CB,
  28860. nikatakanahalfwidth: 0xFF86,
  28861. nikhahitleftthai: 0xF899,
  28862. nikhahitthai: 0x0E4D,
  28863. nine: 0x0039,
  28864. ninearabic: 0x0669,
  28865. ninebengali: 0x09EF,
  28866. ninecircle: 0x2468,
  28867. ninecircleinversesansserif: 0x2792,
  28868. ninedeva: 0x096F,
  28869. ninegujarati: 0x0AEF,
  28870. ninegurmukhi: 0x0A6F,
  28871. ninehackarabic: 0x0669,
  28872. ninehangzhou: 0x3029,
  28873. nineideographicparen: 0x3228,
  28874. nineinferior: 0x2089,
  28875. ninemonospace: 0xFF19,
  28876. nineoldstyle: 0xF739,
  28877. nineparen: 0x247C,
  28878. nineperiod: 0x2490,
  28879. ninepersian: 0x06F9,
  28880. nineroman: 0x2178,
  28881. ninesuperior: 0x2079,
  28882. nineteencircle: 0x2472,
  28883. nineteenparen: 0x2486,
  28884. nineteenperiod: 0x249A,
  28885. ninethai: 0x0E59,
  28886. nj: 0x01CC,
  28887. njecyrillic: 0x045A,
  28888. nkatakana: 0x30F3,
  28889. nkatakanahalfwidth: 0xFF9D,
  28890. nlegrightlong: 0x019E,
  28891. nlinebelow: 0x1E49,
  28892. nmonospace: 0xFF4E,
  28893. nmsquare: 0x339A,
  28894. nnabengali: 0x09A3,
  28895. nnadeva: 0x0923,
  28896. nnagujarati: 0x0AA3,
  28897. nnagurmukhi: 0x0A23,
  28898. nnnadeva: 0x0929,
  28899. nohiragana: 0x306E,
  28900. nokatakana: 0x30CE,
  28901. nokatakanahalfwidth: 0xFF89,
  28902. nonbreakingspace: 0x00A0,
  28903. nonenthai: 0x0E13,
  28904. nonuthai: 0x0E19,
  28905. noonarabic: 0x0646,
  28906. noonfinalarabic: 0xFEE6,
  28907. noonghunnaarabic: 0x06BA,
  28908. noonghunnafinalarabic: 0xFB9F,
  28909. nooninitialarabic: 0xFEE7,
  28910. noonjeeminitialarabic: 0xFCD2,
  28911. noonjeemisolatedarabic: 0xFC4B,
  28912. noonmedialarabic: 0xFEE8,
  28913. noonmeeminitialarabic: 0xFCD5,
  28914. noonmeemisolatedarabic: 0xFC4E,
  28915. noonnoonfinalarabic: 0xFC8D,
  28916. notcontains: 0x220C,
  28917. notelement: 0x2209,
  28918. notelementof: 0x2209,
  28919. notequal: 0x2260,
  28920. notgreater: 0x226F,
  28921. notgreaternorequal: 0x2271,
  28922. notgreaternorless: 0x2279,
  28923. notidentical: 0x2262,
  28924. notless: 0x226E,
  28925. notlessnorequal: 0x2270,
  28926. notparallel: 0x2226,
  28927. notprecedes: 0x2280,
  28928. notsubset: 0x2284,
  28929. notsucceeds: 0x2281,
  28930. notsuperset: 0x2285,
  28931. nowarmenian: 0x0576,
  28932. nparen: 0x24A9,
  28933. nssquare: 0x33B1,
  28934. nsuperior: 0x207F,
  28935. ntilde: 0x00F1,
  28936. nu: 0x03BD,
  28937. nuhiragana: 0x306C,
  28938. nukatakana: 0x30CC,
  28939. nukatakanahalfwidth: 0xFF87,
  28940. nuktabengali: 0x09BC,
  28941. nuktadeva: 0x093C,
  28942. nuktagujarati: 0x0ABC,
  28943. nuktagurmukhi: 0x0A3C,
  28944. numbersign: 0x0023,
  28945. numbersignmonospace: 0xFF03,
  28946. numbersignsmall: 0xFE5F,
  28947. numeralsigngreek: 0x0374,
  28948. numeralsignlowergreek: 0x0375,
  28949. numero: 0x2116,
  28950. nun: 0x05E0,
  28951. nundagesh: 0xFB40,
  28952. nundageshhebrew: 0xFB40,
  28953. nunhebrew: 0x05E0,
  28954. nvsquare: 0x33B5,
  28955. nwsquare: 0x33BB,
  28956. nyabengali: 0x099E,
  28957. nyadeva: 0x091E,
  28958. nyagujarati: 0x0A9E,
  28959. nyagurmukhi: 0x0A1E,
  28960. o: 0x006F,
  28961. oacute: 0x00F3,
  28962. oangthai: 0x0E2D,
  28963. obarred: 0x0275,
  28964. obarredcyrillic: 0x04E9,
  28965. obarreddieresiscyrillic: 0x04EB,
  28966. obengali: 0x0993,
  28967. obopomofo: 0x311B,
  28968. obreve: 0x014F,
  28969. ocandradeva: 0x0911,
  28970. ocandragujarati: 0x0A91,
  28971. ocandravowelsigndeva: 0x0949,
  28972. ocandravowelsigngujarati: 0x0AC9,
  28973. ocaron: 0x01D2,
  28974. ocircle: 0x24DE,
  28975. ocircumflex: 0x00F4,
  28976. ocircumflexacute: 0x1ED1,
  28977. ocircumflexdotbelow: 0x1ED9,
  28978. ocircumflexgrave: 0x1ED3,
  28979. ocircumflexhookabove: 0x1ED5,
  28980. ocircumflextilde: 0x1ED7,
  28981. ocyrillic: 0x043E,
  28982. odblacute: 0x0151,
  28983. odblgrave: 0x020D,
  28984. odeva: 0x0913,
  28985. odieresis: 0x00F6,
  28986. odieresiscyrillic: 0x04E7,
  28987. odotbelow: 0x1ECD,
  28988. oe: 0x0153,
  28989. oekorean: 0x315A,
  28990. ogonek: 0x02DB,
  28991. ogonekcmb: 0x0328,
  28992. ograve: 0x00F2,
  28993. ogujarati: 0x0A93,
  28994. oharmenian: 0x0585,
  28995. ohiragana: 0x304A,
  28996. ohookabove: 0x1ECF,
  28997. ohorn: 0x01A1,
  28998. ohornacute: 0x1EDB,
  28999. ohorndotbelow: 0x1EE3,
  29000. ohorngrave: 0x1EDD,
  29001. ohornhookabove: 0x1EDF,
  29002. ohorntilde: 0x1EE1,
  29003. ohungarumlaut: 0x0151,
  29004. oi: 0x01A3,
  29005. oinvertedbreve: 0x020F,
  29006. okatakana: 0x30AA,
  29007. okatakanahalfwidth: 0xFF75,
  29008. okorean: 0x3157,
  29009. olehebrew: 0x05AB,
  29010. omacron: 0x014D,
  29011. omacronacute: 0x1E53,
  29012. omacrongrave: 0x1E51,
  29013. omdeva: 0x0950,
  29014. omega: 0x03C9,
  29015. omega1: 0x03D6,
  29016. omegacyrillic: 0x0461,
  29017. omegalatinclosed: 0x0277,
  29018. omegaroundcyrillic: 0x047B,
  29019. omegatitlocyrillic: 0x047D,
  29020. omegatonos: 0x03CE,
  29021. omgujarati: 0x0AD0,
  29022. omicron: 0x03BF,
  29023. omicrontonos: 0x03CC,
  29024. omonospace: 0xFF4F,
  29025. one: 0x0031,
  29026. onearabic: 0x0661,
  29027. onebengali: 0x09E7,
  29028. onecircle: 0x2460,
  29029. onecircleinversesansserif: 0x278A,
  29030. onedeva: 0x0967,
  29031. onedotenleader: 0x2024,
  29032. oneeighth: 0x215B,
  29033. onefitted: 0xF6DC,
  29034. onegujarati: 0x0AE7,
  29035. onegurmukhi: 0x0A67,
  29036. onehackarabic: 0x0661,
  29037. onehalf: 0x00BD,
  29038. onehangzhou: 0x3021,
  29039. oneideographicparen: 0x3220,
  29040. oneinferior: 0x2081,
  29041. onemonospace: 0xFF11,
  29042. onenumeratorbengali: 0x09F4,
  29043. oneoldstyle: 0xF731,
  29044. oneparen: 0x2474,
  29045. oneperiod: 0x2488,
  29046. onepersian: 0x06F1,
  29047. onequarter: 0x00BC,
  29048. oneroman: 0x2170,
  29049. onesuperior: 0x00B9,
  29050. onethai: 0x0E51,
  29051. onethird: 0x2153,
  29052. oogonek: 0x01EB,
  29053. oogonekmacron: 0x01ED,
  29054. oogurmukhi: 0x0A13,
  29055. oomatragurmukhi: 0x0A4B,
  29056. oopen: 0x0254,
  29057. oparen: 0x24AA,
  29058. openbullet: 0x25E6,
  29059. option: 0x2325,
  29060. ordfeminine: 0x00AA,
  29061. ordmasculine: 0x00BA,
  29062. orthogonal: 0x221F,
  29063. oshortdeva: 0x0912,
  29064. oshortvowelsigndeva: 0x094A,
  29065. oslash: 0x00F8,
  29066. oslashacute: 0x01FF,
  29067. osmallhiragana: 0x3049,
  29068. osmallkatakana: 0x30A9,
  29069. osmallkatakanahalfwidth: 0xFF6B,
  29070. ostrokeacute: 0x01FF,
  29071. osuperior: 0xF6F0,
  29072. otcyrillic: 0x047F,
  29073. otilde: 0x00F5,
  29074. otildeacute: 0x1E4D,
  29075. otildedieresis: 0x1E4F,
  29076. oubopomofo: 0x3121,
  29077. overline: 0x203E,
  29078. overlinecenterline: 0xFE4A,
  29079. overlinecmb: 0x0305,
  29080. overlinedashed: 0xFE49,
  29081. overlinedblwavy: 0xFE4C,
  29082. overlinewavy: 0xFE4B,
  29083. overscore: 0x00AF,
  29084. ovowelsignbengali: 0x09CB,
  29085. ovowelsigndeva: 0x094B,
  29086. ovowelsigngujarati: 0x0ACB,
  29087. p: 0x0070,
  29088. paampssquare: 0x3380,
  29089. paasentosquare: 0x332B,
  29090. pabengali: 0x09AA,
  29091. pacute: 0x1E55,
  29092. padeva: 0x092A,
  29093. pagedown: 0x21DF,
  29094. pageup: 0x21DE,
  29095. pagujarati: 0x0AAA,
  29096. pagurmukhi: 0x0A2A,
  29097. pahiragana: 0x3071,
  29098. paiyannoithai: 0x0E2F,
  29099. pakatakana: 0x30D1,
  29100. palatalizationcyrilliccmb: 0x0484,
  29101. palochkacyrillic: 0x04C0,
  29102. pansioskorean: 0x317F,
  29103. paragraph: 0x00B6,
  29104. parallel: 0x2225,
  29105. parenleft: 0x0028,
  29106. parenleftaltonearabic: 0xFD3E,
  29107. parenleftbt: 0xF8ED,
  29108. parenleftex: 0xF8EC,
  29109. parenleftinferior: 0x208D,
  29110. parenleftmonospace: 0xFF08,
  29111. parenleftsmall: 0xFE59,
  29112. parenleftsuperior: 0x207D,
  29113. parenlefttp: 0xF8EB,
  29114. parenleftvertical: 0xFE35,
  29115. parenright: 0x0029,
  29116. parenrightaltonearabic: 0xFD3F,
  29117. parenrightbt: 0xF8F8,
  29118. parenrightex: 0xF8F7,
  29119. parenrightinferior: 0x208E,
  29120. parenrightmonospace: 0xFF09,
  29121. parenrightsmall: 0xFE5A,
  29122. parenrightsuperior: 0x207E,
  29123. parenrighttp: 0xF8F6,
  29124. parenrightvertical: 0xFE36,
  29125. partialdiff: 0x2202,
  29126. paseqhebrew: 0x05C0,
  29127. pashtahebrew: 0x0599,
  29128. pasquare: 0x33A9,
  29129. patah: 0x05B7,
  29130. patah11: 0x05B7,
  29131. patah1d: 0x05B7,
  29132. patah2a: 0x05B7,
  29133. patahhebrew: 0x05B7,
  29134. patahnarrowhebrew: 0x05B7,
  29135. patahquarterhebrew: 0x05B7,
  29136. patahwidehebrew: 0x05B7,
  29137. pazerhebrew: 0x05A1,
  29138. pbopomofo: 0x3106,
  29139. pcircle: 0x24DF,
  29140. pdotaccent: 0x1E57,
  29141. pe: 0x05E4,
  29142. pecyrillic: 0x043F,
  29143. pedagesh: 0xFB44,
  29144. pedageshhebrew: 0xFB44,
  29145. peezisquare: 0x333B,
  29146. pefinaldageshhebrew: 0xFB43,
  29147. peharabic: 0x067E,
  29148. peharmenian: 0x057A,
  29149. pehebrew: 0x05E4,
  29150. pehfinalarabic: 0xFB57,
  29151. pehinitialarabic: 0xFB58,
  29152. pehiragana: 0x307A,
  29153. pehmedialarabic: 0xFB59,
  29154. pekatakana: 0x30DA,
  29155. pemiddlehookcyrillic: 0x04A7,
  29156. perafehebrew: 0xFB4E,
  29157. percent: 0x0025,
  29158. percentarabic: 0x066A,
  29159. percentmonospace: 0xFF05,
  29160. percentsmall: 0xFE6A,
  29161. period: 0x002E,
  29162. periodarmenian: 0x0589,
  29163. periodcentered: 0x00B7,
  29164. periodhalfwidth: 0xFF61,
  29165. periodinferior: 0xF6E7,
  29166. periodmonospace: 0xFF0E,
  29167. periodsmall: 0xFE52,
  29168. periodsuperior: 0xF6E8,
  29169. perispomenigreekcmb: 0x0342,
  29170. perpendicular: 0x22A5,
  29171. perthousand: 0x2030,
  29172. peseta: 0x20A7,
  29173. pfsquare: 0x338A,
  29174. phabengali: 0x09AB,
  29175. phadeva: 0x092B,
  29176. phagujarati: 0x0AAB,
  29177. phagurmukhi: 0x0A2B,
  29178. phi: 0x03C6,
  29179. phi1: 0x03D5,
  29180. phieuphacirclekorean: 0x327A,
  29181. phieuphaparenkorean: 0x321A,
  29182. phieuphcirclekorean: 0x326C,
  29183. phieuphkorean: 0x314D,
  29184. phieuphparenkorean: 0x320C,
  29185. philatin: 0x0278,
  29186. phinthuthai: 0x0E3A,
  29187. phisymbolgreek: 0x03D5,
  29188. phook: 0x01A5,
  29189. phophanthai: 0x0E1E,
  29190. phophungthai: 0x0E1C,
  29191. phosamphaothai: 0x0E20,
  29192. pi: 0x03C0,
  29193. pieupacirclekorean: 0x3273,
  29194. pieupaparenkorean: 0x3213,
  29195. pieupcieuckorean: 0x3176,
  29196. pieupcirclekorean: 0x3265,
  29197. pieupkiyeokkorean: 0x3172,
  29198. pieupkorean: 0x3142,
  29199. pieupparenkorean: 0x3205,
  29200. pieupsioskiyeokkorean: 0x3174,
  29201. pieupsioskorean: 0x3144,
  29202. pieupsiostikeutkorean: 0x3175,
  29203. pieupthieuthkorean: 0x3177,
  29204. pieuptikeutkorean: 0x3173,
  29205. pihiragana: 0x3074,
  29206. pikatakana: 0x30D4,
  29207. pisymbolgreek: 0x03D6,
  29208. piwrarmenian: 0x0583,
  29209. plus: 0x002B,
  29210. plusbelowcmb: 0x031F,
  29211. pluscircle: 0x2295,
  29212. plusminus: 0x00B1,
  29213. plusmod: 0x02D6,
  29214. plusmonospace: 0xFF0B,
  29215. plussmall: 0xFE62,
  29216. plussuperior: 0x207A,
  29217. pmonospace: 0xFF50,
  29218. pmsquare: 0x33D8,
  29219. pohiragana: 0x307D,
  29220. pointingindexdownwhite: 0x261F,
  29221. pointingindexleftwhite: 0x261C,
  29222. pointingindexrightwhite: 0x261E,
  29223. pointingindexupwhite: 0x261D,
  29224. pokatakana: 0x30DD,
  29225. poplathai: 0x0E1B,
  29226. postalmark: 0x3012,
  29227. postalmarkface: 0x3020,
  29228. pparen: 0x24AB,
  29229. precedes: 0x227A,
  29230. prescription: 0x211E,
  29231. primemod: 0x02B9,
  29232. primereversed: 0x2035,
  29233. product: 0x220F,
  29234. projective: 0x2305,
  29235. prolongedkana: 0x30FC,
  29236. propellor: 0x2318,
  29237. propersubset: 0x2282,
  29238. propersuperset: 0x2283,
  29239. proportion: 0x2237,
  29240. proportional: 0x221D,
  29241. psi: 0x03C8,
  29242. psicyrillic: 0x0471,
  29243. psilipneumatacyrilliccmb: 0x0486,
  29244. pssquare: 0x33B0,
  29245. puhiragana: 0x3077,
  29246. pukatakana: 0x30D7,
  29247. pvsquare: 0x33B4,
  29248. pwsquare: 0x33BA,
  29249. q: 0x0071,
  29250. qadeva: 0x0958,
  29251. qadmahebrew: 0x05A8,
  29252. qafarabic: 0x0642,
  29253. qaffinalarabic: 0xFED6,
  29254. qafinitialarabic: 0xFED7,
  29255. qafmedialarabic: 0xFED8,
  29256. qamats: 0x05B8,
  29257. qamats10: 0x05B8,
  29258. qamats1a: 0x05B8,
  29259. qamats1c: 0x05B8,
  29260. qamats27: 0x05B8,
  29261. qamats29: 0x05B8,
  29262. qamats33: 0x05B8,
  29263. qamatsde: 0x05B8,
  29264. qamatshebrew: 0x05B8,
  29265. qamatsnarrowhebrew: 0x05B8,
  29266. qamatsqatanhebrew: 0x05B8,
  29267. qamatsqatannarrowhebrew: 0x05B8,
  29268. qamatsqatanquarterhebrew: 0x05B8,
  29269. qamatsqatanwidehebrew: 0x05B8,
  29270. qamatsquarterhebrew: 0x05B8,
  29271. qamatswidehebrew: 0x05B8,
  29272. qarneyparahebrew: 0x059F,
  29273. qbopomofo: 0x3111,
  29274. qcircle: 0x24E0,
  29275. qhook: 0x02A0,
  29276. qmonospace: 0xFF51,
  29277. qof: 0x05E7,
  29278. qofdagesh: 0xFB47,
  29279. qofdageshhebrew: 0xFB47,
  29280. qofhebrew: 0x05E7,
  29281. qparen: 0x24AC,
  29282. quarternote: 0x2669,
  29283. qubuts: 0x05BB,
  29284. qubuts18: 0x05BB,
  29285. qubuts25: 0x05BB,
  29286. qubuts31: 0x05BB,
  29287. qubutshebrew: 0x05BB,
  29288. qubutsnarrowhebrew: 0x05BB,
  29289. qubutsquarterhebrew: 0x05BB,
  29290. qubutswidehebrew: 0x05BB,
  29291. question: 0x003F,
  29292. questionarabic: 0x061F,
  29293. questionarmenian: 0x055E,
  29294. questiondown: 0x00BF,
  29295. questiondownsmall: 0xF7BF,
  29296. questiongreek: 0x037E,
  29297. questionmonospace: 0xFF1F,
  29298. questionsmall: 0xF73F,
  29299. quotedbl: 0x0022,
  29300. quotedblbase: 0x201E,
  29301. quotedblleft: 0x201C,
  29302. quotedblmonospace: 0xFF02,
  29303. quotedblprime: 0x301E,
  29304. quotedblprimereversed: 0x301D,
  29305. quotedblright: 0x201D,
  29306. quoteleft: 0x2018,
  29307. quoteleftreversed: 0x201B,
  29308. quotereversed: 0x201B,
  29309. quoteright: 0x2019,
  29310. quoterightn: 0x0149,
  29311. quotesinglbase: 0x201A,
  29312. quotesingle: 0x0027,
  29313. quotesinglemonospace: 0xFF07,
  29314. r: 0x0072,
  29315. raarmenian: 0x057C,
  29316. rabengali: 0x09B0,
  29317. racute: 0x0155,
  29318. radeva: 0x0930,
  29319. radical: 0x221A,
  29320. radicalex: 0xF8E5,
  29321. radoverssquare: 0x33AE,
  29322. radoverssquaredsquare: 0x33AF,
  29323. radsquare: 0x33AD,
  29324. rafe: 0x05BF,
  29325. rafehebrew: 0x05BF,
  29326. ragujarati: 0x0AB0,
  29327. ragurmukhi: 0x0A30,
  29328. rahiragana: 0x3089,
  29329. rakatakana: 0x30E9,
  29330. rakatakanahalfwidth: 0xFF97,
  29331. ralowerdiagonalbengali: 0x09F1,
  29332. ramiddlediagonalbengali: 0x09F0,
  29333. ramshorn: 0x0264,
  29334. ratio: 0x2236,
  29335. rbopomofo: 0x3116,
  29336. rcaron: 0x0159,
  29337. rcedilla: 0x0157,
  29338. rcircle: 0x24E1,
  29339. rcommaaccent: 0x0157,
  29340. rdblgrave: 0x0211,
  29341. rdotaccent: 0x1E59,
  29342. rdotbelow: 0x1E5B,
  29343. rdotbelowmacron: 0x1E5D,
  29344. referencemark: 0x203B,
  29345. reflexsubset: 0x2286,
  29346. reflexsuperset: 0x2287,
  29347. registered: 0x00AE,
  29348. registersans: 0xF8E8,
  29349. registerserif: 0xF6DA,
  29350. reharabic: 0x0631,
  29351. reharmenian: 0x0580,
  29352. rehfinalarabic: 0xFEAE,
  29353. rehiragana: 0x308C,
  29354. rekatakana: 0x30EC,
  29355. rekatakanahalfwidth: 0xFF9A,
  29356. resh: 0x05E8,
  29357. reshdageshhebrew: 0xFB48,
  29358. reshhebrew: 0x05E8,
  29359. reversedtilde: 0x223D,
  29360. reviahebrew: 0x0597,
  29361. reviamugrashhebrew: 0x0597,
  29362. revlogicalnot: 0x2310,
  29363. rfishhook: 0x027E,
  29364. rfishhookreversed: 0x027F,
  29365. rhabengali: 0x09DD,
  29366. rhadeva: 0x095D,
  29367. rho: 0x03C1,
  29368. rhook: 0x027D,
  29369. rhookturned: 0x027B,
  29370. rhookturnedsuperior: 0x02B5,
  29371. rhosymbolgreek: 0x03F1,
  29372. rhotichookmod: 0x02DE,
  29373. rieulacirclekorean: 0x3271,
  29374. rieulaparenkorean: 0x3211,
  29375. rieulcirclekorean: 0x3263,
  29376. rieulhieuhkorean: 0x3140,
  29377. rieulkiyeokkorean: 0x313A,
  29378. rieulkiyeoksioskorean: 0x3169,
  29379. rieulkorean: 0x3139,
  29380. rieulmieumkorean: 0x313B,
  29381. rieulpansioskorean: 0x316C,
  29382. rieulparenkorean: 0x3203,
  29383. rieulphieuphkorean: 0x313F,
  29384. rieulpieupkorean: 0x313C,
  29385. rieulpieupsioskorean: 0x316B,
  29386. rieulsioskorean: 0x313D,
  29387. rieulthieuthkorean: 0x313E,
  29388. rieultikeutkorean: 0x316A,
  29389. rieulyeorinhieuhkorean: 0x316D,
  29390. rightangle: 0x221F,
  29391. righttackbelowcmb: 0x0319,
  29392. righttriangle: 0x22BF,
  29393. rihiragana: 0x308A,
  29394. rikatakana: 0x30EA,
  29395. rikatakanahalfwidth: 0xFF98,
  29396. ring: 0x02DA,
  29397. ringbelowcmb: 0x0325,
  29398. ringcmb: 0x030A,
  29399. ringhalfleft: 0x02BF,
  29400. ringhalfleftarmenian: 0x0559,
  29401. ringhalfleftbelowcmb: 0x031C,
  29402. ringhalfleftcentered: 0x02D3,
  29403. ringhalfright: 0x02BE,
  29404. ringhalfrightbelowcmb: 0x0339,
  29405. ringhalfrightcentered: 0x02D2,
  29406. rinvertedbreve: 0x0213,
  29407. rittorusquare: 0x3351,
  29408. rlinebelow: 0x1E5F,
  29409. rlongleg: 0x027C,
  29410. rlonglegturned: 0x027A,
  29411. rmonospace: 0xFF52,
  29412. rohiragana: 0x308D,
  29413. rokatakana: 0x30ED,
  29414. rokatakanahalfwidth: 0xFF9B,
  29415. roruathai: 0x0E23,
  29416. rparen: 0x24AD,
  29417. rrabengali: 0x09DC,
  29418. rradeva: 0x0931,
  29419. rragurmukhi: 0x0A5C,
  29420. rreharabic: 0x0691,
  29421. rrehfinalarabic: 0xFB8D,
  29422. rrvocalicbengali: 0x09E0,
  29423. rrvocalicdeva: 0x0960,
  29424. rrvocalicgujarati: 0x0AE0,
  29425. rrvocalicvowelsignbengali: 0x09C4,
  29426. rrvocalicvowelsigndeva: 0x0944,
  29427. rrvocalicvowelsigngujarati: 0x0AC4,
  29428. rsuperior: 0xF6F1,
  29429. rtblock: 0x2590,
  29430. rturned: 0x0279,
  29431. rturnedsuperior: 0x02B4,
  29432. ruhiragana: 0x308B,
  29433. rukatakana: 0x30EB,
  29434. rukatakanahalfwidth: 0xFF99,
  29435. rupeemarkbengali: 0x09F2,
  29436. rupeesignbengali: 0x09F3,
  29437. rupiah: 0xF6DD,
  29438. ruthai: 0x0E24,
  29439. rvocalicbengali: 0x098B,
  29440. rvocalicdeva: 0x090B,
  29441. rvocalicgujarati: 0x0A8B,
  29442. rvocalicvowelsignbengali: 0x09C3,
  29443. rvocalicvowelsigndeva: 0x0943,
  29444. rvocalicvowelsigngujarati: 0x0AC3,
  29445. s: 0x0073,
  29446. sabengali: 0x09B8,
  29447. sacute: 0x015B,
  29448. sacutedotaccent: 0x1E65,
  29449. sadarabic: 0x0635,
  29450. sadeva: 0x0938,
  29451. sadfinalarabic: 0xFEBA,
  29452. sadinitialarabic: 0xFEBB,
  29453. sadmedialarabic: 0xFEBC,
  29454. sagujarati: 0x0AB8,
  29455. sagurmukhi: 0x0A38,
  29456. sahiragana: 0x3055,
  29457. sakatakana: 0x30B5,
  29458. sakatakanahalfwidth: 0xFF7B,
  29459. sallallahoualayhewasallamarabic: 0xFDFA,
  29460. samekh: 0x05E1,
  29461. samekhdagesh: 0xFB41,
  29462. samekhdageshhebrew: 0xFB41,
  29463. samekhhebrew: 0x05E1,
  29464. saraaathai: 0x0E32,
  29465. saraaethai: 0x0E41,
  29466. saraaimaimalaithai: 0x0E44,
  29467. saraaimaimuanthai: 0x0E43,
  29468. saraamthai: 0x0E33,
  29469. saraathai: 0x0E30,
  29470. saraethai: 0x0E40,
  29471. saraiileftthai: 0xF886,
  29472. saraiithai: 0x0E35,
  29473. saraileftthai: 0xF885,
  29474. saraithai: 0x0E34,
  29475. saraothai: 0x0E42,
  29476. saraueeleftthai: 0xF888,
  29477. saraueethai: 0x0E37,
  29478. saraueleftthai: 0xF887,
  29479. sarauethai: 0x0E36,
  29480. sarauthai: 0x0E38,
  29481. sarauuthai: 0x0E39,
  29482. sbopomofo: 0x3119,
  29483. scaron: 0x0161,
  29484. scarondotaccent: 0x1E67,
  29485. scedilla: 0x015F,
  29486. schwa: 0x0259,
  29487. schwacyrillic: 0x04D9,
  29488. schwadieresiscyrillic: 0x04DB,
  29489. schwahook: 0x025A,
  29490. scircle: 0x24E2,
  29491. scircumflex: 0x015D,
  29492. scommaaccent: 0x0219,
  29493. sdotaccent: 0x1E61,
  29494. sdotbelow: 0x1E63,
  29495. sdotbelowdotaccent: 0x1E69,
  29496. seagullbelowcmb: 0x033C,
  29497. second: 0x2033,
  29498. secondtonechinese: 0x02CA,
  29499. section: 0x00A7,
  29500. seenarabic: 0x0633,
  29501. seenfinalarabic: 0xFEB2,
  29502. seeninitialarabic: 0xFEB3,
  29503. seenmedialarabic: 0xFEB4,
  29504. segol: 0x05B6,
  29505. segol13: 0x05B6,
  29506. segol1f: 0x05B6,
  29507. segol2c: 0x05B6,
  29508. segolhebrew: 0x05B6,
  29509. segolnarrowhebrew: 0x05B6,
  29510. segolquarterhebrew: 0x05B6,
  29511. segoltahebrew: 0x0592,
  29512. segolwidehebrew: 0x05B6,
  29513. seharmenian: 0x057D,
  29514. sehiragana: 0x305B,
  29515. sekatakana: 0x30BB,
  29516. sekatakanahalfwidth: 0xFF7E,
  29517. semicolon: 0x003B,
  29518. semicolonarabic: 0x061B,
  29519. semicolonmonospace: 0xFF1B,
  29520. semicolonsmall: 0xFE54,
  29521. semivoicedmarkkana: 0x309C,
  29522. semivoicedmarkkanahalfwidth: 0xFF9F,
  29523. sentisquare: 0x3322,
  29524. sentosquare: 0x3323,
  29525. seven: 0x0037,
  29526. sevenarabic: 0x0667,
  29527. sevenbengali: 0x09ED,
  29528. sevencircle: 0x2466,
  29529. sevencircleinversesansserif: 0x2790,
  29530. sevendeva: 0x096D,
  29531. seveneighths: 0x215E,
  29532. sevengujarati: 0x0AED,
  29533. sevengurmukhi: 0x0A6D,
  29534. sevenhackarabic: 0x0667,
  29535. sevenhangzhou: 0x3027,
  29536. sevenideographicparen: 0x3226,
  29537. seveninferior: 0x2087,
  29538. sevenmonospace: 0xFF17,
  29539. sevenoldstyle: 0xF737,
  29540. sevenparen: 0x247A,
  29541. sevenperiod: 0x248E,
  29542. sevenpersian: 0x06F7,
  29543. sevenroman: 0x2176,
  29544. sevensuperior: 0x2077,
  29545. seventeencircle: 0x2470,
  29546. seventeenparen: 0x2484,
  29547. seventeenperiod: 0x2498,
  29548. seventhai: 0x0E57,
  29549. sfthyphen: 0x00AD,
  29550. shaarmenian: 0x0577,
  29551. shabengali: 0x09B6,
  29552. shacyrillic: 0x0448,
  29553. shaddaarabic: 0x0651,
  29554. shaddadammaarabic: 0xFC61,
  29555. shaddadammatanarabic: 0xFC5E,
  29556. shaddafathaarabic: 0xFC60,
  29557. shaddakasraarabic: 0xFC62,
  29558. shaddakasratanarabic: 0xFC5F,
  29559. shade: 0x2592,
  29560. shadedark: 0x2593,
  29561. shadelight: 0x2591,
  29562. shademedium: 0x2592,
  29563. shadeva: 0x0936,
  29564. shagujarati: 0x0AB6,
  29565. shagurmukhi: 0x0A36,
  29566. shalshelethebrew: 0x0593,
  29567. shbopomofo: 0x3115,
  29568. shchacyrillic: 0x0449,
  29569. sheenarabic: 0x0634,
  29570. sheenfinalarabic: 0xFEB6,
  29571. sheeninitialarabic: 0xFEB7,
  29572. sheenmedialarabic: 0xFEB8,
  29573. sheicoptic: 0x03E3,
  29574. sheqel: 0x20AA,
  29575. sheqelhebrew: 0x20AA,
  29576. sheva: 0x05B0,
  29577. sheva115: 0x05B0,
  29578. sheva15: 0x05B0,
  29579. sheva22: 0x05B0,
  29580. sheva2e: 0x05B0,
  29581. shevahebrew: 0x05B0,
  29582. shevanarrowhebrew: 0x05B0,
  29583. shevaquarterhebrew: 0x05B0,
  29584. shevawidehebrew: 0x05B0,
  29585. shhacyrillic: 0x04BB,
  29586. shimacoptic: 0x03ED,
  29587. shin: 0x05E9,
  29588. shindagesh: 0xFB49,
  29589. shindageshhebrew: 0xFB49,
  29590. shindageshshindot: 0xFB2C,
  29591. shindageshshindothebrew: 0xFB2C,
  29592. shindageshsindot: 0xFB2D,
  29593. shindageshsindothebrew: 0xFB2D,
  29594. shindothebrew: 0x05C1,
  29595. shinhebrew: 0x05E9,
  29596. shinshindot: 0xFB2A,
  29597. shinshindothebrew: 0xFB2A,
  29598. shinsindot: 0xFB2B,
  29599. shinsindothebrew: 0xFB2B,
  29600. shook: 0x0282,
  29601. sigma: 0x03C3,
  29602. sigma1: 0x03C2,
  29603. sigmafinal: 0x03C2,
  29604. sigmalunatesymbolgreek: 0x03F2,
  29605. sihiragana: 0x3057,
  29606. sikatakana: 0x30B7,
  29607. sikatakanahalfwidth: 0xFF7C,
  29608. siluqhebrew: 0x05BD,
  29609. siluqlefthebrew: 0x05BD,
  29610. similar: 0x223C,
  29611. sindothebrew: 0x05C2,
  29612. siosacirclekorean: 0x3274,
  29613. siosaparenkorean: 0x3214,
  29614. sioscieuckorean: 0x317E,
  29615. sioscirclekorean: 0x3266,
  29616. sioskiyeokkorean: 0x317A,
  29617. sioskorean: 0x3145,
  29618. siosnieunkorean: 0x317B,
  29619. siosparenkorean: 0x3206,
  29620. siospieupkorean: 0x317D,
  29621. siostikeutkorean: 0x317C,
  29622. six: 0x0036,
  29623. sixarabic: 0x0666,
  29624. sixbengali: 0x09EC,
  29625. sixcircle: 0x2465,
  29626. sixcircleinversesansserif: 0x278F,
  29627. sixdeva: 0x096C,
  29628. sixgujarati: 0x0AEC,
  29629. sixgurmukhi: 0x0A6C,
  29630. sixhackarabic: 0x0666,
  29631. sixhangzhou: 0x3026,
  29632. sixideographicparen: 0x3225,
  29633. sixinferior: 0x2086,
  29634. sixmonospace: 0xFF16,
  29635. sixoldstyle: 0xF736,
  29636. sixparen: 0x2479,
  29637. sixperiod: 0x248D,
  29638. sixpersian: 0x06F6,
  29639. sixroman: 0x2175,
  29640. sixsuperior: 0x2076,
  29641. sixteencircle: 0x246F,
  29642. sixteencurrencydenominatorbengali: 0x09F9,
  29643. sixteenparen: 0x2483,
  29644. sixteenperiod: 0x2497,
  29645. sixthai: 0x0E56,
  29646. slash: 0x002F,
  29647. slashmonospace: 0xFF0F,
  29648. slong: 0x017F,
  29649. slongdotaccent: 0x1E9B,
  29650. smileface: 0x263A,
  29651. smonospace: 0xFF53,
  29652. sofpasuqhebrew: 0x05C3,
  29653. softhyphen: 0x00AD,
  29654. softsigncyrillic: 0x044C,
  29655. sohiragana: 0x305D,
  29656. sokatakana: 0x30BD,
  29657. sokatakanahalfwidth: 0xFF7F,
  29658. soliduslongoverlaycmb: 0x0338,
  29659. solidusshortoverlaycmb: 0x0337,
  29660. sorusithai: 0x0E29,
  29661. sosalathai: 0x0E28,
  29662. sosothai: 0x0E0B,
  29663. sosuathai: 0x0E2A,
  29664. space: 0x0020,
  29665. spacehackarabic: 0x0020,
  29666. spade: 0x2660,
  29667. spadesuitblack: 0x2660,
  29668. spadesuitwhite: 0x2664,
  29669. sparen: 0x24AE,
  29670. squarebelowcmb: 0x033B,
  29671. squarecc: 0x33C4,
  29672. squarecm: 0x339D,
  29673. squarediagonalcrosshatchfill: 0x25A9,
  29674. squarehorizontalfill: 0x25A4,
  29675. squarekg: 0x338F,
  29676. squarekm: 0x339E,
  29677. squarekmcapital: 0x33CE,
  29678. squareln: 0x33D1,
  29679. squarelog: 0x33D2,
  29680. squaremg: 0x338E,
  29681. squaremil: 0x33D5,
  29682. squaremm: 0x339C,
  29683. squaremsquared: 0x33A1,
  29684. squareorthogonalcrosshatchfill: 0x25A6,
  29685. squareupperlefttolowerrightfill: 0x25A7,
  29686. squareupperrighttolowerleftfill: 0x25A8,
  29687. squareverticalfill: 0x25A5,
  29688. squarewhitewithsmallblack: 0x25A3,
  29689. srsquare: 0x33DB,
  29690. ssabengali: 0x09B7,
  29691. ssadeva: 0x0937,
  29692. ssagujarati: 0x0AB7,
  29693. ssangcieuckorean: 0x3149,
  29694. ssanghieuhkorean: 0x3185,
  29695. ssangieungkorean: 0x3180,
  29696. ssangkiyeokkorean: 0x3132,
  29697. ssangnieunkorean: 0x3165,
  29698. ssangpieupkorean: 0x3143,
  29699. ssangsioskorean: 0x3146,
  29700. ssangtikeutkorean: 0x3138,
  29701. ssuperior: 0xF6F2,
  29702. sterling: 0x00A3,
  29703. sterlingmonospace: 0xFFE1,
  29704. strokelongoverlaycmb: 0x0336,
  29705. strokeshortoverlaycmb: 0x0335,
  29706. subset: 0x2282,
  29707. subsetnotequal: 0x228A,
  29708. subsetorequal: 0x2286,
  29709. succeeds: 0x227B,
  29710. suchthat: 0x220B,
  29711. suhiragana: 0x3059,
  29712. sukatakana: 0x30B9,
  29713. sukatakanahalfwidth: 0xFF7D,
  29714. sukunarabic: 0x0652,
  29715. summation: 0x2211,
  29716. sun: 0x263C,
  29717. superset: 0x2283,
  29718. supersetnotequal: 0x228B,
  29719. supersetorequal: 0x2287,
  29720. svsquare: 0x33DC,
  29721. syouwaerasquare: 0x337C,
  29722. t: 0x0074,
  29723. tabengali: 0x09A4,
  29724. tackdown: 0x22A4,
  29725. tackleft: 0x22A3,
  29726. tadeva: 0x0924,
  29727. tagujarati: 0x0AA4,
  29728. tagurmukhi: 0x0A24,
  29729. taharabic: 0x0637,
  29730. tahfinalarabic: 0xFEC2,
  29731. tahinitialarabic: 0xFEC3,
  29732. tahiragana: 0x305F,
  29733. tahmedialarabic: 0xFEC4,
  29734. taisyouerasquare: 0x337D,
  29735. takatakana: 0x30BF,
  29736. takatakanahalfwidth: 0xFF80,
  29737. tatweelarabic: 0x0640,
  29738. tau: 0x03C4,
  29739. tav: 0x05EA,
  29740. tavdages: 0xFB4A,
  29741. tavdagesh: 0xFB4A,
  29742. tavdageshhebrew: 0xFB4A,
  29743. tavhebrew: 0x05EA,
  29744. tbar: 0x0167,
  29745. tbopomofo: 0x310A,
  29746. tcaron: 0x0165,
  29747. tccurl: 0x02A8,
  29748. tcedilla: 0x0163,
  29749. tcheharabic: 0x0686,
  29750. tchehfinalarabic: 0xFB7B,
  29751. tchehinitialarabic: 0xFB7C,
  29752. tchehmedialarabic: 0xFB7D,
  29753. tcircle: 0x24E3,
  29754. tcircumflexbelow: 0x1E71,
  29755. tcommaaccent: 0x0163,
  29756. tdieresis: 0x1E97,
  29757. tdotaccent: 0x1E6B,
  29758. tdotbelow: 0x1E6D,
  29759. tecyrillic: 0x0442,
  29760. tedescendercyrillic: 0x04AD,
  29761. teharabic: 0x062A,
  29762. tehfinalarabic: 0xFE96,
  29763. tehhahinitialarabic: 0xFCA2,
  29764. tehhahisolatedarabic: 0xFC0C,
  29765. tehinitialarabic: 0xFE97,
  29766. tehiragana: 0x3066,
  29767. tehjeeminitialarabic: 0xFCA1,
  29768. tehjeemisolatedarabic: 0xFC0B,
  29769. tehmarbutaarabic: 0x0629,
  29770. tehmarbutafinalarabic: 0xFE94,
  29771. tehmedialarabic: 0xFE98,
  29772. tehmeeminitialarabic: 0xFCA4,
  29773. tehmeemisolatedarabic: 0xFC0E,
  29774. tehnoonfinalarabic: 0xFC73,
  29775. tekatakana: 0x30C6,
  29776. tekatakanahalfwidth: 0xFF83,
  29777. telephone: 0x2121,
  29778. telephoneblack: 0x260E,
  29779. telishagedolahebrew: 0x05A0,
  29780. telishaqetanahebrew: 0x05A9,
  29781. tencircle: 0x2469,
  29782. tenideographicparen: 0x3229,
  29783. tenparen: 0x247D,
  29784. tenperiod: 0x2491,
  29785. tenroman: 0x2179,
  29786. tesh: 0x02A7,
  29787. tet: 0x05D8,
  29788. tetdagesh: 0xFB38,
  29789. tetdageshhebrew: 0xFB38,
  29790. tethebrew: 0x05D8,
  29791. tetsecyrillic: 0x04B5,
  29792. tevirhebrew: 0x059B,
  29793. tevirlefthebrew: 0x059B,
  29794. thabengali: 0x09A5,
  29795. thadeva: 0x0925,
  29796. thagujarati: 0x0AA5,
  29797. thagurmukhi: 0x0A25,
  29798. thalarabic: 0x0630,
  29799. thalfinalarabic: 0xFEAC,
  29800. thanthakhatlowleftthai: 0xF898,
  29801. thanthakhatlowrightthai: 0xF897,
  29802. thanthakhatthai: 0x0E4C,
  29803. thanthakhatupperleftthai: 0xF896,
  29804. theharabic: 0x062B,
  29805. thehfinalarabic: 0xFE9A,
  29806. thehinitialarabic: 0xFE9B,
  29807. thehmedialarabic: 0xFE9C,
  29808. thereexists: 0x2203,
  29809. therefore: 0x2234,
  29810. theta: 0x03B8,
  29811. theta1: 0x03D1,
  29812. thetasymbolgreek: 0x03D1,
  29813. thieuthacirclekorean: 0x3279,
  29814. thieuthaparenkorean: 0x3219,
  29815. thieuthcirclekorean: 0x326B,
  29816. thieuthkorean: 0x314C,
  29817. thieuthparenkorean: 0x320B,
  29818. thirteencircle: 0x246C,
  29819. thirteenparen: 0x2480,
  29820. thirteenperiod: 0x2494,
  29821. thonangmonthothai: 0x0E11,
  29822. thook: 0x01AD,
  29823. thophuthaothai: 0x0E12,
  29824. thorn: 0x00FE,
  29825. thothahanthai: 0x0E17,
  29826. thothanthai: 0x0E10,
  29827. thothongthai: 0x0E18,
  29828. thothungthai: 0x0E16,
  29829. thousandcyrillic: 0x0482,
  29830. thousandsseparatorarabic: 0x066C,
  29831. thousandsseparatorpersian: 0x066C,
  29832. three: 0x0033,
  29833. threearabic: 0x0663,
  29834. threebengali: 0x09E9,
  29835. threecircle: 0x2462,
  29836. threecircleinversesansserif: 0x278C,
  29837. threedeva: 0x0969,
  29838. threeeighths: 0x215C,
  29839. threegujarati: 0x0AE9,
  29840. threegurmukhi: 0x0A69,
  29841. threehackarabic: 0x0663,
  29842. threehangzhou: 0x3023,
  29843. threeideographicparen: 0x3222,
  29844. threeinferior: 0x2083,
  29845. threemonospace: 0xFF13,
  29846. threenumeratorbengali: 0x09F6,
  29847. threeoldstyle: 0xF733,
  29848. threeparen: 0x2476,
  29849. threeperiod: 0x248A,
  29850. threepersian: 0x06F3,
  29851. threequarters: 0x00BE,
  29852. threequartersemdash: 0xF6DE,
  29853. threeroman: 0x2172,
  29854. threesuperior: 0x00B3,
  29855. threethai: 0x0E53,
  29856. thzsquare: 0x3394,
  29857. tihiragana: 0x3061,
  29858. tikatakana: 0x30C1,
  29859. tikatakanahalfwidth: 0xFF81,
  29860. tikeutacirclekorean: 0x3270,
  29861. tikeutaparenkorean: 0x3210,
  29862. tikeutcirclekorean: 0x3262,
  29863. tikeutkorean: 0x3137,
  29864. tikeutparenkorean: 0x3202,
  29865. tilde: 0x02DC,
  29866. tildebelowcmb: 0x0330,
  29867. tildecmb: 0x0303,
  29868. tildecomb: 0x0303,
  29869. tildedoublecmb: 0x0360,
  29870. tildeoperator: 0x223C,
  29871. tildeoverlaycmb: 0x0334,
  29872. tildeverticalcmb: 0x033E,
  29873. timescircle: 0x2297,
  29874. tipehahebrew: 0x0596,
  29875. tipehalefthebrew: 0x0596,
  29876. tippigurmukhi: 0x0A70,
  29877. titlocyrilliccmb: 0x0483,
  29878. tiwnarmenian: 0x057F,
  29879. tlinebelow: 0x1E6F,
  29880. tmonospace: 0xFF54,
  29881. toarmenian: 0x0569,
  29882. tohiragana: 0x3068,
  29883. tokatakana: 0x30C8,
  29884. tokatakanahalfwidth: 0xFF84,
  29885. tonebarextrahighmod: 0x02E5,
  29886. tonebarextralowmod: 0x02E9,
  29887. tonebarhighmod: 0x02E6,
  29888. tonebarlowmod: 0x02E8,
  29889. tonebarmidmod: 0x02E7,
  29890. tonefive: 0x01BD,
  29891. tonesix: 0x0185,
  29892. tonetwo: 0x01A8,
  29893. tonos: 0x0384,
  29894. tonsquare: 0x3327,
  29895. topatakthai: 0x0E0F,
  29896. tortoiseshellbracketleft: 0x3014,
  29897. tortoiseshellbracketleftsmall: 0xFE5D,
  29898. tortoiseshellbracketleftvertical: 0xFE39,
  29899. tortoiseshellbracketright: 0x3015,
  29900. tortoiseshellbracketrightsmall: 0xFE5E,
  29901. tortoiseshellbracketrightvertical: 0xFE3A,
  29902. totaothai: 0x0E15,
  29903. tpalatalhook: 0x01AB,
  29904. tparen: 0x24AF,
  29905. trademark: 0x2122,
  29906. trademarksans: 0xF8EA,
  29907. trademarkserif: 0xF6DB,
  29908. tretroflexhook: 0x0288,
  29909. triagdn: 0x25BC,
  29910. triaglf: 0x25C4,
  29911. triagrt: 0x25BA,
  29912. triagup: 0x25B2,
  29913. ts: 0x02A6,
  29914. tsadi: 0x05E6,
  29915. tsadidagesh: 0xFB46,
  29916. tsadidageshhebrew: 0xFB46,
  29917. tsadihebrew: 0x05E6,
  29918. tsecyrillic: 0x0446,
  29919. tsere: 0x05B5,
  29920. tsere12: 0x05B5,
  29921. tsere1e: 0x05B5,
  29922. tsere2b: 0x05B5,
  29923. tserehebrew: 0x05B5,
  29924. tserenarrowhebrew: 0x05B5,
  29925. tserequarterhebrew: 0x05B5,
  29926. tserewidehebrew: 0x05B5,
  29927. tshecyrillic: 0x045B,
  29928. tsuperior: 0xF6F3,
  29929. ttabengali: 0x099F,
  29930. ttadeva: 0x091F,
  29931. ttagujarati: 0x0A9F,
  29932. ttagurmukhi: 0x0A1F,
  29933. tteharabic: 0x0679,
  29934. ttehfinalarabic: 0xFB67,
  29935. ttehinitialarabic: 0xFB68,
  29936. ttehmedialarabic: 0xFB69,
  29937. tthabengali: 0x09A0,
  29938. tthadeva: 0x0920,
  29939. tthagujarati: 0x0AA0,
  29940. tthagurmukhi: 0x0A20,
  29941. tturned: 0x0287,
  29942. tuhiragana: 0x3064,
  29943. tukatakana: 0x30C4,
  29944. tukatakanahalfwidth: 0xFF82,
  29945. tusmallhiragana: 0x3063,
  29946. tusmallkatakana: 0x30C3,
  29947. tusmallkatakanahalfwidth: 0xFF6F,
  29948. twelvecircle: 0x246B,
  29949. twelveparen: 0x247F,
  29950. twelveperiod: 0x2493,
  29951. twelveroman: 0x217B,
  29952. twentycircle: 0x2473,
  29953. twentyhangzhou: 0x5344,
  29954. twentyparen: 0x2487,
  29955. twentyperiod: 0x249B,
  29956. two: 0x0032,
  29957. twoarabic: 0x0662,
  29958. twobengali: 0x09E8,
  29959. twocircle: 0x2461,
  29960. twocircleinversesansserif: 0x278B,
  29961. twodeva: 0x0968,
  29962. twodotenleader: 0x2025,
  29963. twodotleader: 0x2025,
  29964. twodotleadervertical: 0xFE30,
  29965. twogujarati: 0x0AE8,
  29966. twogurmukhi: 0x0A68,
  29967. twohackarabic: 0x0662,
  29968. twohangzhou: 0x3022,
  29969. twoideographicparen: 0x3221,
  29970. twoinferior: 0x2082,
  29971. twomonospace: 0xFF12,
  29972. twonumeratorbengali: 0x09F5,
  29973. twooldstyle: 0xF732,
  29974. twoparen: 0x2475,
  29975. twoperiod: 0x2489,
  29976. twopersian: 0x06F2,
  29977. tworoman: 0x2171,
  29978. twostroke: 0x01BB,
  29979. twosuperior: 0x00B2,
  29980. twothai: 0x0E52,
  29981. twothirds: 0x2154,
  29982. u: 0x0075,
  29983. uacute: 0x00FA,
  29984. ubar: 0x0289,
  29985. ubengali: 0x0989,
  29986. ubopomofo: 0x3128,
  29987. ubreve: 0x016D,
  29988. ucaron: 0x01D4,
  29989. ucircle: 0x24E4,
  29990. ucircumflex: 0x00FB,
  29991. ucircumflexbelow: 0x1E77,
  29992. ucyrillic: 0x0443,
  29993. udattadeva: 0x0951,
  29994. udblacute: 0x0171,
  29995. udblgrave: 0x0215,
  29996. udeva: 0x0909,
  29997. udieresis: 0x00FC,
  29998. udieresisacute: 0x01D8,
  29999. udieresisbelow: 0x1E73,
  30000. udieresiscaron: 0x01DA,
  30001. udieresiscyrillic: 0x04F1,
  30002. udieresisgrave: 0x01DC,
  30003. udieresismacron: 0x01D6,
  30004. udotbelow: 0x1EE5,
  30005. ugrave: 0x00F9,
  30006. ugujarati: 0x0A89,
  30007. ugurmukhi: 0x0A09,
  30008. uhiragana: 0x3046,
  30009. uhookabove: 0x1EE7,
  30010. uhorn: 0x01B0,
  30011. uhornacute: 0x1EE9,
  30012. uhorndotbelow: 0x1EF1,
  30013. uhorngrave: 0x1EEB,
  30014. uhornhookabove: 0x1EED,
  30015. uhorntilde: 0x1EEF,
  30016. uhungarumlaut: 0x0171,
  30017. uhungarumlautcyrillic: 0x04F3,
  30018. uinvertedbreve: 0x0217,
  30019. ukatakana: 0x30A6,
  30020. ukatakanahalfwidth: 0xFF73,
  30021. ukcyrillic: 0x0479,
  30022. ukorean: 0x315C,
  30023. umacron: 0x016B,
  30024. umacroncyrillic: 0x04EF,
  30025. umacrondieresis: 0x1E7B,
  30026. umatragurmukhi: 0x0A41,
  30027. umonospace: 0xFF55,
  30028. underscore: 0x005F,
  30029. underscoredbl: 0x2017,
  30030. underscoremonospace: 0xFF3F,
  30031. underscorevertical: 0xFE33,
  30032. underscorewavy: 0xFE4F,
  30033. union: 0x222A,
  30034. universal: 0x2200,
  30035. uogonek: 0x0173,
  30036. uparen: 0x24B0,
  30037. upblock: 0x2580,
  30038. upperdothebrew: 0x05C4,
  30039. upsilon: 0x03C5,
  30040. upsilondieresis: 0x03CB,
  30041. upsilondieresistonos: 0x03B0,
  30042. upsilonlatin: 0x028A,
  30043. upsilontonos: 0x03CD,
  30044. uptackbelowcmb: 0x031D,
  30045. uptackmod: 0x02D4,
  30046. uragurmukhi: 0x0A73,
  30047. uring: 0x016F,
  30048. ushortcyrillic: 0x045E,
  30049. usmallhiragana: 0x3045,
  30050. usmallkatakana: 0x30A5,
  30051. usmallkatakanahalfwidth: 0xFF69,
  30052. ustraightcyrillic: 0x04AF,
  30053. ustraightstrokecyrillic: 0x04B1,
  30054. utilde: 0x0169,
  30055. utildeacute: 0x1E79,
  30056. utildebelow: 0x1E75,
  30057. uubengali: 0x098A,
  30058. uudeva: 0x090A,
  30059. uugujarati: 0x0A8A,
  30060. uugurmukhi: 0x0A0A,
  30061. uumatragurmukhi: 0x0A42,
  30062. uuvowelsignbengali: 0x09C2,
  30063. uuvowelsigndeva: 0x0942,
  30064. uuvowelsigngujarati: 0x0AC2,
  30065. uvowelsignbengali: 0x09C1,
  30066. uvowelsigndeva: 0x0941,
  30067. uvowelsigngujarati: 0x0AC1,
  30068. v: 0x0076,
  30069. vadeva: 0x0935,
  30070. vagujarati: 0x0AB5,
  30071. vagurmukhi: 0x0A35,
  30072. vakatakana: 0x30F7,
  30073. vav: 0x05D5,
  30074. vavdagesh: 0xFB35,
  30075. vavdagesh65: 0xFB35,
  30076. vavdageshhebrew: 0xFB35,
  30077. vavhebrew: 0x05D5,
  30078. vavholam: 0xFB4B,
  30079. vavholamhebrew: 0xFB4B,
  30080. vavvavhebrew: 0x05F0,
  30081. vavyodhebrew: 0x05F1,
  30082. vcircle: 0x24E5,
  30083. vdotbelow: 0x1E7F,
  30084. vecyrillic: 0x0432,
  30085. veharabic: 0x06A4,
  30086. vehfinalarabic: 0xFB6B,
  30087. vehinitialarabic: 0xFB6C,
  30088. vehmedialarabic: 0xFB6D,
  30089. vekatakana: 0x30F9,
  30090. venus: 0x2640,
  30091. verticalbar: 0x007C,
  30092. verticallineabovecmb: 0x030D,
  30093. verticallinebelowcmb: 0x0329,
  30094. verticallinelowmod: 0x02CC,
  30095. verticallinemod: 0x02C8,
  30096. vewarmenian: 0x057E,
  30097. vhook: 0x028B,
  30098. vikatakana: 0x30F8,
  30099. viramabengali: 0x09CD,
  30100. viramadeva: 0x094D,
  30101. viramagujarati: 0x0ACD,
  30102. visargabengali: 0x0983,
  30103. visargadeva: 0x0903,
  30104. visargagujarati: 0x0A83,
  30105. vmonospace: 0xFF56,
  30106. voarmenian: 0x0578,
  30107. voicediterationhiragana: 0x309E,
  30108. voicediterationkatakana: 0x30FE,
  30109. voicedmarkkana: 0x309B,
  30110. voicedmarkkanahalfwidth: 0xFF9E,
  30111. vokatakana: 0x30FA,
  30112. vparen: 0x24B1,
  30113. vtilde: 0x1E7D,
  30114. vturned: 0x028C,
  30115. vuhiragana: 0x3094,
  30116. vukatakana: 0x30F4,
  30117. w: 0x0077,
  30118. wacute: 0x1E83,
  30119. waekorean: 0x3159,
  30120. wahiragana: 0x308F,
  30121. wakatakana: 0x30EF,
  30122. wakatakanahalfwidth: 0xFF9C,
  30123. wakorean: 0x3158,
  30124. wasmallhiragana: 0x308E,
  30125. wasmallkatakana: 0x30EE,
  30126. wattosquare: 0x3357,
  30127. wavedash: 0x301C,
  30128. wavyunderscorevertical: 0xFE34,
  30129. wawarabic: 0x0648,
  30130. wawfinalarabic: 0xFEEE,
  30131. wawhamzaabovearabic: 0x0624,
  30132. wawhamzaabovefinalarabic: 0xFE86,
  30133. wbsquare: 0x33DD,
  30134. wcircle: 0x24E6,
  30135. wcircumflex: 0x0175,
  30136. wdieresis: 0x1E85,
  30137. wdotaccent: 0x1E87,
  30138. wdotbelow: 0x1E89,
  30139. wehiragana: 0x3091,
  30140. weierstrass: 0x2118,
  30141. wekatakana: 0x30F1,
  30142. wekorean: 0x315E,
  30143. weokorean: 0x315D,
  30144. wgrave: 0x1E81,
  30145. whitebullet: 0x25E6,
  30146. whitecircle: 0x25CB,
  30147. whitecircleinverse: 0x25D9,
  30148. whitecornerbracketleft: 0x300E,
  30149. whitecornerbracketleftvertical: 0xFE43,
  30150. whitecornerbracketright: 0x300F,
  30151. whitecornerbracketrightvertical: 0xFE44,
  30152. whitediamond: 0x25C7,
  30153. whitediamondcontainingblacksmalldiamond: 0x25C8,
  30154. whitedownpointingsmalltriangle: 0x25BF,
  30155. whitedownpointingtriangle: 0x25BD,
  30156. whiteleftpointingsmalltriangle: 0x25C3,
  30157. whiteleftpointingtriangle: 0x25C1,
  30158. whitelenticularbracketleft: 0x3016,
  30159. whitelenticularbracketright: 0x3017,
  30160. whiterightpointingsmalltriangle: 0x25B9,
  30161. whiterightpointingtriangle: 0x25B7,
  30162. whitesmallsquare: 0x25AB,
  30163. whitesmilingface: 0x263A,
  30164. whitesquare: 0x25A1,
  30165. whitestar: 0x2606,
  30166. whitetelephone: 0x260F,
  30167. whitetortoiseshellbracketleft: 0x3018,
  30168. whitetortoiseshellbracketright: 0x3019,
  30169. whiteuppointingsmalltriangle: 0x25B5,
  30170. whiteuppointingtriangle: 0x25B3,
  30171. wihiragana: 0x3090,
  30172. wikatakana: 0x30F0,
  30173. wikorean: 0x315F,
  30174. wmonospace: 0xFF57,
  30175. wohiragana: 0x3092,
  30176. wokatakana: 0x30F2,
  30177. wokatakanahalfwidth: 0xFF66,
  30178. won: 0x20A9,
  30179. wonmonospace: 0xFFE6,
  30180. wowaenthai: 0x0E27,
  30181. wparen: 0x24B2,
  30182. wring: 0x1E98,
  30183. wsuperior: 0x02B7,
  30184. wturned: 0x028D,
  30185. wynn: 0x01BF,
  30186. x: 0x0078,
  30187. xabovecmb: 0x033D,
  30188. xbopomofo: 0x3112,
  30189. xcircle: 0x24E7,
  30190. xdieresis: 0x1E8D,
  30191. xdotaccent: 0x1E8B,
  30192. xeharmenian: 0x056D,
  30193. xi: 0x03BE,
  30194. xmonospace: 0xFF58,
  30195. xparen: 0x24B3,
  30196. xsuperior: 0x02E3,
  30197. y: 0x0079,
  30198. yaadosquare: 0x334E,
  30199. yabengali: 0x09AF,
  30200. yacute: 0x00FD,
  30201. yadeva: 0x092F,
  30202. yaekorean: 0x3152,
  30203. yagujarati: 0x0AAF,
  30204. yagurmukhi: 0x0A2F,
  30205. yahiragana: 0x3084,
  30206. yakatakana: 0x30E4,
  30207. yakatakanahalfwidth: 0xFF94,
  30208. yakorean: 0x3151,
  30209. yamakkanthai: 0x0E4E,
  30210. yasmallhiragana: 0x3083,
  30211. yasmallkatakana: 0x30E3,
  30212. yasmallkatakanahalfwidth: 0xFF6C,
  30213. yatcyrillic: 0x0463,
  30214. ycircle: 0x24E8,
  30215. ycircumflex: 0x0177,
  30216. ydieresis: 0x00FF,
  30217. ydotaccent: 0x1E8F,
  30218. ydotbelow: 0x1EF5,
  30219. yeharabic: 0x064A,
  30220. yehbarreearabic: 0x06D2,
  30221. yehbarreefinalarabic: 0xFBAF,
  30222. yehfinalarabic: 0xFEF2,
  30223. yehhamzaabovearabic: 0x0626,
  30224. yehhamzaabovefinalarabic: 0xFE8A,
  30225. yehhamzaaboveinitialarabic: 0xFE8B,
  30226. yehhamzaabovemedialarabic: 0xFE8C,
  30227. yehinitialarabic: 0xFEF3,
  30228. yehmedialarabic: 0xFEF4,
  30229. yehmeeminitialarabic: 0xFCDD,
  30230. yehmeemisolatedarabic: 0xFC58,
  30231. yehnoonfinalarabic: 0xFC94,
  30232. yehthreedotsbelowarabic: 0x06D1,
  30233. yekorean: 0x3156,
  30234. yen: 0x00A5,
  30235. yenmonospace: 0xFFE5,
  30236. yeokorean: 0x3155,
  30237. yeorinhieuhkorean: 0x3186,
  30238. yerahbenyomohebrew: 0x05AA,
  30239. yerahbenyomolefthebrew: 0x05AA,
  30240. yericyrillic: 0x044B,
  30241. yerudieresiscyrillic: 0x04F9,
  30242. yesieungkorean: 0x3181,
  30243. yesieungpansioskorean: 0x3183,
  30244. yesieungsioskorean: 0x3182,
  30245. yetivhebrew: 0x059A,
  30246. ygrave: 0x1EF3,
  30247. yhook: 0x01B4,
  30248. yhookabove: 0x1EF7,
  30249. yiarmenian: 0x0575,
  30250. yicyrillic: 0x0457,
  30251. yikorean: 0x3162,
  30252. yinyang: 0x262F,
  30253. yiwnarmenian: 0x0582,
  30254. ymonospace: 0xFF59,
  30255. yod: 0x05D9,
  30256. yoddagesh: 0xFB39,
  30257. yoddageshhebrew: 0xFB39,
  30258. yodhebrew: 0x05D9,
  30259. yodyodhebrew: 0x05F2,
  30260. yodyodpatahhebrew: 0xFB1F,
  30261. yohiragana: 0x3088,
  30262. yoikorean: 0x3189,
  30263. yokatakana: 0x30E8,
  30264. yokatakanahalfwidth: 0xFF96,
  30265. yokorean: 0x315B,
  30266. yosmallhiragana: 0x3087,
  30267. yosmallkatakana: 0x30E7,
  30268. yosmallkatakanahalfwidth: 0xFF6E,
  30269. yotgreek: 0x03F3,
  30270. yoyaekorean: 0x3188,
  30271. yoyakorean: 0x3187,
  30272. yoyakthai: 0x0E22,
  30273. yoyingthai: 0x0E0D,
  30274. yparen: 0x24B4,
  30275. ypogegrammeni: 0x037A,
  30276. ypogegrammenigreekcmb: 0x0345,
  30277. yr: 0x01A6,
  30278. yring: 0x1E99,
  30279. ysuperior: 0x02B8,
  30280. ytilde: 0x1EF9,
  30281. yturned: 0x028E,
  30282. yuhiragana: 0x3086,
  30283. yuikorean: 0x318C,
  30284. yukatakana: 0x30E6,
  30285. yukatakanahalfwidth: 0xFF95,
  30286. yukorean: 0x3160,
  30287. yusbigcyrillic: 0x046B,
  30288. yusbigiotifiedcyrillic: 0x046D,
  30289. yuslittlecyrillic: 0x0467,
  30290. yuslittleiotifiedcyrillic: 0x0469,
  30291. yusmallhiragana: 0x3085,
  30292. yusmallkatakana: 0x30E5,
  30293. yusmallkatakanahalfwidth: 0xFF6D,
  30294. yuyekorean: 0x318B,
  30295. yuyeokorean: 0x318A,
  30296. yyabengali: 0x09DF,
  30297. yyadeva: 0x095F,
  30298. z: 0x007A,
  30299. zaarmenian: 0x0566,
  30300. zacute: 0x017A,
  30301. zadeva: 0x095B,
  30302. zagurmukhi: 0x0A5B,
  30303. zaharabic: 0x0638,
  30304. zahfinalarabic: 0xFEC6,
  30305. zahinitialarabic: 0xFEC7,
  30306. zahiragana: 0x3056,
  30307. zahmedialarabic: 0xFEC8,
  30308. zainarabic: 0x0632,
  30309. zainfinalarabic: 0xFEB0,
  30310. zakatakana: 0x30B6,
  30311. zaqefgadolhebrew: 0x0595,
  30312. zaqefqatanhebrew: 0x0594,
  30313. zarqahebrew: 0x0598,
  30314. zayin: 0x05D6,
  30315. zayindagesh: 0xFB36,
  30316. zayindageshhebrew: 0xFB36,
  30317. zayinhebrew: 0x05D6,
  30318. zbopomofo: 0x3117,
  30319. zcaron: 0x017E,
  30320. zcircle: 0x24E9,
  30321. zcircumflex: 0x1E91,
  30322. zcurl: 0x0291,
  30323. zdot: 0x017C,
  30324. zdotaccent: 0x017C,
  30325. zdotbelow: 0x1E93,
  30326. zecyrillic: 0x0437,
  30327. zedescendercyrillic: 0x0499,
  30328. zedieresiscyrillic: 0x04DF,
  30329. zehiragana: 0x305C,
  30330. zekatakana: 0x30BC,
  30331. zero: 0x0030,
  30332. zeroarabic: 0x0660,
  30333. zerobengali: 0x09E6,
  30334. zerodeva: 0x0966,
  30335. zerogujarati: 0x0AE6,
  30336. zerogurmukhi: 0x0A66,
  30337. zerohackarabic: 0x0660,
  30338. zeroinferior: 0x2080,
  30339. zeromonospace: 0xFF10,
  30340. zerooldstyle: 0xF730,
  30341. zeropersian: 0x06F0,
  30342. zerosuperior: 0x2070,
  30343. zerothai: 0x0E50,
  30344. zerowidthjoiner: 0xFEFF,
  30345. zerowidthnonjoiner: 0x200C,
  30346. zerowidthspace: 0x200B,
  30347. zeta: 0x03B6,
  30348. zhbopomofo: 0x3113,
  30349. zhearmenian: 0x056A,
  30350. zhebrevecyrillic: 0x04C2,
  30351. zhecyrillic: 0x0436,
  30352. zhedescendercyrillic: 0x0497,
  30353. zhedieresiscyrillic: 0x04DD,
  30354. zihiragana: 0x3058,
  30355. zikatakana: 0x30B8,
  30356. zinorhebrew: 0x05AE,
  30357. zlinebelow: 0x1E95,
  30358. zmonospace: 0xFF5A,
  30359. zohiragana: 0x305E,
  30360. zokatakana: 0x30BE,
  30361. zparen: 0x24B5,
  30362. zretroflexhook: 0x0290,
  30363. zstroke: 0x01B6,
  30364. zuhiragana: 0x305A,
  30365. zukatakana: 0x30BA,
  30366. '.notdef': 0x0000
  30367. };
  30368. var DingbatsGlyphsUnicode = {
  30369. space: 0x0020,
  30370. a1: 0x2701,
  30371. a2: 0x2702,
  30372. a202: 0x2703,
  30373. a3: 0x2704,
  30374. a4: 0x260E,
  30375. a5: 0x2706,
  30376. a119: 0x2707,
  30377. a118: 0x2708,
  30378. a117: 0x2709,
  30379. a11: 0x261B,
  30380. a12: 0x261E,
  30381. a13: 0x270C,
  30382. a14: 0x270D,
  30383. a15: 0x270E,
  30384. a16: 0x270F,
  30385. a105: 0x2710,
  30386. a17: 0x2711,
  30387. a18: 0x2712,
  30388. a19: 0x2713,
  30389. a20: 0x2714,
  30390. a21: 0x2715,
  30391. a22: 0x2716,
  30392. a23: 0x2717,
  30393. a24: 0x2718,
  30394. a25: 0x2719,
  30395. a26: 0x271A,
  30396. a27: 0x271B,
  30397. a28: 0x271C,
  30398. a6: 0x271D,
  30399. a7: 0x271E,
  30400. a8: 0x271F,
  30401. a9: 0x2720,
  30402. a10: 0x2721,
  30403. a29: 0x2722,
  30404. a30: 0x2723,
  30405. a31: 0x2724,
  30406. a32: 0x2725,
  30407. a33: 0x2726,
  30408. a34: 0x2727,
  30409. a35: 0x2605,
  30410. a36: 0x2729,
  30411. a37: 0x272A,
  30412. a38: 0x272B,
  30413. a39: 0x272C,
  30414. a40: 0x272D,
  30415. a41: 0x272E,
  30416. a42: 0x272F,
  30417. a43: 0x2730,
  30418. a44: 0x2731,
  30419. a45: 0x2732,
  30420. a46: 0x2733,
  30421. a47: 0x2734,
  30422. a48: 0x2735,
  30423. a49: 0x2736,
  30424. a50: 0x2737,
  30425. a51: 0x2738,
  30426. a52: 0x2739,
  30427. a53: 0x273A,
  30428. a54: 0x273B,
  30429. a55: 0x273C,
  30430. a56: 0x273D,
  30431. a57: 0x273E,
  30432. a58: 0x273F,
  30433. a59: 0x2740,
  30434. a60: 0x2741,
  30435. a61: 0x2742,
  30436. a62: 0x2743,
  30437. a63: 0x2744,
  30438. a64: 0x2745,
  30439. a65: 0x2746,
  30440. a66: 0x2747,
  30441. a67: 0x2748,
  30442. a68: 0x2749,
  30443. a69: 0x274A,
  30444. a70: 0x274B,
  30445. a71: 0x25CF,
  30446. a72: 0x274D,
  30447. a73: 0x25A0,
  30448. a74: 0x274F,
  30449. a203: 0x2750,
  30450. a75: 0x2751,
  30451. a204: 0x2752,
  30452. a76: 0x25B2,
  30453. a77: 0x25BC,
  30454. a78: 0x25C6,
  30455. a79: 0x2756,
  30456. a81: 0x25D7,
  30457. a82: 0x2758,
  30458. a83: 0x2759,
  30459. a84: 0x275A,
  30460. a97: 0x275B,
  30461. a98: 0x275C,
  30462. a99: 0x275D,
  30463. a100: 0x275E,
  30464. a101: 0x2761,
  30465. a102: 0x2762,
  30466. a103: 0x2763,
  30467. a104: 0x2764,
  30468. a106: 0x2765,
  30469. a107: 0x2766,
  30470. a108: 0x2767,
  30471. a112: 0x2663,
  30472. a111: 0x2666,
  30473. a110: 0x2665,
  30474. a109: 0x2660,
  30475. a120: 0x2460,
  30476. a121: 0x2461,
  30477. a122: 0x2462,
  30478. a123: 0x2463,
  30479. a124: 0x2464,
  30480. a125: 0x2465,
  30481. a126: 0x2466,
  30482. a127: 0x2467,
  30483. a128: 0x2468,
  30484. a129: 0x2469,
  30485. a130: 0x2776,
  30486. a131: 0x2777,
  30487. a132: 0x2778,
  30488. a133: 0x2779,
  30489. a134: 0x277A,
  30490. a135: 0x277B,
  30491. a136: 0x277C,
  30492. a137: 0x277D,
  30493. a138: 0x277E,
  30494. a139: 0x277F,
  30495. a140: 0x2780,
  30496. a141: 0x2781,
  30497. a142: 0x2782,
  30498. a143: 0x2783,
  30499. a144: 0x2784,
  30500. a145: 0x2785,
  30501. a146: 0x2786,
  30502. a147: 0x2787,
  30503. a148: 0x2788,
  30504. a149: 0x2789,
  30505. a150: 0x278A,
  30506. a151: 0x278B,
  30507. a152: 0x278C,
  30508. a153: 0x278D,
  30509. a154: 0x278E,
  30510. a155: 0x278F,
  30511. a156: 0x2790,
  30512. a157: 0x2791,
  30513. a158: 0x2792,
  30514. a159: 0x2793,
  30515. a160: 0x2794,
  30516. a161: 0x2192,
  30517. a163: 0x2194,
  30518. a164: 0x2195,
  30519. a196: 0x2798,
  30520. a165: 0x2799,
  30521. a192: 0x279A,
  30522. a166: 0x279B,
  30523. a167: 0x279C,
  30524. a168: 0x279D,
  30525. a169: 0x279E,
  30526. a170: 0x279F,
  30527. a171: 0x27A0,
  30528. a172: 0x27A1,
  30529. a173: 0x27A2,
  30530. a162: 0x27A3,
  30531. a174: 0x27A4,
  30532. a175: 0x27A5,
  30533. a176: 0x27A6,
  30534. a177: 0x27A7,
  30535. a178: 0x27A8,
  30536. a179: 0x27A9,
  30537. a193: 0x27AA,
  30538. a180: 0x27AB,
  30539. a199: 0x27AC,
  30540. a181: 0x27AD,
  30541. a200: 0x27AE,
  30542. a182: 0x27AF,
  30543. a201: 0x27B1,
  30544. a183: 0x27B2,
  30545. a184: 0x27B3,
  30546. a197: 0x27B4,
  30547. a185: 0x27B5,
  30548. a194: 0x27B6,
  30549. a198: 0x27B7,
  30550. a186: 0x27B8,
  30551. a195: 0x27B9,
  30552. a187: 0x27BA,
  30553. a188: 0x27BB,
  30554. a189: 0x27BC,
  30555. a190: 0x27BD,
  30556. a191: 0x27BE,
  30557. a89: 0x2768, // 0xF8D7
  30558. a90: 0x2769, // 0xF8D8
  30559. a93: 0x276A, // 0xF8D9
  30560. a94: 0x276B, // 0xF8DA
  30561. a91: 0x276C, // 0xF8DB
  30562. a92: 0x276D, // 0xF8DC
  30563. a205: 0x276E, // 0xF8DD
  30564. a85: 0x276F, // 0xF8DE
  30565. a206: 0x2770, // 0xF8DF
  30566. a86: 0x2771, // 0xF8E0
  30567. a87: 0x2772, // 0xF8E1
  30568. a88: 0x2773, // 0xF8E2
  30569. a95: 0x2774, // 0xF8E3
  30570. a96: 0x2775, // 0xF8E4
  30571. '.notdef': 0x0000
  30572. };
  30573. var PDFImage = (function PDFImageClosure() {
  30574. /**
  30575. * Decode the image in the main thread if it supported. Resovles the promise
  30576. * when the image data is ready.
  30577. */
  30578. function handleImageData(handler, xref, res, image) {
  30579. if (image instanceof JpegStream && image.isNativelyDecodable(xref, res)) {
  30580. // For natively supported jpegs send them to the main thread for decoding.
  30581. var dict = image.dict;
  30582. var colorSpace = dict.get('ColorSpace', 'CS');
  30583. colorSpace = ColorSpace.parse(colorSpace, xref, res);
  30584. var numComps = colorSpace.numComps;
  30585. var decodePromise = handler.sendWithPromise('JpegDecode',
  30586. [image.getIR(), numComps]);
  30587. return decodePromise.then(function (message) {
  30588. var data = message.data;
  30589. return new Stream(data, 0, data.length, image.dict);
  30590. });
  30591. } else {
  30592. return Promise.resolve(image);
  30593. }
  30594. }
  30595. /**
  30596. * Decode and clamp a value. The formula is different from the spec because we
  30597. * don't decode to float range [0,1], we decode it in the [0,max] range.
  30598. */
  30599. function decodeAndClamp(value, addend, coefficient, max) {
  30600. value = addend + value * coefficient;
  30601. // Clamp the value to the range
  30602. return (value < 0 ? 0 : (value > max ? max : value));
  30603. }
  30604. function PDFImage(xref, res, image, inline, smask, mask, isMask) {
  30605. this.image = image;
  30606. var dict = image.dict;
  30607. if (dict.has('Filter')) {
  30608. var filter = dict.get('Filter').name;
  30609. if (filter === 'JPXDecode') {
  30610. var jpxImage = new JpxImage();
  30611. jpxImage.parseImageProperties(image.stream);
  30612. image.stream.reset();
  30613. image.bitsPerComponent = jpxImage.bitsPerComponent;
  30614. image.numComps = jpxImage.componentsCount;
  30615. } else if (filter === 'JBIG2Decode') {
  30616. image.bitsPerComponent = 1;
  30617. image.numComps = 1;
  30618. }
  30619. }
  30620. // TODO cache rendered images?
  30621. this.width = dict.get('Width', 'W');
  30622. this.height = dict.get('Height', 'H');
  30623. if (this.width < 1 || this.height < 1) {
  30624. error('Invalid image width: ' + this.width + ' or height: ' +
  30625. this.height);
  30626. }
  30627. this.interpolate = dict.get('Interpolate', 'I') || false;
  30628. this.imageMask = dict.get('ImageMask', 'IM') || false;
  30629. this.matte = dict.get('Matte') || false;
  30630. var bitsPerComponent = image.bitsPerComponent;
  30631. if (!bitsPerComponent) {
  30632. bitsPerComponent = dict.get('BitsPerComponent', 'BPC');
  30633. if (!bitsPerComponent) {
  30634. if (this.imageMask) {
  30635. bitsPerComponent = 1;
  30636. } else {
  30637. error('Bits per component missing in image: ' + this.imageMask);
  30638. }
  30639. }
  30640. }
  30641. this.bpc = bitsPerComponent;
  30642. if (!this.imageMask) {
  30643. var colorSpace = dict.get('ColorSpace', 'CS');
  30644. if (!colorSpace) {
  30645. info('JPX images (which do not require color spaces)');
  30646. switch (image.numComps) {
  30647. case 1:
  30648. colorSpace = Name.get('DeviceGray');
  30649. break;
  30650. case 3:
  30651. colorSpace = Name.get('DeviceRGB');
  30652. break;
  30653. case 4:
  30654. colorSpace = Name.get('DeviceCMYK');
  30655. break;
  30656. default:
  30657. error('JPX images with ' + this.numComps +
  30658. ' color components not supported.');
  30659. }
  30660. }
  30661. this.colorSpace = ColorSpace.parse(colorSpace, xref, res);
  30662. this.numComps = this.colorSpace.numComps;
  30663. }
  30664. this.decode = dict.get('Decode', 'D');
  30665. this.needsDecode = false;
  30666. if (this.decode &&
  30667. ((this.colorSpace && !this.colorSpace.isDefaultDecode(this.decode)) ||
  30668. (isMask && !ColorSpace.isDefaultDecode(this.decode, 1)))) {
  30669. this.needsDecode = true;
  30670. // Do some preprocessing to avoid more math.
  30671. var max = (1 << bitsPerComponent) - 1;
  30672. this.decodeCoefficients = [];
  30673. this.decodeAddends = [];
  30674. for (var i = 0, j = 0; i < this.decode.length; i += 2, ++j) {
  30675. var dmin = this.decode[i];
  30676. var dmax = this.decode[i + 1];
  30677. this.decodeCoefficients[j] = dmax - dmin;
  30678. this.decodeAddends[j] = max * dmin;
  30679. }
  30680. }
  30681. if (smask) {
  30682. this.smask = new PDFImage(xref, res, smask, false);
  30683. } else if (mask) {
  30684. if (isStream(mask)) {
  30685. this.mask = new PDFImage(xref, res, mask, false, null, null, true);
  30686. } else {
  30687. // Color key mask (just an array).
  30688. this.mask = mask;
  30689. }
  30690. }
  30691. }
  30692. /**
  30693. * Handles processing of image data and returns the Promise that is resolved
  30694. * with a PDFImage when the image is ready to be used.
  30695. */
  30696. PDFImage.buildImage = function PDFImage_buildImage(handler, xref,
  30697. res, image, inline) {
  30698. var imagePromise = handleImageData(handler, xref, res, image);
  30699. var smaskPromise;
  30700. var maskPromise;
  30701. var smask = image.dict.get('SMask');
  30702. var mask = image.dict.get('Mask');
  30703. if (smask) {
  30704. smaskPromise = handleImageData(handler, xref, res, smask);
  30705. maskPromise = Promise.resolve(null);
  30706. } else {
  30707. smaskPromise = Promise.resolve(null);
  30708. if (mask) {
  30709. if (isStream(mask)) {
  30710. maskPromise = handleImageData(handler, xref, res, mask);
  30711. } else if (isArray(mask)) {
  30712. maskPromise = Promise.resolve(mask);
  30713. } else {
  30714. warn('Unsupported mask format.');
  30715. maskPromise = Promise.resolve(null);
  30716. }
  30717. } else {
  30718. maskPromise = Promise.resolve(null);
  30719. }
  30720. }
  30721. return Promise.all([imagePromise, smaskPromise, maskPromise]).then(
  30722. function(results) {
  30723. var imageData = results[0];
  30724. var smaskData = results[1];
  30725. var maskData = results[2];
  30726. return new PDFImage(xref, res, imageData, inline, smaskData, maskData);
  30727. });
  30728. };
  30729. /**
  30730. * Resize an image using the nearest neighbor algorithm. Currently only
  30731. * supports one and three component images.
  30732. * @param {TypedArray} pixels The original image with one component.
  30733. * @param {Number} bpc Number of bits per component.
  30734. * @param {Number} components Number of color components, 1 or 3 is supported.
  30735. * @param {Number} w1 Original width.
  30736. * @param {Number} h1 Original height.
  30737. * @param {Number} w2 New width.
  30738. * @param {Number} h2 New height.
  30739. * @param {TypedArray} dest (Optional) The destination buffer.
  30740. * @param {Number} alpha01 (Optional) Size reserved for the alpha channel.
  30741. * @return {TypedArray} Resized image data.
  30742. */
  30743. PDFImage.resize = function PDFImage_resize(pixels, bpc, components,
  30744. w1, h1, w2, h2, dest, alpha01) {
  30745. if (components !== 1 && components !== 3) {
  30746. error('Unsupported component count for resizing.');
  30747. }
  30748. var length = w2 * h2 * components;
  30749. var temp = dest ? dest : (bpc <= 8 ? new Uint8Array(length) :
  30750. (bpc <= 16 ? new Uint16Array(length) : new Uint32Array(length)));
  30751. var xRatio = w1 / w2;
  30752. var yRatio = h1 / h2;
  30753. var i, j, py, newIndex = 0, oldIndex;
  30754. var xScaled = new Uint16Array(w2);
  30755. var w1Scanline = w1 * components;
  30756. if (alpha01 !== 1) {
  30757. alpha01 = 0;
  30758. }
  30759. for (j = 0; j < w2; j++) {
  30760. xScaled[j] = Math.floor(j * xRatio) * components;
  30761. }
  30762. if (components === 1) {
  30763. for (i = 0; i < h2; i++) {
  30764. py = Math.floor(i * yRatio) * w1Scanline;
  30765. for (j = 0; j < w2; j++) {
  30766. oldIndex = py + xScaled[j];
  30767. temp[newIndex++] = pixels[oldIndex];
  30768. }
  30769. }
  30770. } else if (components === 3) {
  30771. for (i = 0; i < h2; i++) {
  30772. py = Math.floor(i * yRatio) * w1Scanline;
  30773. for (j = 0; j < w2; j++) {
  30774. oldIndex = py + xScaled[j];
  30775. temp[newIndex++] = pixels[oldIndex++];
  30776. temp[newIndex++] = pixels[oldIndex++];
  30777. temp[newIndex++] = pixels[oldIndex++];
  30778. newIndex += alpha01;
  30779. }
  30780. }
  30781. }
  30782. return temp;
  30783. };
  30784. PDFImage.createMask =
  30785. function PDFImage_createMask(imgArray, width, height,
  30786. imageIsFromDecodeStream, inverseDecode) {
  30787. // |imgArray| might not contain full data for every pixel of the mask, so
  30788. // we need to distinguish between |computedLength| and |actualLength|.
  30789. // In particular, if inverseDecode is true, then the array we return must
  30790. // have a length of |computedLength|.
  30791. var computedLength = ((width + 7) >> 3) * height;
  30792. var actualLength = imgArray.byteLength;
  30793. var haveFullData = computedLength === actualLength;
  30794. var data, i;
  30795. if (imageIsFromDecodeStream && (!inverseDecode || haveFullData)) {
  30796. // imgArray came from a DecodeStream and its data is in an appropriate
  30797. // form, so we can just transfer it.
  30798. data = imgArray;
  30799. } else if (!inverseDecode) {
  30800. data = new Uint8Array(actualLength);
  30801. data.set(imgArray);
  30802. } else {
  30803. data = new Uint8Array(computedLength);
  30804. data.set(imgArray);
  30805. for (i = actualLength; i < computedLength; i++) {
  30806. data[i] = 0xff;
  30807. }
  30808. }
  30809. // If necessary, invert the original mask data (but not any extra we might
  30810. // have added above). It's safe to modify the array -- whether it's the
  30811. // original or a copy, we're about to transfer it anyway, so nothing else
  30812. // in this thread can be relying on its contents.
  30813. if (inverseDecode) {
  30814. for (i = 0; i < actualLength; i++) {
  30815. data[i] = ~data[i];
  30816. }
  30817. }
  30818. return {data: data, width: width, height: height};
  30819. };
  30820. PDFImage.prototype = {
  30821. get drawWidth() {
  30822. return Math.max(this.width,
  30823. this.smask && this.smask.width || 0,
  30824. this.mask && this.mask.width || 0);
  30825. },
  30826. get drawHeight() {
  30827. return Math.max(this.height,
  30828. this.smask && this.smask.height || 0,
  30829. this.mask && this.mask.height || 0);
  30830. },
  30831. decodeBuffer: function PDFImage_decodeBuffer(buffer) {
  30832. var bpc = this.bpc;
  30833. var numComps = this.numComps;
  30834. var decodeAddends = this.decodeAddends;
  30835. var decodeCoefficients = this.decodeCoefficients;
  30836. var max = (1 << bpc) - 1;
  30837. var i, ii;
  30838. if (bpc === 1) {
  30839. // If the buffer needed decode that means it just needs to be inverted.
  30840. for (i = 0, ii = buffer.length; i < ii; i++) {
  30841. buffer[i] = +!(buffer[i]);
  30842. }
  30843. return;
  30844. }
  30845. var index = 0;
  30846. for (i = 0, ii = this.width * this.height; i < ii; i++) {
  30847. for (var j = 0; j < numComps; j++) {
  30848. buffer[index] = decodeAndClamp(buffer[index], decodeAddends[j],
  30849. decodeCoefficients[j], max);
  30850. index++;
  30851. }
  30852. }
  30853. },
  30854. getComponents: function PDFImage_getComponents(buffer) {
  30855. var bpc = this.bpc;
  30856. // This image doesn't require any extra work.
  30857. if (bpc === 8) {
  30858. return buffer;
  30859. }
  30860. var width = this.width;
  30861. var height = this.height;
  30862. var numComps = this.numComps;
  30863. var length = width * height * numComps;
  30864. var bufferPos = 0;
  30865. var output = (bpc <= 8 ? new Uint8Array(length) :
  30866. (bpc <= 16 ? new Uint16Array(length) : new Uint32Array(length)));
  30867. var rowComps = width * numComps;
  30868. var max = (1 << bpc) - 1;
  30869. var i = 0, ii, buf;
  30870. if (bpc === 1) {
  30871. // Optimization for reading 1 bpc images.
  30872. var mask, loop1End, loop2End;
  30873. for (var j = 0; j < height; j++) {
  30874. loop1End = i + (rowComps & ~7);
  30875. loop2End = i + rowComps;
  30876. // unroll loop for all full bytes
  30877. while (i < loop1End) {
  30878. buf = buffer[bufferPos++];
  30879. output[i] = (buf >> 7) & 1;
  30880. output[i + 1] = (buf >> 6) & 1;
  30881. output[i + 2] = (buf >> 5) & 1;
  30882. output[i + 3] = (buf >> 4) & 1;
  30883. output[i + 4] = (buf >> 3) & 1;
  30884. output[i + 5] = (buf >> 2) & 1;
  30885. output[i + 6] = (buf >> 1) & 1;
  30886. output[i + 7] = buf & 1;
  30887. i += 8;
  30888. }
  30889. // handle remaing bits
  30890. if (i < loop2End) {
  30891. buf = buffer[bufferPos++];
  30892. mask = 128;
  30893. while (i < loop2End) {
  30894. output[i++] = +!!(buf & mask);
  30895. mask >>= 1;
  30896. }
  30897. }
  30898. }
  30899. } else {
  30900. // The general case that handles all other bpc values.
  30901. var bits = 0;
  30902. buf = 0;
  30903. for (i = 0, ii = length; i < ii; ++i) {
  30904. if (i % rowComps === 0) {
  30905. buf = 0;
  30906. bits = 0;
  30907. }
  30908. while (bits < bpc) {
  30909. buf = (buf << 8) | buffer[bufferPos++];
  30910. bits += 8;
  30911. }
  30912. var remainingBits = bits - bpc;
  30913. var value = buf >> remainingBits;
  30914. output[i] = (value < 0 ? 0 : (value > max ? max : value));
  30915. buf = buf & ((1 << remainingBits) - 1);
  30916. bits = remainingBits;
  30917. }
  30918. }
  30919. return output;
  30920. },
  30921. fillOpacity: function PDFImage_fillOpacity(rgbaBuf, width, height,
  30922. actualHeight, image) {
  30923. var smask = this.smask;
  30924. var mask = this.mask;
  30925. var alphaBuf, sw, sh, i, ii, j;
  30926. if (smask) {
  30927. sw = smask.width;
  30928. sh = smask.height;
  30929. alphaBuf = new Uint8Array(sw * sh);
  30930. smask.fillGrayBuffer(alphaBuf);
  30931. if (sw !== width || sh !== height) {
  30932. alphaBuf = PDFImage.resize(alphaBuf, smask.bpc, 1, sw, sh, width,
  30933. height);
  30934. }
  30935. } else if (mask) {
  30936. if (mask instanceof PDFImage) {
  30937. sw = mask.width;
  30938. sh = mask.height;
  30939. alphaBuf = new Uint8Array(sw * sh);
  30940. mask.numComps = 1;
  30941. mask.fillGrayBuffer(alphaBuf);
  30942. // Need to invert values in rgbaBuf
  30943. for (i = 0, ii = sw * sh; i < ii; ++i) {
  30944. alphaBuf[i] = 255 - alphaBuf[i];
  30945. }
  30946. if (sw !== width || sh !== height) {
  30947. alphaBuf = PDFImage.resize(alphaBuf, mask.bpc, 1, sw, sh, width,
  30948. height);
  30949. }
  30950. } else if (isArray(mask)) {
  30951. // Color key mask: if any of the compontents are outside the range
  30952. // then they should be painted.
  30953. alphaBuf = new Uint8Array(width * height);
  30954. var numComps = this.numComps;
  30955. for (i = 0, ii = width * height; i < ii; ++i) {
  30956. var opacity = 0;
  30957. var imageOffset = i * numComps;
  30958. for (j = 0; j < numComps; ++j) {
  30959. var color = image[imageOffset + j];
  30960. var maskOffset = j * 2;
  30961. if (color < mask[maskOffset] || color > mask[maskOffset + 1]) {
  30962. opacity = 255;
  30963. break;
  30964. }
  30965. }
  30966. alphaBuf[i] = opacity;
  30967. }
  30968. } else {
  30969. error('Unknown mask format.');
  30970. }
  30971. }
  30972. if (alphaBuf) {
  30973. for (i = 0, j = 3, ii = width * actualHeight; i < ii; ++i, j += 4) {
  30974. rgbaBuf[j] = alphaBuf[i];
  30975. }
  30976. } else {
  30977. // No mask.
  30978. for (i = 0, j = 3, ii = width * actualHeight; i < ii; ++i, j += 4) {
  30979. rgbaBuf[j] = 255;
  30980. }
  30981. }
  30982. },
  30983. undoPreblend: function PDFImage_undoPreblend(buffer, width, height) {
  30984. var matte = this.smask && this.smask.matte;
  30985. if (!matte) {
  30986. return;
  30987. }
  30988. var matteRgb = this.colorSpace.getRgb(matte, 0);
  30989. var matteR = matteRgb[0];
  30990. var matteG = matteRgb[1];
  30991. var matteB = matteRgb[2];
  30992. var length = width * height * 4;
  30993. var r, g, b;
  30994. for (var i = 0; i < length; i += 4) {
  30995. var alpha = buffer[i + 3];
  30996. if (alpha === 0) {
  30997. // according formula we have to get Infinity in all components
  30998. // making it white (typical paper color) should be okay
  30999. buffer[i] = 255;
  31000. buffer[i + 1] = 255;
  31001. buffer[i + 2] = 255;
  31002. continue;
  31003. }
  31004. var k = 255 / alpha;
  31005. r = (buffer[i] - matteR) * k + matteR;
  31006. g = (buffer[i + 1] - matteG) * k + matteG;
  31007. b = (buffer[i + 2] - matteB) * k + matteB;
  31008. buffer[i] = r <= 0 ? 0 : r >= 255 ? 255 : r | 0;
  31009. buffer[i + 1] = g <= 0 ? 0 : g >= 255 ? 255 : g | 0;
  31010. buffer[i + 2] = b <= 0 ? 0 : b >= 255 ? 255 : b | 0;
  31011. }
  31012. },
  31013. createImageData: function PDFImage_createImageData(forceRGBA) {
  31014. var drawWidth = this.drawWidth;
  31015. var drawHeight = this.drawHeight;
  31016. var imgData = { // other fields are filled in below
  31017. width: drawWidth,
  31018. height: drawHeight
  31019. };
  31020. var numComps = this.numComps;
  31021. var originalWidth = this.width;
  31022. var originalHeight = this.height;
  31023. var bpc = this.bpc;
  31024. // Rows start at byte boundary.
  31025. var rowBytes = (originalWidth * numComps * bpc + 7) >> 3;
  31026. var imgArray;
  31027. if (!forceRGBA) {
  31028. // If it is a 1-bit-per-pixel grayscale (i.e. black-and-white) image
  31029. // without any complications, we pass a same-sized copy to the main
  31030. // thread rather than expanding by 32x to RGBA form. This saves *lots*
  31031. // of memory for many scanned documents. It's also much faster.
  31032. //
  31033. // Similarly, if it is a 24-bit-per pixel RGB image without any
  31034. // complications, we avoid expanding by 1.333x to RGBA form.
  31035. var kind;
  31036. if (this.colorSpace.name === 'DeviceGray' && bpc === 1) {
  31037. kind = ImageKind.GRAYSCALE_1BPP;
  31038. } else if (this.colorSpace.name === 'DeviceRGB' && bpc === 8 &&
  31039. !this.needsDecode) {
  31040. kind = ImageKind.RGB_24BPP;
  31041. }
  31042. if (kind && !this.smask && !this.mask &&
  31043. drawWidth === originalWidth && drawHeight === originalHeight) {
  31044. imgData.kind = kind;
  31045. imgArray = this.getImageBytes(originalHeight * rowBytes);
  31046. // If imgArray came from a DecodeStream, we're safe to transfer it
  31047. // (and thus neuter it) because it will constitute the entire
  31048. // DecodeStream's data. But if it came from a Stream, we need to
  31049. // copy it because it'll only be a portion of the Stream's data, and
  31050. // the rest will be read later on.
  31051. if (this.image instanceof DecodeStream) {
  31052. imgData.data = imgArray;
  31053. } else {
  31054. var newArray = new Uint8Array(imgArray.length);
  31055. newArray.set(imgArray);
  31056. imgData.data = newArray;
  31057. }
  31058. if (this.needsDecode) {
  31059. // Invert the buffer (which must be grayscale if we reached here).
  31060. assert(kind === ImageKind.GRAYSCALE_1BPP);
  31061. var buffer = imgData.data;
  31062. for (var i = 0, ii = buffer.length; i < ii; i++) {
  31063. buffer[i] ^= 0xff;
  31064. }
  31065. }
  31066. return imgData;
  31067. }
  31068. if (this.image instanceof JpegStream && !this.smask && !this.mask) {
  31069. imgData.kind = ImageKind.RGB_24BPP;
  31070. imgData.data = this.getImageBytes(originalHeight * rowBytes,
  31071. drawWidth, drawHeight, true);
  31072. return imgData;
  31073. }
  31074. }
  31075. imgArray = this.getImageBytes(originalHeight * rowBytes);
  31076. // imgArray can be incomplete (e.g. after CCITT fax encoding).
  31077. var actualHeight = 0 | (imgArray.length / rowBytes *
  31078. drawHeight / originalHeight);
  31079. var comps = this.getComponents(imgArray);
  31080. // If opacity data is present, use RGBA_32BPP form. Otherwise, use the
  31081. // more compact RGB_24BPP form if allowable.
  31082. var alpha01, maybeUndoPreblend;
  31083. if (!forceRGBA && !this.smask && !this.mask) {
  31084. imgData.kind = ImageKind.RGB_24BPP;
  31085. imgData.data = new Uint8Array(drawWidth * drawHeight * 3);
  31086. alpha01 = 0;
  31087. maybeUndoPreblend = false;
  31088. } else {
  31089. imgData.kind = ImageKind.RGBA_32BPP;
  31090. imgData.data = new Uint8Array(drawWidth * drawHeight * 4);
  31091. alpha01 = 1;
  31092. maybeUndoPreblend = true;
  31093. // Color key masking (opacity) must be performed before decoding.
  31094. this.fillOpacity(imgData.data, drawWidth, drawHeight, actualHeight,
  31095. comps);
  31096. }
  31097. if (this.needsDecode) {
  31098. this.decodeBuffer(comps);
  31099. }
  31100. this.colorSpace.fillRgb(imgData.data, originalWidth, originalHeight,
  31101. drawWidth, drawHeight, actualHeight, bpc, comps,
  31102. alpha01);
  31103. if (maybeUndoPreblend) {
  31104. this.undoPreblend(imgData.data, drawWidth, actualHeight);
  31105. }
  31106. return imgData;
  31107. },
  31108. fillGrayBuffer: function PDFImage_fillGrayBuffer(buffer) {
  31109. var numComps = this.numComps;
  31110. if (numComps !== 1) {
  31111. error('Reading gray scale from a color image: ' + numComps);
  31112. }
  31113. var width = this.width;
  31114. var height = this.height;
  31115. var bpc = this.bpc;
  31116. // rows start at byte boundary
  31117. var rowBytes = (width * numComps * bpc + 7) >> 3;
  31118. var imgArray = this.getImageBytes(height * rowBytes);
  31119. var comps = this.getComponents(imgArray);
  31120. var i, length;
  31121. if (bpc === 1) {
  31122. // inline decoding (= inversion) for 1 bpc images
  31123. length = width * height;
  31124. if (this.needsDecode) {
  31125. // invert and scale to {0, 255}
  31126. for (i = 0; i < length; ++i) {
  31127. buffer[i] = (comps[i] - 1) & 255;
  31128. }
  31129. } else {
  31130. // scale to {0, 255}
  31131. for (i = 0; i < length; ++i) {
  31132. buffer[i] = (-comps[i]) & 255;
  31133. }
  31134. }
  31135. return;
  31136. }
  31137. if (this.needsDecode) {
  31138. this.decodeBuffer(comps);
  31139. }
  31140. length = width * height;
  31141. // we aren't using a colorspace so we need to scale the value
  31142. var scale = 255 / ((1 << bpc) - 1);
  31143. for (i = 0; i < length; ++i) {
  31144. buffer[i] = (scale * comps[i]) | 0;
  31145. }
  31146. },
  31147. getImageBytes: function PDFImage_getImageBytes(length,
  31148. drawWidth, drawHeight,
  31149. forceRGB) {
  31150. this.image.reset();
  31151. this.image.drawWidth = drawWidth || this.width;
  31152. this.image.drawHeight = drawHeight || this.height;
  31153. this.image.forceRGB = !!forceRGB;
  31154. return this.image.getBytes(length);
  31155. }
  31156. };
  31157. return PDFImage;
  31158. })();
  31159. // The Metrics object contains glyph widths (in glyph space units).
  31160. // As per PDF spec, for most fonts (Type 3 being an exception) a glyph
  31161. // space unit corresponds to 1/1000th of text space unit.
  31162. var Metrics = {
  31163. 'Courier': 600,
  31164. 'Courier-Bold': 600,
  31165. 'Courier-BoldOblique': 600,
  31166. 'Courier-Oblique': 600,
  31167. 'Helvetica' : {
  31168. 'space': 278,
  31169. 'exclam': 278,
  31170. 'quotedbl': 355,
  31171. 'numbersign': 556,
  31172. 'dollar': 556,
  31173. 'percent': 889,
  31174. 'ampersand': 667,
  31175. 'quoteright': 222,
  31176. 'parenleft': 333,
  31177. 'parenright': 333,
  31178. 'asterisk': 389,
  31179. 'plus': 584,
  31180. 'comma': 278,
  31181. 'hyphen': 333,
  31182. 'period': 278,
  31183. 'slash': 278,
  31184. 'zero': 556,
  31185. 'one': 556,
  31186. 'two': 556,
  31187. 'three': 556,
  31188. 'four': 556,
  31189. 'five': 556,
  31190. 'six': 556,
  31191. 'seven': 556,
  31192. 'eight': 556,
  31193. 'nine': 556,
  31194. 'colon': 278,
  31195. 'semicolon': 278,
  31196. 'less': 584,
  31197. 'equal': 584,
  31198. 'greater': 584,
  31199. 'question': 556,
  31200. 'at': 1015,
  31201. 'A': 667,
  31202. 'B': 667,
  31203. 'C': 722,
  31204. 'D': 722,
  31205. 'E': 667,
  31206. 'F': 611,
  31207. 'G': 778,
  31208. 'H': 722,
  31209. 'I': 278,
  31210. 'J': 500,
  31211. 'K': 667,
  31212. 'L': 556,
  31213. 'M': 833,
  31214. 'N': 722,
  31215. 'O': 778,
  31216. 'P': 667,
  31217. 'Q': 778,
  31218. 'R': 722,
  31219. 'S': 667,
  31220. 'T': 611,
  31221. 'U': 722,
  31222. 'V': 667,
  31223. 'W': 944,
  31224. 'X': 667,
  31225. 'Y': 667,
  31226. 'Z': 611,
  31227. 'bracketleft': 278,
  31228. 'backslash': 278,
  31229. 'bracketright': 278,
  31230. 'asciicircum': 469,
  31231. 'underscore': 556,
  31232. 'quoteleft': 222,
  31233. 'a': 556,
  31234. 'b': 556,
  31235. 'c': 500,
  31236. 'd': 556,
  31237. 'e': 556,
  31238. 'f': 278,
  31239. 'g': 556,
  31240. 'h': 556,
  31241. 'i': 222,
  31242. 'j': 222,
  31243. 'k': 500,
  31244. 'l': 222,
  31245. 'm': 833,
  31246. 'n': 556,
  31247. 'o': 556,
  31248. 'p': 556,
  31249. 'q': 556,
  31250. 'r': 333,
  31251. 's': 500,
  31252. 't': 278,
  31253. 'u': 556,
  31254. 'v': 500,
  31255. 'w': 722,
  31256. 'x': 500,
  31257. 'y': 500,
  31258. 'z': 500,
  31259. 'braceleft': 334,
  31260. 'bar': 260,
  31261. 'braceright': 334,
  31262. 'asciitilde': 584,
  31263. 'exclamdown': 333,
  31264. 'cent': 556,
  31265. 'sterling': 556,
  31266. 'fraction': 167,
  31267. 'yen': 556,
  31268. 'florin': 556,
  31269. 'section': 556,
  31270. 'currency': 556,
  31271. 'quotesingle': 191,
  31272. 'quotedblleft': 333,
  31273. 'guillemotleft': 556,
  31274. 'guilsinglleft': 333,
  31275. 'guilsinglright': 333,
  31276. 'fi': 500,
  31277. 'fl': 500,
  31278. 'endash': 556,
  31279. 'dagger': 556,
  31280. 'daggerdbl': 556,
  31281. 'periodcentered': 278,
  31282. 'paragraph': 537,
  31283. 'bullet': 350,
  31284. 'quotesinglbase': 222,
  31285. 'quotedblbase': 333,
  31286. 'quotedblright': 333,
  31287. 'guillemotright': 556,
  31288. 'ellipsis': 1000,
  31289. 'perthousand': 1000,
  31290. 'questiondown': 611,
  31291. 'grave': 333,
  31292. 'acute': 333,
  31293. 'circumflex': 333,
  31294. 'tilde': 333,
  31295. 'macron': 333,
  31296. 'breve': 333,
  31297. 'dotaccent': 333,
  31298. 'dieresis': 333,
  31299. 'ring': 333,
  31300. 'cedilla': 333,
  31301. 'hungarumlaut': 333,
  31302. 'ogonek': 333,
  31303. 'caron': 333,
  31304. 'emdash': 1000,
  31305. 'AE': 1000,
  31306. 'ordfeminine': 370,
  31307. 'Lslash': 556,
  31308. 'Oslash': 778,
  31309. 'OE': 1000,
  31310. 'ordmasculine': 365,
  31311. 'ae': 889,
  31312. 'dotlessi': 278,
  31313. 'lslash': 222,
  31314. 'oslash': 611,
  31315. 'oe': 944,
  31316. 'germandbls': 611,
  31317. 'Idieresis': 278,
  31318. 'eacute': 556,
  31319. 'abreve': 556,
  31320. 'uhungarumlaut': 556,
  31321. 'ecaron': 556,
  31322. 'Ydieresis': 667,
  31323. 'divide': 584,
  31324. 'Yacute': 667,
  31325. 'Acircumflex': 667,
  31326. 'aacute': 556,
  31327. 'Ucircumflex': 722,
  31328. 'yacute': 500,
  31329. 'scommaaccent': 500,
  31330. 'ecircumflex': 556,
  31331. 'Uring': 722,
  31332. 'Udieresis': 722,
  31333. 'aogonek': 556,
  31334. 'Uacute': 722,
  31335. 'uogonek': 556,
  31336. 'Edieresis': 667,
  31337. 'Dcroat': 722,
  31338. 'commaaccent': 250,
  31339. 'copyright': 737,
  31340. 'Emacron': 667,
  31341. 'ccaron': 500,
  31342. 'aring': 556,
  31343. 'Ncommaaccent': 722,
  31344. 'lacute': 222,
  31345. 'agrave': 556,
  31346. 'Tcommaaccent': 611,
  31347. 'Cacute': 722,
  31348. 'atilde': 556,
  31349. 'Edotaccent': 667,
  31350. 'scaron': 500,
  31351. 'scedilla': 500,
  31352. 'iacute': 278,
  31353. 'lozenge': 471,
  31354. 'Rcaron': 722,
  31355. 'Gcommaaccent': 778,
  31356. 'ucircumflex': 556,
  31357. 'acircumflex': 556,
  31358. 'Amacron': 667,
  31359. 'rcaron': 333,
  31360. 'ccedilla': 500,
  31361. 'Zdotaccent': 611,
  31362. 'Thorn': 667,
  31363. 'Omacron': 778,
  31364. 'Racute': 722,
  31365. 'Sacute': 667,
  31366. 'dcaron': 643,
  31367. 'Umacron': 722,
  31368. 'uring': 556,
  31369. 'threesuperior': 333,
  31370. 'Ograve': 778,
  31371. 'Agrave': 667,
  31372. 'Abreve': 667,
  31373. 'multiply': 584,
  31374. 'uacute': 556,
  31375. 'Tcaron': 611,
  31376. 'partialdiff': 476,
  31377. 'ydieresis': 500,
  31378. 'Nacute': 722,
  31379. 'icircumflex': 278,
  31380. 'Ecircumflex': 667,
  31381. 'adieresis': 556,
  31382. 'edieresis': 556,
  31383. 'cacute': 500,
  31384. 'nacute': 556,
  31385. 'umacron': 556,
  31386. 'Ncaron': 722,
  31387. 'Iacute': 278,
  31388. 'plusminus': 584,
  31389. 'brokenbar': 260,
  31390. 'registered': 737,
  31391. 'Gbreve': 778,
  31392. 'Idotaccent': 278,
  31393. 'summation': 600,
  31394. 'Egrave': 667,
  31395. 'racute': 333,
  31396. 'omacron': 556,
  31397. 'Zacute': 611,
  31398. 'Zcaron': 611,
  31399. 'greaterequal': 549,
  31400. 'Eth': 722,
  31401. 'Ccedilla': 722,
  31402. 'lcommaaccent': 222,
  31403. 'tcaron': 317,
  31404. 'eogonek': 556,
  31405. 'Uogonek': 722,
  31406. 'Aacute': 667,
  31407. 'Adieresis': 667,
  31408. 'egrave': 556,
  31409. 'zacute': 500,
  31410. 'iogonek': 222,
  31411. 'Oacute': 778,
  31412. 'oacute': 556,
  31413. 'amacron': 556,
  31414. 'sacute': 500,
  31415. 'idieresis': 278,
  31416. 'Ocircumflex': 778,
  31417. 'Ugrave': 722,
  31418. 'Delta': 612,
  31419. 'thorn': 556,
  31420. 'twosuperior': 333,
  31421. 'Odieresis': 778,
  31422. 'mu': 556,
  31423. 'igrave': 278,
  31424. 'ohungarumlaut': 556,
  31425. 'Eogonek': 667,
  31426. 'dcroat': 556,
  31427. 'threequarters': 834,
  31428. 'Scedilla': 667,
  31429. 'lcaron': 299,
  31430. 'Kcommaaccent': 667,
  31431. 'Lacute': 556,
  31432. 'trademark': 1000,
  31433. 'edotaccent': 556,
  31434. 'Igrave': 278,
  31435. 'Imacron': 278,
  31436. 'Lcaron': 556,
  31437. 'onehalf': 834,
  31438. 'lessequal': 549,
  31439. 'ocircumflex': 556,
  31440. 'ntilde': 556,
  31441. 'Uhungarumlaut': 722,
  31442. 'Eacute': 667,
  31443. 'emacron': 556,
  31444. 'gbreve': 556,
  31445. 'onequarter': 834,
  31446. 'Scaron': 667,
  31447. 'Scommaaccent': 667,
  31448. 'Ohungarumlaut': 778,
  31449. 'degree': 400,
  31450. 'ograve': 556,
  31451. 'Ccaron': 722,
  31452. 'ugrave': 556,
  31453. 'radical': 453,
  31454. 'Dcaron': 722,
  31455. 'rcommaaccent': 333,
  31456. 'Ntilde': 722,
  31457. 'otilde': 556,
  31458. 'Rcommaaccent': 722,
  31459. 'Lcommaaccent': 556,
  31460. 'Atilde': 667,
  31461. 'Aogonek': 667,
  31462. 'Aring': 667,
  31463. 'Otilde': 778,
  31464. 'zdotaccent': 500,
  31465. 'Ecaron': 667,
  31466. 'Iogonek': 278,
  31467. 'kcommaaccent': 500,
  31468. 'minus': 584,
  31469. 'Icircumflex': 278,
  31470. 'ncaron': 556,
  31471. 'tcommaaccent': 278,
  31472. 'logicalnot': 584,
  31473. 'odieresis': 556,
  31474. 'udieresis': 556,
  31475. 'notequal': 549,
  31476. 'gcommaaccent': 556,
  31477. 'eth': 556,
  31478. 'zcaron': 500,
  31479. 'ncommaaccent': 556,
  31480. 'onesuperior': 333,
  31481. 'imacron': 278,
  31482. 'Euro': 556
  31483. },
  31484. 'Helvetica-Bold': {
  31485. 'space': 278,
  31486. 'exclam': 333,
  31487. 'quotedbl': 474,
  31488. 'numbersign': 556,
  31489. 'dollar': 556,
  31490. 'percent': 889,
  31491. 'ampersand': 722,
  31492. 'quoteright': 278,
  31493. 'parenleft': 333,
  31494. 'parenright': 333,
  31495. 'asterisk': 389,
  31496. 'plus': 584,
  31497. 'comma': 278,
  31498. 'hyphen': 333,
  31499. 'period': 278,
  31500. 'slash': 278,
  31501. 'zero': 556,
  31502. 'one': 556,
  31503. 'two': 556,
  31504. 'three': 556,
  31505. 'four': 556,
  31506. 'five': 556,
  31507. 'six': 556,
  31508. 'seven': 556,
  31509. 'eight': 556,
  31510. 'nine': 556,
  31511. 'colon': 333,
  31512. 'semicolon': 333,
  31513. 'less': 584,
  31514. 'equal': 584,
  31515. 'greater': 584,
  31516. 'question': 611,
  31517. 'at': 975,
  31518. 'A': 722,
  31519. 'B': 722,
  31520. 'C': 722,
  31521. 'D': 722,
  31522. 'E': 667,
  31523. 'F': 611,
  31524. 'G': 778,
  31525. 'H': 722,
  31526. 'I': 278,
  31527. 'J': 556,
  31528. 'K': 722,
  31529. 'L': 611,
  31530. 'M': 833,
  31531. 'N': 722,
  31532. 'O': 778,
  31533. 'P': 667,
  31534. 'Q': 778,
  31535. 'R': 722,
  31536. 'S': 667,
  31537. 'T': 611,
  31538. 'U': 722,
  31539. 'V': 667,
  31540. 'W': 944,
  31541. 'X': 667,
  31542. 'Y': 667,
  31543. 'Z': 611,
  31544. 'bracketleft': 333,
  31545. 'backslash': 278,
  31546. 'bracketright': 333,
  31547. 'asciicircum': 584,
  31548. 'underscore': 556,
  31549. 'quoteleft': 278,
  31550. 'a': 556,
  31551. 'b': 611,
  31552. 'c': 556,
  31553. 'd': 611,
  31554. 'e': 556,
  31555. 'f': 333,
  31556. 'g': 611,
  31557. 'h': 611,
  31558. 'i': 278,
  31559. 'j': 278,
  31560. 'k': 556,
  31561. 'l': 278,
  31562. 'm': 889,
  31563. 'n': 611,
  31564. 'o': 611,
  31565. 'p': 611,
  31566. 'q': 611,
  31567. 'r': 389,
  31568. 's': 556,
  31569. 't': 333,
  31570. 'u': 611,
  31571. 'v': 556,
  31572. 'w': 778,
  31573. 'x': 556,
  31574. 'y': 556,
  31575. 'z': 500,
  31576. 'braceleft': 389,
  31577. 'bar': 280,
  31578. 'braceright': 389,
  31579. 'asciitilde': 584,
  31580. 'exclamdown': 333,
  31581. 'cent': 556,
  31582. 'sterling': 556,
  31583. 'fraction': 167,
  31584. 'yen': 556,
  31585. 'florin': 556,
  31586. 'section': 556,
  31587. 'currency': 556,
  31588. 'quotesingle': 238,
  31589. 'quotedblleft': 500,
  31590. 'guillemotleft': 556,
  31591. 'guilsinglleft': 333,
  31592. 'guilsinglright': 333,
  31593. 'fi': 611,
  31594. 'fl': 611,
  31595. 'endash': 556,
  31596. 'dagger': 556,
  31597. 'daggerdbl': 556,
  31598. 'periodcentered': 278,
  31599. 'paragraph': 556,
  31600. 'bullet': 350,
  31601. 'quotesinglbase': 278,
  31602. 'quotedblbase': 500,
  31603. 'quotedblright': 500,
  31604. 'guillemotright': 556,
  31605. 'ellipsis': 1000,
  31606. 'perthousand': 1000,
  31607. 'questiondown': 611,
  31608. 'grave': 333,
  31609. 'acute': 333,
  31610. 'circumflex': 333,
  31611. 'tilde': 333,
  31612. 'macron': 333,
  31613. 'breve': 333,
  31614. 'dotaccent': 333,
  31615. 'dieresis': 333,
  31616. 'ring': 333,
  31617. 'cedilla': 333,
  31618. 'hungarumlaut': 333,
  31619. 'ogonek': 333,
  31620. 'caron': 333,
  31621. 'emdash': 1000,
  31622. 'AE': 1000,
  31623. 'ordfeminine': 370,
  31624. 'Lslash': 611,
  31625. 'Oslash': 778,
  31626. 'OE': 1000,
  31627. 'ordmasculine': 365,
  31628. 'ae': 889,
  31629. 'dotlessi': 278,
  31630. 'lslash': 278,
  31631. 'oslash': 611,
  31632. 'oe': 944,
  31633. 'germandbls': 611,
  31634. 'Idieresis': 278,
  31635. 'eacute': 556,
  31636. 'abreve': 556,
  31637. 'uhungarumlaut': 611,
  31638. 'ecaron': 556,
  31639. 'Ydieresis': 667,
  31640. 'divide': 584,
  31641. 'Yacute': 667,
  31642. 'Acircumflex': 722,
  31643. 'aacute': 556,
  31644. 'Ucircumflex': 722,
  31645. 'yacute': 556,
  31646. 'scommaaccent': 556,
  31647. 'ecircumflex': 556,
  31648. 'Uring': 722,
  31649. 'Udieresis': 722,
  31650. 'aogonek': 556,
  31651. 'Uacute': 722,
  31652. 'uogonek': 611,
  31653. 'Edieresis': 667,
  31654. 'Dcroat': 722,
  31655. 'commaaccent': 250,
  31656. 'copyright': 737,
  31657. 'Emacron': 667,
  31658. 'ccaron': 556,
  31659. 'aring': 556,
  31660. 'Ncommaaccent': 722,
  31661. 'lacute': 278,
  31662. 'agrave': 556,
  31663. 'Tcommaaccent': 611,
  31664. 'Cacute': 722,
  31665. 'atilde': 556,
  31666. 'Edotaccent': 667,
  31667. 'scaron': 556,
  31668. 'scedilla': 556,
  31669. 'iacute': 278,
  31670. 'lozenge': 494,
  31671. 'Rcaron': 722,
  31672. 'Gcommaaccent': 778,
  31673. 'ucircumflex': 611,
  31674. 'acircumflex': 556,
  31675. 'Amacron': 722,
  31676. 'rcaron': 389,
  31677. 'ccedilla': 556,
  31678. 'Zdotaccent': 611,
  31679. 'Thorn': 667,
  31680. 'Omacron': 778,
  31681. 'Racute': 722,
  31682. 'Sacute': 667,
  31683. 'dcaron': 743,
  31684. 'Umacron': 722,
  31685. 'uring': 611,
  31686. 'threesuperior': 333,
  31687. 'Ograve': 778,
  31688. 'Agrave': 722,
  31689. 'Abreve': 722,
  31690. 'multiply': 584,
  31691. 'uacute': 611,
  31692. 'Tcaron': 611,
  31693. 'partialdiff': 494,
  31694. 'ydieresis': 556,
  31695. 'Nacute': 722,
  31696. 'icircumflex': 278,
  31697. 'Ecircumflex': 667,
  31698. 'adieresis': 556,
  31699. 'edieresis': 556,
  31700. 'cacute': 556,
  31701. 'nacute': 611,
  31702. 'umacron': 611,
  31703. 'Ncaron': 722,
  31704. 'Iacute': 278,
  31705. 'plusminus': 584,
  31706. 'brokenbar': 280,
  31707. 'registered': 737,
  31708. 'Gbreve': 778,
  31709. 'Idotaccent': 278,
  31710. 'summation': 600,
  31711. 'Egrave': 667,
  31712. 'racute': 389,
  31713. 'omacron': 611,
  31714. 'Zacute': 611,
  31715. 'Zcaron': 611,
  31716. 'greaterequal': 549,
  31717. 'Eth': 722,
  31718. 'Ccedilla': 722,
  31719. 'lcommaaccent': 278,
  31720. 'tcaron': 389,
  31721. 'eogonek': 556,
  31722. 'Uogonek': 722,
  31723. 'Aacute': 722,
  31724. 'Adieresis': 722,
  31725. 'egrave': 556,
  31726. 'zacute': 500,
  31727. 'iogonek': 278,
  31728. 'Oacute': 778,
  31729. 'oacute': 611,
  31730. 'amacron': 556,
  31731. 'sacute': 556,
  31732. 'idieresis': 278,
  31733. 'Ocircumflex': 778,
  31734. 'Ugrave': 722,
  31735. 'Delta': 612,
  31736. 'thorn': 611,
  31737. 'twosuperior': 333,
  31738. 'Odieresis': 778,
  31739. 'mu': 611,
  31740. 'igrave': 278,
  31741. 'ohungarumlaut': 611,
  31742. 'Eogonek': 667,
  31743. 'dcroat': 611,
  31744. 'threequarters': 834,
  31745. 'Scedilla': 667,
  31746. 'lcaron': 400,
  31747. 'Kcommaaccent': 722,
  31748. 'Lacute': 611,
  31749. 'trademark': 1000,
  31750. 'edotaccent': 556,
  31751. 'Igrave': 278,
  31752. 'Imacron': 278,
  31753. 'Lcaron': 611,
  31754. 'onehalf': 834,
  31755. 'lessequal': 549,
  31756. 'ocircumflex': 611,
  31757. 'ntilde': 611,
  31758. 'Uhungarumlaut': 722,
  31759. 'Eacute': 667,
  31760. 'emacron': 556,
  31761. 'gbreve': 611,
  31762. 'onequarter': 834,
  31763. 'Scaron': 667,
  31764. 'Scommaaccent': 667,
  31765. 'Ohungarumlaut': 778,
  31766. 'degree': 400,
  31767. 'ograve': 611,
  31768. 'Ccaron': 722,
  31769. 'ugrave': 611,
  31770. 'radical': 549,
  31771. 'Dcaron': 722,
  31772. 'rcommaaccent': 389,
  31773. 'Ntilde': 722,
  31774. 'otilde': 611,
  31775. 'Rcommaaccent': 722,
  31776. 'Lcommaaccent': 611,
  31777. 'Atilde': 722,
  31778. 'Aogonek': 722,
  31779. 'Aring': 722,
  31780. 'Otilde': 778,
  31781. 'zdotaccent': 500,
  31782. 'Ecaron': 667,
  31783. 'Iogonek': 278,
  31784. 'kcommaaccent': 556,
  31785. 'minus': 584,
  31786. 'Icircumflex': 278,
  31787. 'ncaron': 611,
  31788. 'tcommaaccent': 333,
  31789. 'logicalnot': 584,
  31790. 'odieresis': 611,
  31791. 'udieresis': 611,
  31792. 'notequal': 549,
  31793. 'gcommaaccent': 611,
  31794. 'eth': 611,
  31795. 'zcaron': 500,
  31796. 'ncommaaccent': 611,
  31797. 'onesuperior': 333,
  31798. 'imacron': 278,
  31799. 'Euro': 556
  31800. },
  31801. 'Helvetica-BoldOblique': {
  31802. 'space': 278,
  31803. 'exclam': 333,
  31804. 'quotedbl': 474,
  31805. 'numbersign': 556,
  31806. 'dollar': 556,
  31807. 'percent': 889,
  31808. 'ampersand': 722,
  31809. 'quoteright': 278,
  31810. 'parenleft': 333,
  31811. 'parenright': 333,
  31812. 'asterisk': 389,
  31813. 'plus': 584,
  31814. 'comma': 278,
  31815. 'hyphen': 333,
  31816. 'period': 278,
  31817. 'slash': 278,
  31818. 'zero': 556,
  31819. 'one': 556,
  31820. 'two': 556,
  31821. 'three': 556,
  31822. 'four': 556,
  31823. 'five': 556,
  31824. 'six': 556,
  31825. 'seven': 556,
  31826. 'eight': 556,
  31827. 'nine': 556,
  31828. 'colon': 333,
  31829. 'semicolon': 333,
  31830. 'less': 584,
  31831. 'equal': 584,
  31832. 'greater': 584,
  31833. 'question': 611,
  31834. 'at': 975,
  31835. 'A': 722,
  31836. 'B': 722,
  31837. 'C': 722,
  31838. 'D': 722,
  31839. 'E': 667,
  31840. 'F': 611,
  31841. 'G': 778,
  31842. 'H': 722,
  31843. 'I': 278,
  31844. 'J': 556,
  31845. 'K': 722,
  31846. 'L': 611,
  31847. 'M': 833,
  31848. 'N': 722,
  31849. 'O': 778,
  31850. 'P': 667,
  31851. 'Q': 778,
  31852. 'R': 722,
  31853. 'S': 667,
  31854. 'T': 611,
  31855. 'U': 722,
  31856. 'V': 667,
  31857. 'W': 944,
  31858. 'X': 667,
  31859. 'Y': 667,
  31860. 'Z': 611,
  31861. 'bracketleft': 333,
  31862. 'backslash': 278,
  31863. 'bracketright': 333,
  31864. 'asciicircum': 584,
  31865. 'underscore': 556,
  31866. 'quoteleft': 278,
  31867. 'a': 556,
  31868. 'b': 611,
  31869. 'c': 556,
  31870. 'd': 611,
  31871. 'e': 556,
  31872. 'f': 333,
  31873. 'g': 611,
  31874. 'h': 611,
  31875. 'i': 278,
  31876. 'j': 278,
  31877. 'k': 556,
  31878. 'l': 278,
  31879. 'm': 889,
  31880. 'n': 611,
  31881. 'o': 611,
  31882. 'p': 611,
  31883. 'q': 611,
  31884. 'r': 389,
  31885. 's': 556,
  31886. 't': 333,
  31887. 'u': 611,
  31888. 'v': 556,
  31889. 'w': 778,
  31890. 'x': 556,
  31891. 'y': 556,
  31892. 'z': 500,
  31893. 'braceleft': 389,
  31894. 'bar': 280,
  31895. 'braceright': 389,
  31896. 'asciitilde': 584,
  31897. 'exclamdown': 333,
  31898. 'cent': 556,
  31899. 'sterling': 556,
  31900. 'fraction': 167,
  31901. 'yen': 556,
  31902. 'florin': 556,
  31903. 'section': 556,
  31904. 'currency': 556,
  31905. 'quotesingle': 238,
  31906. 'quotedblleft': 500,
  31907. 'guillemotleft': 556,
  31908. 'guilsinglleft': 333,
  31909. 'guilsinglright': 333,
  31910. 'fi': 611,
  31911. 'fl': 611,
  31912. 'endash': 556,
  31913. 'dagger': 556,
  31914. 'daggerdbl': 556,
  31915. 'periodcentered': 278,
  31916. 'paragraph': 556,
  31917. 'bullet': 350,
  31918. 'quotesinglbase': 278,
  31919. 'quotedblbase': 500,
  31920. 'quotedblright': 500,
  31921. 'guillemotright': 556,
  31922. 'ellipsis': 1000,
  31923. 'perthousand': 1000,
  31924. 'questiondown': 611,
  31925. 'grave': 333,
  31926. 'acute': 333,
  31927. 'circumflex': 333,
  31928. 'tilde': 333,
  31929. 'macron': 333,
  31930. 'breve': 333,
  31931. 'dotaccent': 333,
  31932. 'dieresis': 333,
  31933. 'ring': 333,
  31934. 'cedilla': 333,
  31935. 'hungarumlaut': 333,
  31936. 'ogonek': 333,
  31937. 'caron': 333,
  31938. 'emdash': 1000,
  31939. 'AE': 1000,
  31940. 'ordfeminine': 370,
  31941. 'Lslash': 611,
  31942. 'Oslash': 778,
  31943. 'OE': 1000,
  31944. 'ordmasculine': 365,
  31945. 'ae': 889,
  31946. 'dotlessi': 278,
  31947. 'lslash': 278,
  31948. 'oslash': 611,
  31949. 'oe': 944,
  31950. 'germandbls': 611,
  31951. 'Idieresis': 278,
  31952. 'eacute': 556,
  31953. 'abreve': 556,
  31954. 'uhungarumlaut': 611,
  31955. 'ecaron': 556,
  31956. 'Ydieresis': 667,
  31957. 'divide': 584,
  31958. 'Yacute': 667,
  31959. 'Acircumflex': 722,
  31960. 'aacute': 556,
  31961. 'Ucircumflex': 722,
  31962. 'yacute': 556,
  31963. 'scommaaccent': 556,
  31964. 'ecircumflex': 556,
  31965. 'Uring': 722,
  31966. 'Udieresis': 722,
  31967. 'aogonek': 556,
  31968. 'Uacute': 722,
  31969. 'uogonek': 611,
  31970. 'Edieresis': 667,
  31971. 'Dcroat': 722,
  31972. 'commaaccent': 250,
  31973. 'copyright': 737,
  31974. 'Emacron': 667,
  31975. 'ccaron': 556,
  31976. 'aring': 556,
  31977. 'Ncommaaccent': 722,
  31978. 'lacute': 278,
  31979. 'agrave': 556,
  31980. 'Tcommaaccent': 611,
  31981. 'Cacute': 722,
  31982. 'atilde': 556,
  31983. 'Edotaccent': 667,
  31984. 'scaron': 556,
  31985. 'scedilla': 556,
  31986. 'iacute': 278,
  31987. 'lozenge': 494,
  31988. 'Rcaron': 722,
  31989. 'Gcommaaccent': 778,
  31990. 'ucircumflex': 611,
  31991. 'acircumflex': 556,
  31992. 'Amacron': 722,
  31993. 'rcaron': 389,
  31994. 'ccedilla': 556,
  31995. 'Zdotaccent': 611,
  31996. 'Thorn': 667,
  31997. 'Omacron': 778,
  31998. 'Racute': 722,
  31999. 'Sacute': 667,
  32000. 'dcaron': 743,
  32001. 'Umacron': 722,
  32002. 'uring': 611,
  32003. 'threesuperior': 333,
  32004. 'Ograve': 778,
  32005. 'Agrave': 722,
  32006. 'Abreve': 722,
  32007. 'multiply': 584,
  32008. 'uacute': 611,
  32009. 'Tcaron': 611,
  32010. 'partialdiff': 494,
  32011. 'ydieresis': 556,
  32012. 'Nacute': 722,
  32013. 'icircumflex': 278,
  32014. 'Ecircumflex': 667,
  32015. 'adieresis': 556,
  32016. 'edieresis': 556,
  32017. 'cacute': 556,
  32018. 'nacute': 611,
  32019. 'umacron': 611,
  32020. 'Ncaron': 722,
  32021. 'Iacute': 278,
  32022. 'plusminus': 584,
  32023. 'brokenbar': 280,
  32024. 'registered': 737,
  32025. 'Gbreve': 778,
  32026. 'Idotaccent': 278,
  32027. 'summation': 600,
  32028. 'Egrave': 667,
  32029. 'racute': 389,
  32030. 'omacron': 611,
  32031. 'Zacute': 611,
  32032. 'Zcaron': 611,
  32033. 'greaterequal': 549,
  32034. 'Eth': 722,
  32035. 'Ccedilla': 722,
  32036. 'lcommaaccent': 278,
  32037. 'tcaron': 389,
  32038. 'eogonek': 556,
  32039. 'Uogonek': 722,
  32040. 'Aacute': 722,
  32041. 'Adieresis': 722,
  32042. 'egrave': 556,
  32043. 'zacute': 500,
  32044. 'iogonek': 278,
  32045. 'Oacute': 778,
  32046. 'oacute': 611,
  32047. 'amacron': 556,
  32048. 'sacute': 556,
  32049. 'idieresis': 278,
  32050. 'Ocircumflex': 778,
  32051. 'Ugrave': 722,
  32052. 'Delta': 612,
  32053. 'thorn': 611,
  32054. 'twosuperior': 333,
  32055. 'Odieresis': 778,
  32056. 'mu': 611,
  32057. 'igrave': 278,
  32058. 'ohungarumlaut': 611,
  32059. 'Eogonek': 667,
  32060. 'dcroat': 611,
  32061. 'threequarters': 834,
  32062. 'Scedilla': 667,
  32063. 'lcaron': 400,
  32064. 'Kcommaaccent': 722,
  32065. 'Lacute': 611,
  32066. 'trademark': 1000,
  32067. 'edotaccent': 556,
  32068. 'Igrave': 278,
  32069. 'Imacron': 278,
  32070. 'Lcaron': 611,
  32071. 'onehalf': 834,
  32072. 'lessequal': 549,
  32073. 'ocircumflex': 611,
  32074. 'ntilde': 611,
  32075. 'Uhungarumlaut': 722,
  32076. 'Eacute': 667,
  32077. 'emacron': 556,
  32078. 'gbreve': 611,
  32079. 'onequarter': 834,
  32080. 'Scaron': 667,
  32081. 'Scommaaccent': 667,
  32082. 'Ohungarumlaut': 778,
  32083. 'degree': 400,
  32084. 'ograve': 611,
  32085. 'Ccaron': 722,
  32086. 'ugrave': 611,
  32087. 'radical': 549,
  32088. 'Dcaron': 722,
  32089. 'rcommaaccent': 389,
  32090. 'Ntilde': 722,
  32091. 'otilde': 611,
  32092. 'Rcommaaccent': 722,
  32093. 'Lcommaaccent': 611,
  32094. 'Atilde': 722,
  32095. 'Aogonek': 722,
  32096. 'Aring': 722,
  32097. 'Otilde': 778,
  32098. 'zdotaccent': 500,
  32099. 'Ecaron': 667,
  32100. 'Iogonek': 278,
  32101. 'kcommaaccent': 556,
  32102. 'minus': 584,
  32103. 'Icircumflex': 278,
  32104. 'ncaron': 611,
  32105. 'tcommaaccent': 333,
  32106. 'logicalnot': 584,
  32107. 'odieresis': 611,
  32108. 'udieresis': 611,
  32109. 'notequal': 549,
  32110. 'gcommaaccent': 611,
  32111. 'eth': 611,
  32112. 'zcaron': 500,
  32113. 'ncommaaccent': 611,
  32114. 'onesuperior': 333,
  32115. 'imacron': 278,
  32116. 'Euro': 556
  32117. },
  32118. 'Helvetica-Oblique' : {
  32119. 'space': 278,
  32120. 'exclam': 278,
  32121. 'quotedbl': 355,
  32122. 'numbersign': 556,
  32123. 'dollar': 556,
  32124. 'percent': 889,
  32125. 'ampersand': 667,
  32126. 'quoteright': 222,
  32127. 'parenleft': 333,
  32128. 'parenright': 333,
  32129. 'asterisk': 389,
  32130. 'plus': 584,
  32131. 'comma': 278,
  32132. 'hyphen': 333,
  32133. 'period': 278,
  32134. 'slash': 278,
  32135. 'zero': 556,
  32136. 'one': 556,
  32137. 'two': 556,
  32138. 'three': 556,
  32139. 'four': 556,
  32140. 'five': 556,
  32141. 'six': 556,
  32142. 'seven': 556,
  32143. 'eight': 556,
  32144. 'nine': 556,
  32145. 'colon': 278,
  32146. 'semicolon': 278,
  32147. 'less': 584,
  32148. 'equal': 584,
  32149. 'greater': 584,
  32150. 'question': 556,
  32151. 'at': 1015,
  32152. 'A': 667,
  32153. 'B': 667,
  32154. 'C': 722,
  32155. 'D': 722,
  32156. 'E': 667,
  32157. 'F': 611,
  32158. 'G': 778,
  32159. 'H': 722,
  32160. 'I': 278,
  32161. 'J': 500,
  32162. 'K': 667,
  32163. 'L': 556,
  32164. 'M': 833,
  32165. 'N': 722,
  32166. 'O': 778,
  32167. 'P': 667,
  32168. 'Q': 778,
  32169. 'R': 722,
  32170. 'S': 667,
  32171. 'T': 611,
  32172. 'U': 722,
  32173. 'V': 667,
  32174. 'W': 944,
  32175. 'X': 667,
  32176. 'Y': 667,
  32177. 'Z': 611,
  32178. 'bracketleft': 278,
  32179. 'backslash': 278,
  32180. 'bracketright': 278,
  32181. 'asciicircum': 469,
  32182. 'underscore': 556,
  32183. 'quoteleft': 222,
  32184. 'a': 556,
  32185. 'b': 556,
  32186. 'c': 500,
  32187. 'd': 556,
  32188. 'e': 556,
  32189. 'f': 278,
  32190. 'g': 556,
  32191. 'h': 556,
  32192. 'i': 222,
  32193. 'j': 222,
  32194. 'k': 500,
  32195. 'l': 222,
  32196. 'm': 833,
  32197. 'n': 556,
  32198. 'o': 556,
  32199. 'p': 556,
  32200. 'q': 556,
  32201. 'r': 333,
  32202. 's': 500,
  32203. 't': 278,
  32204. 'u': 556,
  32205. 'v': 500,
  32206. 'w': 722,
  32207. 'x': 500,
  32208. 'y': 500,
  32209. 'z': 500,
  32210. 'braceleft': 334,
  32211. 'bar': 260,
  32212. 'braceright': 334,
  32213. 'asciitilde': 584,
  32214. 'exclamdown': 333,
  32215. 'cent': 556,
  32216. 'sterling': 556,
  32217. 'fraction': 167,
  32218. 'yen': 556,
  32219. 'florin': 556,
  32220. 'section': 556,
  32221. 'currency': 556,
  32222. 'quotesingle': 191,
  32223. 'quotedblleft': 333,
  32224. 'guillemotleft': 556,
  32225. 'guilsinglleft': 333,
  32226. 'guilsinglright': 333,
  32227. 'fi': 500,
  32228. 'fl': 500,
  32229. 'endash': 556,
  32230. 'dagger': 556,
  32231. 'daggerdbl': 556,
  32232. 'periodcentered': 278,
  32233. 'paragraph': 537,
  32234. 'bullet': 350,
  32235. 'quotesinglbase': 222,
  32236. 'quotedblbase': 333,
  32237. 'quotedblright': 333,
  32238. 'guillemotright': 556,
  32239. 'ellipsis': 1000,
  32240. 'perthousand': 1000,
  32241. 'questiondown': 611,
  32242. 'grave': 333,
  32243. 'acute': 333,
  32244. 'circumflex': 333,
  32245. 'tilde': 333,
  32246. 'macron': 333,
  32247. 'breve': 333,
  32248. 'dotaccent': 333,
  32249. 'dieresis': 333,
  32250. 'ring': 333,
  32251. 'cedilla': 333,
  32252. 'hungarumlaut': 333,
  32253. 'ogonek': 333,
  32254. 'caron': 333,
  32255. 'emdash': 1000,
  32256. 'AE': 1000,
  32257. 'ordfeminine': 370,
  32258. 'Lslash': 556,
  32259. 'Oslash': 778,
  32260. 'OE': 1000,
  32261. 'ordmasculine': 365,
  32262. 'ae': 889,
  32263. 'dotlessi': 278,
  32264. 'lslash': 222,
  32265. 'oslash': 611,
  32266. 'oe': 944,
  32267. 'germandbls': 611,
  32268. 'Idieresis': 278,
  32269. 'eacute': 556,
  32270. 'abreve': 556,
  32271. 'uhungarumlaut': 556,
  32272. 'ecaron': 556,
  32273. 'Ydieresis': 667,
  32274. 'divide': 584,
  32275. 'Yacute': 667,
  32276. 'Acircumflex': 667,
  32277. 'aacute': 556,
  32278. 'Ucircumflex': 722,
  32279. 'yacute': 500,
  32280. 'scommaaccent': 500,
  32281. 'ecircumflex': 556,
  32282. 'Uring': 722,
  32283. 'Udieresis': 722,
  32284. 'aogonek': 556,
  32285. 'Uacute': 722,
  32286. 'uogonek': 556,
  32287. 'Edieresis': 667,
  32288. 'Dcroat': 722,
  32289. 'commaaccent': 250,
  32290. 'copyright': 737,
  32291. 'Emacron': 667,
  32292. 'ccaron': 500,
  32293. 'aring': 556,
  32294. 'Ncommaaccent': 722,
  32295. 'lacute': 222,
  32296. 'agrave': 556,
  32297. 'Tcommaaccent': 611,
  32298. 'Cacute': 722,
  32299. 'atilde': 556,
  32300. 'Edotaccent': 667,
  32301. 'scaron': 500,
  32302. 'scedilla': 500,
  32303. 'iacute': 278,
  32304. 'lozenge': 471,
  32305. 'Rcaron': 722,
  32306. 'Gcommaaccent': 778,
  32307. 'ucircumflex': 556,
  32308. 'acircumflex': 556,
  32309. 'Amacron': 667,
  32310. 'rcaron': 333,
  32311. 'ccedilla': 500,
  32312. 'Zdotaccent': 611,
  32313. 'Thorn': 667,
  32314. 'Omacron': 778,
  32315. 'Racute': 722,
  32316. 'Sacute': 667,
  32317. 'dcaron': 643,
  32318. 'Umacron': 722,
  32319. 'uring': 556,
  32320. 'threesuperior': 333,
  32321. 'Ograve': 778,
  32322. 'Agrave': 667,
  32323. 'Abreve': 667,
  32324. 'multiply': 584,
  32325. 'uacute': 556,
  32326. 'Tcaron': 611,
  32327. 'partialdiff': 476,
  32328. 'ydieresis': 500,
  32329. 'Nacute': 722,
  32330. 'icircumflex': 278,
  32331. 'Ecircumflex': 667,
  32332. 'adieresis': 556,
  32333. 'edieresis': 556,
  32334. 'cacute': 500,
  32335. 'nacute': 556,
  32336. 'umacron': 556,
  32337. 'Ncaron': 722,
  32338. 'Iacute': 278,
  32339. 'plusminus': 584,
  32340. 'brokenbar': 260,
  32341. 'registered': 737,
  32342. 'Gbreve': 778,
  32343. 'Idotaccent': 278,
  32344. 'summation': 600,
  32345. 'Egrave': 667,
  32346. 'racute': 333,
  32347. 'omacron': 556,
  32348. 'Zacute': 611,
  32349. 'Zcaron': 611,
  32350. 'greaterequal': 549,
  32351. 'Eth': 722,
  32352. 'Ccedilla': 722,
  32353. 'lcommaaccent': 222,
  32354. 'tcaron': 317,
  32355. 'eogonek': 556,
  32356. 'Uogonek': 722,
  32357. 'Aacute': 667,
  32358. 'Adieresis': 667,
  32359. 'egrave': 556,
  32360. 'zacute': 500,
  32361. 'iogonek': 222,
  32362. 'Oacute': 778,
  32363. 'oacute': 556,
  32364. 'amacron': 556,
  32365. 'sacute': 500,
  32366. 'idieresis': 278,
  32367. 'Ocircumflex': 778,
  32368. 'Ugrave': 722,
  32369. 'Delta': 612,
  32370. 'thorn': 556,
  32371. 'twosuperior': 333,
  32372. 'Odieresis': 778,
  32373. 'mu': 556,
  32374. 'igrave': 278,
  32375. 'ohungarumlaut': 556,
  32376. 'Eogonek': 667,
  32377. 'dcroat': 556,
  32378. 'threequarters': 834,
  32379. 'Scedilla': 667,
  32380. 'lcaron': 299,
  32381. 'Kcommaaccent': 667,
  32382. 'Lacute': 556,
  32383. 'trademark': 1000,
  32384. 'edotaccent': 556,
  32385. 'Igrave': 278,
  32386. 'Imacron': 278,
  32387. 'Lcaron': 556,
  32388. 'onehalf': 834,
  32389. 'lessequal': 549,
  32390. 'ocircumflex': 556,
  32391. 'ntilde': 556,
  32392. 'Uhungarumlaut': 722,
  32393. 'Eacute': 667,
  32394. 'emacron': 556,
  32395. 'gbreve': 556,
  32396. 'onequarter': 834,
  32397. 'Scaron': 667,
  32398. 'Scommaaccent': 667,
  32399. 'Ohungarumlaut': 778,
  32400. 'degree': 400,
  32401. 'ograve': 556,
  32402. 'Ccaron': 722,
  32403. 'ugrave': 556,
  32404. 'radical': 453,
  32405. 'Dcaron': 722,
  32406. 'rcommaaccent': 333,
  32407. 'Ntilde': 722,
  32408. 'otilde': 556,
  32409. 'Rcommaaccent': 722,
  32410. 'Lcommaaccent': 556,
  32411. 'Atilde': 667,
  32412. 'Aogonek': 667,
  32413. 'Aring': 667,
  32414. 'Otilde': 778,
  32415. 'zdotaccent': 500,
  32416. 'Ecaron': 667,
  32417. 'Iogonek': 278,
  32418. 'kcommaaccent': 500,
  32419. 'minus': 584,
  32420. 'Icircumflex': 278,
  32421. 'ncaron': 556,
  32422. 'tcommaaccent': 278,
  32423. 'logicalnot': 584,
  32424. 'odieresis': 556,
  32425. 'udieresis': 556,
  32426. 'notequal': 549,
  32427. 'gcommaaccent': 556,
  32428. 'eth': 556,
  32429. 'zcaron': 500,
  32430. 'ncommaaccent': 556,
  32431. 'onesuperior': 333,
  32432. 'imacron': 278,
  32433. 'Euro': 556
  32434. },
  32435. 'Symbol': {
  32436. 'space': 250,
  32437. 'exclam': 333,
  32438. 'universal': 713,
  32439. 'numbersign': 500,
  32440. 'existential': 549,
  32441. 'percent': 833,
  32442. 'ampersand': 778,
  32443. 'suchthat': 439,
  32444. 'parenleft': 333,
  32445. 'parenright': 333,
  32446. 'asteriskmath': 500,
  32447. 'plus': 549,
  32448. 'comma': 250,
  32449. 'minus': 549,
  32450. 'period': 250,
  32451. 'slash': 278,
  32452. 'zero': 500,
  32453. 'one': 500,
  32454. 'two': 500,
  32455. 'three': 500,
  32456. 'four': 500,
  32457. 'five': 500,
  32458. 'six': 500,
  32459. 'seven': 500,
  32460. 'eight': 500,
  32461. 'nine': 500,
  32462. 'colon': 278,
  32463. 'semicolon': 278,
  32464. 'less': 549,
  32465. 'equal': 549,
  32466. 'greater': 549,
  32467. 'question': 444,
  32468. 'congruent': 549,
  32469. 'Alpha': 722,
  32470. 'Beta': 667,
  32471. 'Chi': 722,
  32472. 'Delta': 612,
  32473. 'Epsilon': 611,
  32474. 'Phi': 763,
  32475. 'Gamma': 603,
  32476. 'Eta': 722,
  32477. 'Iota': 333,
  32478. 'theta1': 631,
  32479. 'Kappa': 722,
  32480. 'Lambda': 686,
  32481. 'Mu': 889,
  32482. 'Nu': 722,
  32483. 'Omicron': 722,
  32484. 'Pi': 768,
  32485. 'Theta': 741,
  32486. 'Rho': 556,
  32487. 'Sigma': 592,
  32488. 'Tau': 611,
  32489. 'Upsilon': 690,
  32490. 'sigma1': 439,
  32491. 'Omega': 768,
  32492. 'Xi': 645,
  32493. 'Psi': 795,
  32494. 'Zeta': 611,
  32495. 'bracketleft': 333,
  32496. 'therefore': 863,
  32497. 'bracketright': 333,
  32498. 'perpendicular': 658,
  32499. 'underscore': 500,
  32500. 'radicalex': 500,
  32501. 'alpha': 631,
  32502. 'beta': 549,
  32503. 'chi': 549,
  32504. 'delta': 494,
  32505. 'epsilon': 439,
  32506. 'phi': 521,
  32507. 'gamma': 411,
  32508. 'eta': 603,
  32509. 'iota': 329,
  32510. 'phi1': 603,
  32511. 'kappa': 549,
  32512. 'lambda': 549,
  32513. 'mu': 576,
  32514. 'nu': 521,
  32515. 'omicron': 549,
  32516. 'pi': 549,
  32517. 'theta': 521,
  32518. 'rho': 549,
  32519. 'sigma': 603,
  32520. 'tau': 439,
  32521. 'upsilon': 576,
  32522. 'omega1': 713,
  32523. 'omega': 686,
  32524. 'xi': 493,
  32525. 'psi': 686,
  32526. 'zeta': 494,
  32527. 'braceleft': 480,
  32528. 'bar': 200,
  32529. 'braceright': 480,
  32530. 'similar': 549,
  32531. 'Euro': 750,
  32532. 'Upsilon1': 620,
  32533. 'minute': 247,
  32534. 'lessequal': 549,
  32535. 'fraction': 167,
  32536. 'infinity': 713,
  32537. 'florin': 500,
  32538. 'club': 753,
  32539. 'diamond': 753,
  32540. 'heart': 753,
  32541. 'spade': 753,
  32542. 'arrowboth': 1042,
  32543. 'arrowleft': 987,
  32544. 'arrowup': 603,
  32545. 'arrowright': 987,
  32546. 'arrowdown': 603,
  32547. 'degree': 400,
  32548. 'plusminus': 549,
  32549. 'second': 411,
  32550. 'greaterequal': 549,
  32551. 'multiply': 549,
  32552. 'proportional': 713,
  32553. 'partialdiff': 494,
  32554. 'bullet': 460,
  32555. 'divide': 549,
  32556. 'notequal': 549,
  32557. 'equivalence': 549,
  32558. 'approxequal': 549,
  32559. 'ellipsis': 1000,
  32560. 'arrowvertex': 603,
  32561. 'arrowhorizex': 1000,
  32562. 'carriagereturn': 658,
  32563. 'aleph': 823,
  32564. 'Ifraktur': 686,
  32565. 'Rfraktur': 795,
  32566. 'weierstrass': 987,
  32567. 'circlemultiply': 768,
  32568. 'circleplus': 768,
  32569. 'emptyset': 823,
  32570. 'intersection': 768,
  32571. 'union': 768,
  32572. 'propersuperset': 713,
  32573. 'reflexsuperset': 713,
  32574. 'notsubset': 713,
  32575. 'propersubset': 713,
  32576. 'reflexsubset': 713,
  32577. 'element': 713,
  32578. 'notelement': 713,
  32579. 'angle': 768,
  32580. 'gradient': 713,
  32581. 'registerserif': 790,
  32582. 'copyrightserif': 790,
  32583. 'trademarkserif': 890,
  32584. 'product': 823,
  32585. 'radical': 549,
  32586. 'dotmath': 250,
  32587. 'logicalnot': 713,
  32588. 'logicaland': 603,
  32589. 'logicalor': 603,
  32590. 'arrowdblboth': 1042,
  32591. 'arrowdblleft': 987,
  32592. 'arrowdblup': 603,
  32593. 'arrowdblright': 987,
  32594. 'arrowdbldown': 603,
  32595. 'lozenge': 494,
  32596. 'angleleft': 329,
  32597. 'registersans': 790,
  32598. 'copyrightsans': 790,
  32599. 'trademarksans': 786,
  32600. 'summation': 713,
  32601. 'parenlefttp': 384,
  32602. 'parenleftex': 384,
  32603. 'parenleftbt': 384,
  32604. 'bracketlefttp': 384,
  32605. 'bracketleftex': 384,
  32606. 'bracketleftbt': 384,
  32607. 'bracelefttp': 494,
  32608. 'braceleftmid': 494,
  32609. 'braceleftbt': 494,
  32610. 'braceex': 494,
  32611. 'angleright': 329,
  32612. 'integral': 274,
  32613. 'integraltp': 686,
  32614. 'integralex': 686,
  32615. 'integralbt': 686,
  32616. 'parenrighttp': 384,
  32617. 'parenrightex': 384,
  32618. 'parenrightbt': 384,
  32619. 'bracketrighttp': 384,
  32620. 'bracketrightex': 384,
  32621. 'bracketrightbt': 384,
  32622. 'bracerighttp': 494,
  32623. 'bracerightmid': 494,
  32624. 'bracerightbt': 494,
  32625. 'apple': 790
  32626. },
  32627. 'Times-Roman': {
  32628. 'space': 250,
  32629. 'exclam': 333,
  32630. 'quotedbl': 408,
  32631. 'numbersign': 500,
  32632. 'dollar': 500,
  32633. 'percent': 833,
  32634. 'ampersand': 778,
  32635. 'quoteright': 333,
  32636. 'parenleft': 333,
  32637. 'parenright': 333,
  32638. 'asterisk': 500,
  32639. 'plus': 564,
  32640. 'comma': 250,
  32641. 'hyphen': 333,
  32642. 'period': 250,
  32643. 'slash': 278,
  32644. 'zero': 500,
  32645. 'one': 500,
  32646. 'two': 500,
  32647. 'three': 500,
  32648. 'four': 500,
  32649. 'five': 500,
  32650. 'six': 500,
  32651. 'seven': 500,
  32652. 'eight': 500,
  32653. 'nine': 500,
  32654. 'colon': 278,
  32655. 'semicolon': 278,
  32656. 'less': 564,
  32657. 'equal': 564,
  32658. 'greater': 564,
  32659. 'question': 444,
  32660. 'at': 921,
  32661. 'A': 722,
  32662. 'B': 667,
  32663. 'C': 667,
  32664. 'D': 722,
  32665. 'E': 611,
  32666. 'F': 556,
  32667. 'G': 722,
  32668. 'H': 722,
  32669. 'I': 333,
  32670. 'J': 389,
  32671. 'K': 722,
  32672. 'L': 611,
  32673. 'M': 889,
  32674. 'N': 722,
  32675. 'O': 722,
  32676. 'P': 556,
  32677. 'Q': 722,
  32678. 'R': 667,
  32679. 'S': 556,
  32680. 'T': 611,
  32681. 'U': 722,
  32682. 'V': 722,
  32683. 'W': 944,
  32684. 'X': 722,
  32685. 'Y': 722,
  32686. 'Z': 611,
  32687. 'bracketleft': 333,
  32688. 'backslash': 278,
  32689. 'bracketright': 333,
  32690. 'asciicircum': 469,
  32691. 'underscore': 500,
  32692. 'quoteleft': 333,
  32693. 'a': 444,
  32694. 'b': 500,
  32695. 'c': 444,
  32696. 'd': 500,
  32697. 'e': 444,
  32698. 'f': 333,
  32699. 'g': 500,
  32700. 'h': 500,
  32701. 'i': 278,
  32702. 'j': 278,
  32703. 'k': 500,
  32704. 'l': 278,
  32705. 'm': 778,
  32706. 'n': 500,
  32707. 'o': 500,
  32708. 'p': 500,
  32709. 'q': 500,
  32710. 'r': 333,
  32711. 's': 389,
  32712. 't': 278,
  32713. 'u': 500,
  32714. 'v': 500,
  32715. 'w': 722,
  32716. 'x': 500,
  32717. 'y': 500,
  32718. 'z': 444,
  32719. 'braceleft': 480,
  32720. 'bar': 200,
  32721. 'braceright': 480,
  32722. 'asciitilde': 541,
  32723. 'exclamdown': 333,
  32724. 'cent': 500,
  32725. 'sterling': 500,
  32726. 'fraction': 167,
  32727. 'yen': 500,
  32728. 'florin': 500,
  32729. 'section': 500,
  32730. 'currency': 500,
  32731. 'quotesingle': 180,
  32732. 'quotedblleft': 444,
  32733. 'guillemotleft': 500,
  32734. 'guilsinglleft': 333,
  32735. 'guilsinglright': 333,
  32736. 'fi': 556,
  32737. 'fl': 556,
  32738. 'endash': 500,
  32739. 'dagger': 500,
  32740. 'daggerdbl': 500,
  32741. 'periodcentered': 250,
  32742. 'paragraph': 453,
  32743. 'bullet': 350,
  32744. 'quotesinglbase': 333,
  32745. 'quotedblbase': 444,
  32746. 'quotedblright': 444,
  32747. 'guillemotright': 500,
  32748. 'ellipsis': 1000,
  32749. 'perthousand': 1000,
  32750. 'questiondown': 444,
  32751. 'grave': 333,
  32752. 'acute': 333,
  32753. 'circumflex': 333,
  32754. 'tilde': 333,
  32755. 'macron': 333,
  32756. 'breve': 333,
  32757. 'dotaccent': 333,
  32758. 'dieresis': 333,
  32759. 'ring': 333,
  32760. 'cedilla': 333,
  32761. 'hungarumlaut': 333,
  32762. 'ogonek': 333,
  32763. 'caron': 333,
  32764. 'emdash': 1000,
  32765. 'AE': 889,
  32766. 'ordfeminine': 276,
  32767. 'Lslash': 611,
  32768. 'Oslash': 722,
  32769. 'OE': 889,
  32770. 'ordmasculine': 310,
  32771. 'ae': 667,
  32772. 'dotlessi': 278,
  32773. 'lslash': 278,
  32774. 'oslash': 500,
  32775. 'oe': 722,
  32776. 'germandbls': 500,
  32777. 'Idieresis': 333,
  32778. 'eacute': 444,
  32779. 'abreve': 444,
  32780. 'uhungarumlaut': 500,
  32781. 'ecaron': 444,
  32782. 'Ydieresis': 722,
  32783. 'divide': 564,
  32784. 'Yacute': 722,
  32785. 'Acircumflex': 722,
  32786. 'aacute': 444,
  32787. 'Ucircumflex': 722,
  32788. 'yacute': 500,
  32789. 'scommaaccent': 389,
  32790. 'ecircumflex': 444,
  32791. 'Uring': 722,
  32792. 'Udieresis': 722,
  32793. 'aogonek': 444,
  32794. 'Uacute': 722,
  32795. 'uogonek': 500,
  32796. 'Edieresis': 611,
  32797. 'Dcroat': 722,
  32798. 'commaaccent': 250,
  32799. 'copyright': 760,
  32800. 'Emacron': 611,
  32801. 'ccaron': 444,
  32802. 'aring': 444,
  32803. 'Ncommaaccent': 722,
  32804. 'lacute': 278,
  32805. 'agrave': 444,
  32806. 'Tcommaaccent': 611,
  32807. 'Cacute': 667,
  32808. 'atilde': 444,
  32809. 'Edotaccent': 611,
  32810. 'scaron': 389,
  32811. 'scedilla': 389,
  32812. 'iacute': 278,
  32813. 'lozenge': 471,
  32814. 'Rcaron': 667,
  32815. 'Gcommaaccent': 722,
  32816. 'ucircumflex': 500,
  32817. 'acircumflex': 444,
  32818. 'Amacron': 722,
  32819. 'rcaron': 333,
  32820. 'ccedilla': 444,
  32821. 'Zdotaccent': 611,
  32822. 'Thorn': 556,
  32823. 'Omacron': 722,
  32824. 'Racute': 667,
  32825. 'Sacute': 556,
  32826. 'dcaron': 588,
  32827. 'Umacron': 722,
  32828. 'uring': 500,
  32829. 'threesuperior': 300,
  32830. 'Ograve': 722,
  32831. 'Agrave': 722,
  32832. 'Abreve': 722,
  32833. 'multiply': 564,
  32834. 'uacute': 500,
  32835. 'Tcaron': 611,
  32836. 'partialdiff': 476,
  32837. 'ydieresis': 500,
  32838. 'Nacute': 722,
  32839. 'icircumflex': 278,
  32840. 'Ecircumflex': 611,
  32841. 'adieresis': 444,
  32842. 'edieresis': 444,
  32843. 'cacute': 444,
  32844. 'nacute': 500,
  32845. 'umacron': 500,
  32846. 'Ncaron': 722,
  32847. 'Iacute': 333,
  32848. 'plusminus': 564,
  32849. 'brokenbar': 200,
  32850. 'registered': 760,
  32851. 'Gbreve': 722,
  32852. 'Idotaccent': 333,
  32853. 'summation': 600,
  32854. 'Egrave': 611,
  32855. 'racute': 333,
  32856. 'omacron': 500,
  32857. 'Zacute': 611,
  32858. 'Zcaron': 611,
  32859. 'greaterequal': 549,
  32860. 'Eth': 722,
  32861. 'Ccedilla': 667,
  32862. 'lcommaaccent': 278,
  32863. 'tcaron': 326,
  32864. 'eogonek': 444,
  32865. 'Uogonek': 722,
  32866. 'Aacute': 722,
  32867. 'Adieresis': 722,
  32868. 'egrave': 444,
  32869. 'zacute': 444,
  32870. 'iogonek': 278,
  32871. 'Oacute': 722,
  32872. 'oacute': 500,
  32873. 'amacron': 444,
  32874. 'sacute': 389,
  32875. 'idieresis': 278,
  32876. 'Ocircumflex': 722,
  32877. 'Ugrave': 722,
  32878. 'Delta': 612,
  32879. 'thorn': 500,
  32880. 'twosuperior': 300,
  32881. 'Odieresis': 722,
  32882. 'mu': 500,
  32883. 'igrave': 278,
  32884. 'ohungarumlaut': 500,
  32885. 'Eogonek': 611,
  32886. 'dcroat': 500,
  32887. 'threequarters': 750,
  32888. 'Scedilla': 556,
  32889. 'lcaron': 344,
  32890. 'Kcommaaccent': 722,
  32891. 'Lacute': 611,
  32892. 'trademark': 980,
  32893. 'edotaccent': 444,
  32894. 'Igrave': 333,
  32895. 'Imacron': 333,
  32896. 'Lcaron': 611,
  32897. 'onehalf': 750,
  32898. 'lessequal': 549,
  32899. 'ocircumflex': 500,
  32900. 'ntilde': 500,
  32901. 'Uhungarumlaut': 722,
  32902. 'Eacute': 611,
  32903. 'emacron': 444,
  32904. 'gbreve': 500,
  32905. 'onequarter': 750,
  32906. 'Scaron': 556,
  32907. 'Scommaaccent': 556,
  32908. 'Ohungarumlaut': 722,
  32909. 'degree': 400,
  32910. 'ograve': 500,
  32911. 'Ccaron': 667,
  32912. 'ugrave': 500,
  32913. 'radical': 453,
  32914. 'Dcaron': 722,
  32915. 'rcommaaccent': 333,
  32916. 'Ntilde': 722,
  32917. 'otilde': 500,
  32918. 'Rcommaaccent': 667,
  32919. 'Lcommaaccent': 611,
  32920. 'Atilde': 722,
  32921. 'Aogonek': 722,
  32922. 'Aring': 722,
  32923. 'Otilde': 722,
  32924. 'zdotaccent': 444,
  32925. 'Ecaron': 611,
  32926. 'Iogonek': 333,
  32927. 'kcommaaccent': 500,
  32928. 'minus': 564,
  32929. 'Icircumflex': 333,
  32930. 'ncaron': 500,
  32931. 'tcommaaccent': 278,
  32932. 'logicalnot': 564,
  32933. 'odieresis': 500,
  32934. 'udieresis': 500,
  32935. 'notequal': 549,
  32936. 'gcommaaccent': 500,
  32937. 'eth': 500,
  32938. 'zcaron': 444,
  32939. 'ncommaaccent': 500,
  32940. 'onesuperior': 300,
  32941. 'imacron': 278,
  32942. 'Euro': 500
  32943. },
  32944. 'Times-Bold': {
  32945. 'space': 250,
  32946. 'exclam': 333,
  32947. 'quotedbl': 555,
  32948. 'numbersign': 500,
  32949. 'dollar': 500,
  32950. 'percent': 1000,
  32951. 'ampersand': 833,
  32952. 'quoteright': 333,
  32953. 'parenleft': 333,
  32954. 'parenright': 333,
  32955. 'asterisk': 500,
  32956. 'plus': 570,
  32957. 'comma': 250,
  32958. 'hyphen': 333,
  32959. 'period': 250,
  32960. 'slash': 278,
  32961. 'zero': 500,
  32962. 'one': 500,
  32963. 'two': 500,
  32964. 'three': 500,
  32965. 'four': 500,
  32966. 'five': 500,
  32967. 'six': 500,
  32968. 'seven': 500,
  32969. 'eight': 500,
  32970. 'nine': 500,
  32971. 'colon': 333,
  32972. 'semicolon': 333,
  32973. 'less': 570,
  32974. 'equal': 570,
  32975. 'greater': 570,
  32976. 'question': 500,
  32977. 'at': 930,
  32978. 'A': 722,
  32979. 'B': 667,
  32980. 'C': 722,
  32981. 'D': 722,
  32982. 'E': 667,
  32983. 'F': 611,
  32984. 'G': 778,
  32985. 'H': 778,
  32986. 'I': 389,
  32987. 'J': 500,
  32988. 'K': 778,
  32989. 'L': 667,
  32990. 'M': 944,
  32991. 'N': 722,
  32992. 'O': 778,
  32993. 'P': 611,
  32994. 'Q': 778,
  32995. 'R': 722,
  32996. 'S': 556,
  32997. 'T': 667,
  32998. 'U': 722,
  32999. 'V': 722,
  33000. 'W': 1000,
  33001. 'X': 722,
  33002. 'Y': 722,
  33003. 'Z': 667,
  33004. 'bracketleft': 333,
  33005. 'backslash': 278,
  33006. 'bracketright': 333,
  33007. 'asciicircum': 581,
  33008. 'underscore': 500,
  33009. 'quoteleft': 333,
  33010. 'a': 500,
  33011. 'b': 556,
  33012. 'c': 444,
  33013. 'd': 556,
  33014. 'e': 444,
  33015. 'f': 333,
  33016. 'g': 500,
  33017. 'h': 556,
  33018. 'i': 278,
  33019. 'j': 333,
  33020. 'k': 556,
  33021. 'l': 278,
  33022. 'm': 833,
  33023. 'n': 556,
  33024. 'o': 500,
  33025. 'p': 556,
  33026. 'q': 556,
  33027. 'r': 444,
  33028. 's': 389,
  33029. 't': 333,
  33030. 'u': 556,
  33031. 'v': 500,
  33032. 'w': 722,
  33033. 'x': 500,
  33034. 'y': 500,
  33035. 'z': 444,
  33036. 'braceleft': 394,
  33037. 'bar': 220,
  33038. 'braceright': 394,
  33039. 'asciitilde': 520,
  33040. 'exclamdown': 333,
  33041. 'cent': 500,
  33042. 'sterling': 500,
  33043. 'fraction': 167,
  33044. 'yen': 500,
  33045. 'florin': 500,
  33046. 'section': 500,
  33047. 'currency': 500,
  33048. 'quotesingle': 278,
  33049. 'quotedblleft': 500,
  33050. 'guillemotleft': 500,
  33051. 'guilsinglleft': 333,
  33052. 'guilsinglright': 333,
  33053. 'fi': 556,
  33054. 'fl': 556,
  33055. 'endash': 500,
  33056. 'dagger': 500,
  33057. 'daggerdbl': 500,
  33058. 'periodcentered': 250,
  33059. 'paragraph': 540,
  33060. 'bullet': 350,
  33061. 'quotesinglbase': 333,
  33062. 'quotedblbase': 500,
  33063. 'quotedblright': 500,
  33064. 'guillemotright': 500,
  33065. 'ellipsis': 1000,
  33066. 'perthousand': 1000,
  33067. 'questiondown': 500,
  33068. 'grave': 333,
  33069. 'acute': 333,
  33070. 'circumflex': 333,
  33071. 'tilde': 333,
  33072. 'macron': 333,
  33073. 'breve': 333,
  33074. 'dotaccent': 333,
  33075. 'dieresis': 333,
  33076. 'ring': 333,
  33077. 'cedilla': 333,
  33078. 'hungarumlaut': 333,
  33079. 'ogonek': 333,
  33080. 'caron': 333,
  33081. 'emdash': 1000,
  33082. 'AE': 1000,
  33083. 'ordfeminine': 300,
  33084. 'Lslash': 667,
  33085. 'Oslash': 778,
  33086. 'OE': 1000,
  33087. 'ordmasculine': 330,
  33088. 'ae': 722,
  33089. 'dotlessi': 278,
  33090. 'lslash': 278,
  33091. 'oslash': 500,
  33092. 'oe': 722,
  33093. 'germandbls': 556,
  33094. 'Idieresis': 389,
  33095. 'eacute': 444,
  33096. 'abreve': 500,
  33097. 'uhungarumlaut': 556,
  33098. 'ecaron': 444,
  33099. 'Ydieresis': 722,
  33100. 'divide': 570,
  33101. 'Yacute': 722,
  33102. 'Acircumflex': 722,
  33103. 'aacute': 500,
  33104. 'Ucircumflex': 722,
  33105. 'yacute': 500,
  33106. 'scommaaccent': 389,
  33107. 'ecircumflex': 444,
  33108. 'Uring': 722,
  33109. 'Udieresis': 722,
  33110. 'aogonek': 500,
  33111. 'Uacute': 722,
  33112. 'uogonek': 556,
  33113. 'Edieresis': 667,
  33114. 'Dcroat': 722,
  33115. 'commaaccent': 250,
  33116. 'copyright': 747,
  33117. 'Emacron': 667,
  33118. 'ccaron': 444,
  33119. 'aring': 500,
  33120. 'Ncommaaccent': 722,
  33121. 'lacute': 278,
  33122. 'agrave': 500,
  33123. 'Tcommaaccent': 667,
  33124. 'Cacute': 722,
  33125. 'atilde': 500,
  33126. 'Edotaccent': 667,
  33127. 'scaron': 389,
  33128. 'scedilla': 389,
  33129. 'iacute': 278,
  33130. 'lozenge': 494,
  33131. 'Rcaron': 722,
  33132. 'Gcommaaccent': 778,
  33133. 'ucircumflex': 556,
  33134. 'acircumflex': 500,
  33135. 'Amacron': 722,
  33136. 'rcaron': 444,
  33137. 'ccedilla': 444,
  33138. 'Zdotaccent': 667,
  33139. 'Thorn': 611,
  33140. 'Omacron': 778,
  33141. 'Racute': 722,
  33142. 'Sacute': 556,
  33143. 'dcaron': 672,
  33144. 'Umacron': 722,
  33145. 'uring': 556,
  33146. 'threesuperior': 300,
  33147. 'Ograve': 778,
  33148. 'Agrave': 722,
  33149. 'Abreve': 722,
  33150. 'multiply': 570,
  33151. 'uacute': 556,
  33152. 'Tcaron': 667,
  33153. 'partialdiff': 494,
  33154. 'ydieresis': 500,
  33155. 'Nacute': 722,
  33156. 'icircumflex': 278,
  33157. 'Ecircumflex': 667,
  33158. 'adieresis': 500,
  33159. 'edieresis': 444,
  33160. 'cacute': 444,
  33161. 'nacute': 556,
  33162. 'umacron': 556,
  33163. 'Ncaron': 722,
  33164. 'Iacute': 389,
  33165. 'plusminus': 570,
  33166. 'brokenbar': 220,
  33167. 'registered': 747,
  33168. 'Gbreve': 778,
  33169. 'Idotaccent': 389,
  33170. 'summation': 600,
  33171. 'Egrave': 667,
  33172. 'racute': 444,
  33173. 'omacron': 500,
  33174. 'Zacute': 667,
  33175. 'Zcaron': 667,
  33176. 'greaterequal': 549,
  33177. 'Eth': 722,
  33178. 'Ccedilla': 722,
  33179. 'lcommaaccent': 278,
  33180. 'tcaron': 416,
  33181. 'eogonek': 444,
  33182. 'Uogonek': 722,
  33183. 'Aacute': 722,
  33184. 'Adieresis': 722,
  33185. 'egrave': 444,
  33186. 'zacute': 444,
  33187. 'iogonek': 278,
  33188. 'Oacute': 778,
  33189. 'oacute': 500,
  33190. 'amacron': 500,
  33191. 'sacute': 389,
  33192. 'idieresis': 278,
  33193. 'Ocircumflex': 778,
  33194. 'Ugrave': 722,
  33195. 'Delta': 612,
  33196. 'thorn': 556,
  33197. 'twosuperior': 300,
  33198. 'Odieresis': 778,
  33199. 'mu': 556,
  33200. 'igrave': 278,
  33201. 'ohungarumlaut': 500,
  33202. 'Eogonek': 667,
  33203. 'dcroat': 556,
  33204. 'threequarters': 750,
  33205. 'Scedilla': 556,
  33206. 'lcaron': 394,
  33207. 'Kcommaaccent': 778,
  33208. 'Lacute': 667,
  33209. 'trademark': 1000,
  33210. 'edotaccent': 444,
  33211. 'Igrave': 389,
  33212. 'Imacron': 389,
  33213. 'Lcaron': 667,
  33214. 'onehalf': 750,
  33215. 'lessequal': 549,
  33216. 'ocircumflex': 500,
  33217. 'ntilde': 556,
  33218. 'Uhungarumlaut': 722,
  33219. 'Eacute': 667,
  33220. 'emacron': 444,
  33221. 'gbreve': 500,
  33222. 'onequarter': 750,
  33223. 'Scaron': 556,
  33224. 'Scommaaccent': 556,
  33225. 'Ohungarumlaut': 778,
  33226. 'degree': 400,
  33227. 'ograve': 500,
  33228. 'Ccaron': 722,
  33229. 'ugrave': 556,
  33230. 'radical': 549,
  33231. 'Dcaron': 722,
  33232. 'rcommaaccent': 444,
  33233. 'Ntilde': 722,
  33234. 'otilde': 500,
  33235. 'Rcommaaccent': 722,
  33236. 'Lcommaaccent': 667,
  33237. 'Atilde': 722,
  33238. 'Aogonek': 722,
  33239. 'Aring': 722,
  33240. 'Otilde': 778,
  33241. 'zdotaccent': 444,
  33242. 'Ecaron': 667,
  33243. 'Iogonek': 389,
  33244. 'kcommaaccent': 556,
  33245. 'minus': 570,
  33246. 'Icircumflex': 389,
  33247. 'ncaron': 556,
  33248. 'tcommaaccent': 333,
  33249. 'logicalnot': 570,
  33250. 'odieresis': 500,
  33251. 'udieresis': 556,
  33252. 'notequal': 549,
  33253. 'gcommaaccent': 500,
  33254. 'eth': 500,
  33255. 'zcaron': 444,
  33256. 'ncommaaccent': 556,
  33257. 'onesuperior': 300,
  33258. 'imacron': 278,
  33259. 'Euro': 500
  33260. },
  33261. 'Times-BoldItalic': {
  33262. 'space': 250,
  33263. 'exclam': 389,
  33264. 'quotedbl': 555,
  33265. 'numbersign': 500,
  33266. 'dollar': 500,
  33267. 'percent': 833,
  33268. 'ampersand': 778,
  33269. 'quoteright': 333,
  33270. 'parenleft': 333,
  33271. 'parenright': 333,
  33272. 'asterisk': 500,
  33273. 'plus': 570,
  33274. 'comma': 250,
  33275. 'hyphen': 333,
  33276. 'period': 250,
  33277. 'slash': 278,
  33278. 'zero': 500,
  33279. 'one': 500,
  33280. 'two': 500,
  33281. 'three': 500,
  33282. 'four': 500,
  33283. 'five': 500,
  33284. 'six': 500,
  33285. 'seven': 500,
  33286. 'eight': 500,
  33287. 'nine': 500,
  33288. 'colon': 333,
  33289. 'semicolon': 333,
  33290. 'less': 570,
  33291. 'equal': 570,
  33292. 'greater': 570,
  33293. 'question': 500,
  33294. 'at': 832,
  33295. 'A': 667,
  33296. 'B': 667,
  33297. 'C': 667,
  33298. 'D': 722,
  33299. 'E': 667,
  33300. 'F': 667,
  33301. 'G': 722,
  33302. 'H': 778,
  33303. 'I': 389,
  33304. 'J': 500,
  33305. 'K': 667,
  33306. 'L': 611,
  33307. 'M': 889,
  33308. 'N': 722,
  33309. 'O': 722,
  33310. 'P': 611,
  33311. 'Q': 722,
  33312. 'R': 667,
  33313. 'S': 556,
  33314. 'T': 611,
  33315. 'U': 722,
  33316. 'V': 667,
  33317. 'W': 889,
  33318. 'X': 667,
  33319. 'Y': 611,
  33320. 'Z': 611,
  33321. 'bracketleft': 333,
  33322. 'backslash': 278,
  33323. 'bracketright': 333,
  33324. 'asciicircum': 570,
  33325. 'underscore': 500,
  33326. 'quoteleft': 333,
  33327. 'a': 500,
  33328. 'b': 500,
  33329. 'c': 444,
  33330. 'd': 500,
  33331. 'e': 444,
  33332. 'f': 333,
  33333. 'g': 500,
  33334. 'h': 556,
  33335. 'i': 278,
  33336. 'j': 278,
  33337. 'k': 500,
  33338. 'l': 278,
  33339. 'm': 778,
  33340. 'n': 556,
  33341. 'o': 500,
  33342. 'p': 500,
  33343. 'q': 500,
  33344. 'r': 389,
  33345. 's': 389,
  33346. 't': 278,
  33347. 'u': 556,
  33348. 'v': 444,
  33349. 'w': 667,
  33350. 'x': 500,
  33351. 'y': 444,
  33352. 'z': 389,
  33353. 'braceleft': 348,
  33354. 'bar': 220,
  33355. 'braceright': 348,
  33356. 'asciitilde': 570,
  33357. 'exclamdown': 389,
  33358. 'cent': 500,
  33359. 'sterling': 500,
  33360. 'fraction': 167,
  33361. 'yen': 500,
  33362. 'florin': 500,
  33363. 'section': 500,
  33364. 'currency': 500,
  33365. 'quotesingle': 278,
  33366. 'quotedblleft': 500,
  33367. 'guillemotleft': 500,
  33368. 'guilsinglleft': 333,
  33369. 'guilsinglright': 333,
  33370. 'fi': 556,
  33371. 'fl': 556,
  33372. 'endash': 500,
  33373. 'dagger': 500,
  33374. 'daggerdbl': 500,
  33375. 'periodcentered': 250,
  33376. 'paragraph': 500,
  33377. 'bullet': 350,
  33378. 'quotesinglbase': 333,
  33379. 'quotedblbase': 500,
  33380. 'quotedblright': 500,
  33381. 'guillemotright': 500,
  33382. 'ellipsis': 1000,
  33383. 'perthousand': 1000,
  33384. 'questiondown': 500,
  33385. 'grave': 333,
  33386. 'acute': 333,
  33387. 'circumflex': 333,
  33388. 'tilde': 333,
  33389. 'macron': 333,
  33390. 'breve': 333,
  33391. 'dotaccent': 333,
  33392. 'dieresis': 333,
  33393. 'ring': 333,
  33394. 'cedilla': 333,
  33395. 'hungarumlaut': 333,
  33396. 'ogonek': 333,
  33397. 'caron': 333,
  33398. 'emdash': 1000,
  33399. 'AE': 944,
  33400. 'ordfeminine': 266,
  33401. 'Lslash': 611,
  33402. 'Oslash': 722,
  33403. 'OE': 944,
  33404. 'ordmasculine': 300,
  33405. 'ae': 722,
  33406. 'dotlessi': 278,
  33407. 'lslash': 278,
  33408. 'oslash': 500,
  33409. 'oe': 722,
  33410. 'germandbls': 500,
  33411. 'Idieresis': 389,
  33412. 'eacute': 444,
  33413. 'abreve': 500,
  33414. 'uhungarumlaut': 556,
  33415. 'ecaron': 444,
  33416. 'Ydieresis': 611,
  33417. 'divide': 570,
  33418. 'Yacute': 611,
  33419. 'Acircumflex': 667,
  33420. 'aacute': 500,
  33421. 'Ucircumflex': 722,
  33422. 'yacute': 444,
  33423. 'scommaaccent': 389,
  33424. 'ecircumflex': 444,
  33425. 'Uring': 722,
  33426. 'Udieresis': 722,
  33427. 'aogonek': 500,
  33428. 'Uacute': 722,
  33429. 'uogonek': 556,
  33430. 'Edieresis': 667,
  33431. 'Dcroat': 722,
  33432. 'commaaccent': 250,
  33433. 'copyright': 747,
  33434. 'Emacron': 667,
  33435. 'ccaron': 444,
  33436. 'aring': 500,
  33437. 'Ncommaaccent': 722,
  33438. 'lacute': 278,
  33439. 'agrave': 500,
  33440. 'Tcommaaccent': 611,
  33441. 'Cacute': 667,
  33442. 'atilde': 500,
  33443. 'Edotaccent': 667,
  33444. 'scaron': 389,
  33445. 'scedilla': 389,
  33446. 'iacute': 278,
  33447. 'lozenge': 494,
  33448. 'Rcaron': 667,
  33449. 'Gcommaaccent': 722,
  33450. 'ucircumflex': 556,
  33451. 'acircumflex': 500,
  33452. 'Amacron': 667,
  33453. 'rcaron': 389,
  33454. 'ccedilla': 444,
  33455. 'Zdotaccent': 611,
  33456. 'Thorn': 611,
  33457. 'Omacron': 722,
  33458. 'Racute': 667,
  33459. 'Sacute': 556,
  33460. 'dcaron': 608,
  33461. 'Umacron': 722,
  33462. 'uring': 556,
  33463. 'threesuperior': 300,
  33464. 'Ograve': 722,
  33465. 'Agrave': 667,
  33466. 'Abreve': 667,
  33467. 'multiply': 570,
  33468. 'uacute': 556,
  33469. 'Tcaron': 611,
  33470. 'partialdiff': 494,
  33471. 'ydieresis': 444,
  33472. 'Nacute': 722,
  33473. 'icircumflex': 278,
  33474. 'Ecircumflex': 667,
  33475. 'adieresis': 500,
  33476. 'edieresis': 444,
  33477. 'cacute': 444,
  33478. 'nacute': 556,
  33479. 'umacron': 556,
  33480. 'Ncaron': 722,
  33481. 'Iacute': 389,
  33482. 'plusminus': 570,
  33483. 'brokenbar': 220,
  33484. 'registered': 747,
  33485. 'Gbreve': 722,
  33486. 'Idotaccent': 389,
  33487. 'summation': 600,
  33488. 'Egrave': 667,
  33489. 'racute': 389,
  33490. 'omacron': 500,
  33491. 'Zacute': 611,
  33492. 'Zcaron': 611,
  33493. 'greaterequal': 549,
  33494. 'Eth': 722,
  33495. 'Ccedilla': 667,
  33496. 'lcommaaccent': 278,
  33497. 'tcaron': 366,
  33498. 'eogonek': 444,
  33499. 'Uogonek': 722,
  33500. 'Aacute': 667,
  33501. 'Adieresis': 667,
  33502. 'egrave': 444,
  33503. 'zacute': 389,
  33504. 'iogonek': 278,
  33505. 'Oacute': 722,
  33506. 'oacute': 500,
  33507. 'amacron': 500,
  33508. 'sacute': 389,
  33509. 'idieresis': 278,
  33510. 'Ocircumflex': 722,
  33511. 'Ugrave': 722,
  33512. 'Delta': 612,
  33513. 'thorn': 500,
  33514. 'twosuperior': 300,
  33515. 'Odieresis': 722,
  33516. 'mu': 576,
  33517. 'igrave': 278,
  33518. 'ohungarumlaut': 500,
  33519. 'Eogonek': 667,
  33520. 'dcroat': 500,
  33521. 'threequarters': 750,
  33522. 'Scedilla': 556,
  33523. 'lcaron': 382,
  33524. 'Kcommaaccent': 667,
  33525. 'Lacute': 611,
  33526. 'trademark': 1000,
  33527. 'edotaccent': 444,
  33528. 'Igrave': 389,
  33529. 'Imacron': 389,
  33530. 'Lcaron': 611,
  33531. 'onehalf': 750,
  33532. 'lessequal': 549,
  33533. 'ocircumflex': 500,
  33534. 'ntilde': 556,
  33535. 'Uhungarumlaut': 722,
  33536. 'Eacute': 667,
  33537. 'emacron': 444,
  33538. 'gbreve': 500,
  33539. 'onequarter': 750,
  33540. 'Scaron': 556,
  33541. 'Scommaaccent': 556,
  33542. 'Ohungarumlaut': 722,
  33543. 'degree': 400,
  33544. 'ograve': 500,
  33545. 'Ccaron': 667,
  33546. 'ugrave': 556,
  33547. 'radical': 549,
  33548. 'Dcaron': 722,
  33549. 'rcommaaccent': 389,
  33550. 'Ntilde': 722,
  33551. 'otilde': 500,
  33552. 'Rcommaaccent': 667,
  33553. 'Lcommaaccent': 611,
  33554. 'Atilde': 667,
  33555. 'Aogonek': 667,
  33556. 'Aring': 667,
  33557. 'Otilde': 722,
  33558. 'zdotaccent': 389,
  33559. 'Ecaron': 667,
  33560. 'Iogonek': 389,
  33561. 'kcommaaccent': 500,
  33562. 'minus': 606,
  33563. 'Icircumflex': 389,
  33564. 'ncaron': 556,
  33565. 'tcommaaccent': 278,
  33566. 'logicalnot': 606,
  33567. 'odieresis': 500,
  33568. 'udieresis': 556,
  33569. 'notequal': 549,
  33570. 'gcommaaccent': 500,
  33571. 'eth': 500,
  33572. 'zcaron': 389,
  33573. 'ncommaaccent': 556,
  33574. 'onesuperior': 300,
  33575. 'imacron': 278,
  33576. 'Euro': 500
  33577. },
  33578. 'Times-Italic': {
  33579. 'space': 250,
  33580. 'exclam': 333,
  33581. 'quotedbl': 420,
  33582. 'numbersign': 500,
  33583. 'dollar': 500,
  33584. 'percent': 833,
  33585. 'ampersand': 778,
  33586. 'quoteright': 333,
  33587. 'parenleft': 333,
  33588. 'parenright': 333,
  33589. 'asterisk': 500,
  33590. 'plus': 675,
  33591. 'comma': 250,
  33592. 'hyphen': 333,
  33593. 'period': 250,
  33594. 'slash': 278,
  33595. 'zero': 500,
  33596. 'one': 500,
  33597. 'two': 500,
  33598. 'three': 500,
  33599. 'four': 500,
  33600. 'five': 500,
  33601. 'six': 500,
  33602. 'seven': 500,
  33603. 'eight': 500,
  33604. 'nine': 500,
  33605. 'colon': 333,
  33606. 'semicolon': 333,
  33607. 'less': 675,
  33608. 'equal': 675,
  33609. 'greater': 675,
  33610. 'question': 500,
  33611. 'at': 920,
  33612. 'A': 611,
  33613. 'B': 611,
  33614. 'C': 667,
  33615. 'D': 722,
  33616. 'E': 611,
  33617. 'F': 611,
  33618. 'G': 722,
  33619. 'H': 722,
  33620. 'I': 333,
  33621. 'J': 444,
  33622. 'K': 667,
  33623. 'L': 556,
  33624. 'M': 833,
  33625. 'N': 667,
  33626. 'O': 722,
  33627. 'P': 611,
  33628. 'Q': 722,
  33629. 'R': 611,
  33630. 'S': 500,
  33631. 'T': 556,
  33632. 'U': 722,
  33633. 'V': 611,
  33634. 'W': 833,
  33635. 'X': 611,
  33636. 'Y': 556,
  33637. 'Z': 556,
  33638. 'bracketleft': 389,
  33639. 'backslash': 278,
  33640. 'bracketright': 389,
  33641. 'asciicircum': 422,
  33642. 'underscore': 500,
  33643. 'quoteleft': 333,
  33644. 'a': 500,
  33645. 'b': 500,
  33646. 'c': 444,
  33647. 'd': 500,
  33648. 'e': 444,
  33649. 'f': 278,
  33650. 'g': 500,
  33651. 'h': 500,
  33652. 'i': 278,
  33653. 'j': 278,
  33654. 'k': 444,
  33655. 'l': 278,
  33656. 'm': 722,
  33657. 'n': 500,
  33658. 'o': 500,
  33659. 'p': 500,
  33660. 'q': 500,
  33661. 'r': 389,
  33662. 's': 389,
  33663. 't': 278,
  33664. 'u': 500,
  33665. 'v': 444,
  33666. 'w': 667,
  33667. 'x': 444,
  33668. 'y': 444,
  33669. 'z': 389,
  33670. 'braceleft': 400,
  33671. 'bar': 275,
  33672. 'braceright': 400,
  33673. 'asciitilde': 541,
  33674. 'exclamdown': 389,
  33675. 'cent': 500,
  33676. 'sterling': 500,
  33677. 'fraction': 167,
  33678. 'yen': 500,
  33679. 'florin': 500,
  33680. 'section': 500,
  33681. 'currency': 500,
  33682. 'quotesingle': 214,
  33683. 'quotedblleft': 556,
  33684. 'guillemotleft': 500,
  33685. 'guilsinglleft': 333,
  33686. 'guilsinglright': 333,
  33687. 'fi': 500,
  33688. 'fl': 500,
  33689. 'endash': 500,
  33690. 'dagger': 500,
  33691. 'daggerdbl': 500,
  33692. 'periodcentered': 250,
  33693. 'paragraph': 523,
  33694. 'bullet': 350,
  33695. 'quotesinglbase': 333,
  33696. 'quotedblbase': 556,
  33697. 'quotedblright': 556,
  33698. 'guillemotright': 500,
  33699. 'ellipsis': 889,
  33700. 'perthousand': 1000,
  33701. 'questiondown': 500,
  33702. 'grave': 333,
  33703. 'acute': 333,
  33704. 'circumflex': 333,
  33705. 'tilde': 333,
  33706. 'macron': 333,
  33707. 'breve': 333,
  33708. 'dotaccent': 333,
  33709. 'dieresis': 333,
  33710. 'ring': 333,
  33711. 'cedilla': 333,
  33712. 'hungarumlaut': 333,
  33713. 'ogonek': 333,
  33714. 'caron': 333,
  33715. 'emdash': 889,
  33716. 'AE': 889,
  33717. 'ordfeminine': 276,
  33718. 'Lslash': 556,
  33719. 'Oslash': 722,
  33720. 'OE': 944,
  33721. 'ordmasculine': 310,
  33722. 'ae': 667,
  33723. 'dotlessi': 278,
  33724. 'lslash': 278,
  33725. 'oslash': 500,
  33726. 'oe': 667,
  33727. 'germandbls': 500,
  33728. 'Idieresis': 333,
  33729. 'eacute': 444,
  33730. 'abreve': 500,
  33731. 'uhungarumlaut': 500,
  33732. 'ecaron': 444,
  33733. 'Ydieresis': 556,
  33734. 'divide': 675,
  33735. 'Yacute': 556,
  33736. 'Acircumflex': 611,
  33737. 'aacute': 500,
  33738. 'Ucircumflex': 722,
  33739. 'yacute': 444,
  33740. 'scommaaccent': 389,
  33741. 'ecircumflex': 444,
  33742. 'Uring': 722,
  33743. 'Udieresis': 722,
  33744. 'aogonek': 500,
  33745. 'Uacute': 722,
  33746. 'uogonek': 500,
  33747. 'Edieresis': 611,
  33748. 'Dcroat': 722,
  33749. 'commaaccent': 250,
  33750. 'copyright': 760,
  33751. 'Emacron': 611,
  33752. 'ccaron': 444,
  33753. 'aring': 500,
  33754. 'Ncommaaccent': 667,
  33755. 'lacute': 278,
  33756. 'agrave': 500,
  33757. 'Tcommaaccent': 556,
  33758. 'Cacute': 667,
  33759. 'atilde': 500,
  33760. 'Edotaccent': 611,
  33761. 'scaron': 389,
  33762. 'scedilla': 389,
  33763. 'iacute': 278,
  33764. 'lozenge': 471,
  33765. 'Rcaron': 611,
  33766. 'Gcommaaccent': 722,
  33767. 'ucircumflex': 500,
  33768. 'acircumflex': 500,
  33769. 'Amacron': 611,
  33770. 'rcaron': 389,
  33771. 'ccedilla': 444,
  33772. 'Zdotaccent': 556,
  33773. 'Thorn': 611,
  33774. 'Omacron': 722,
  33775. 'Racute': 611,
  33776. 'Sacute': 500,
  33777. 'dcaron': 544,
  33778. 'Umacron': 722,
  33779. 'uring': 500,
  33780. 'threesuperior': 300,
  33781. 'Ograve': 722,
  33782. 'Agrave': 611,
  33783. 'Abreve': 611,
  33784. 'multiply': 675,
  33785. 'uacute': 500,
  33786. 'Tcaron': 556,
  33787. 'partialdiff': 476,
  33788. 'ydieresis': 444,
  33789. 'Nacute': 667,
  33790. 'icircumflex': 278,
  33791. 'Ecircumflex': 611,
  33792. 'adieresis': 500,
  33793. 'edieresis': 444,
  33794. 'cacute': 444,
  33795. 'nacute': 500,
  33796. 'umacron': 500,
  33797. 'Ncaron': 667,
  33798. 'Iacute': 333,
  33799. 'plusminus': 675,
  33800. 'brokenbar': 275,
  33801. 'registered': 760,
  33802. 'Gbreve': 722,
  33803. 'Idotaccent': 333,
  33804. 'summation': 600,
  33805. 'Egrave': 611,
  33806. 'racute': 389,
  33807. 'omacron': 500,
  33808. 'Zacute': 556,
  33809. 'Zcaron': 556,
  33810. 'greaterequal': 549,
  33811. 'Eth': 722,
  33812. 'Ccedilla': 667,
  33813. 'lcommaaccent': 278,
  33814. 'tcaron': 300,
  33815. 'eogonek': 444,
  33816. 'Uogonek': 722,
  33817. 'Aacute': 611,
  33818. 'Adieresis': 611,
  33819. 'egrave': 444,
  33820. 'zacute': 389,
  33821. 'iogonek': 278,
  33822. 'Oacute': 722,
  33823. 'oacute': 500,
  33824. 'amacron': 500,
  33825. 'sacute': 389,
  33826. 'idieresis': 278,
  33827. 'Ocircumflex': 722,
  33828. 'Ugrave': 722,
  33829. 'Delta': 612,
  33830. 'thorn': 500,
  33831. 'twosuperior': 300,
  33832. 'Odieresis': 722,
  33833. 'mu': 500,
  33834. 'igrave': 278,
  33835. 'ohungarumlaut': 500,
  33836. 'Eogonek': 611,
  33837. 'dcroat': 500,
  33838. 'threequarters': 750,
  33839. 'Scedilla': 500,
  33840. 'lcaron': 300,
  33841. 'Kcommaaccent': 667,
  33842. 'Lacute': 556,
  33843. 'trademark': 980,
  33844. 'edotaccent': 444,
  33845. 'Igrave': 333,
  33846. 'Imacron': 333,
  33847. 'Lcaron': 611,
  33848. 'onehalf': 750,
  33849. 'lessequal': 549,
  33850. 'ocircumflex': 500,
  33851. 'ntilde': 500,
  33852. 'Uhungarumlaut': 722,
  33853. 'Eacute': 611,
  33854. 'emacron': 444,
  33855. 'gbreve': 500,
  33856. 'onequarter': 750,
  33857. 'Scaron': 500,
  33858. 'Scommaaccent': 500,
  33859. 'Ohungarumlaut': 722,
  33860. 'degree': 400,
  33861. 'ograve': 500,
  33862. 'Ccaron': 667,
  33863. 'ugrave': 500,
  33864. 'radical': 453,
  33865. 'Dcaron': 722,
  33866. 'rcommaaccent': 389,
  33867. 'Ntilde': 667,
  33868. 'otilde': 500,
  33869. 'Rcommaaccent': 611,
  33870. 'Lcommaaccent': 556,
  33871. 'Atilde': 611,
  33872. 'Aogonek': 611,
  33873. 'Aring': 611,
  33874. 'Otilde': 722,
  33875. 'zdotaccent': 389,
  33876. 'Ecaron': 611,
  33877. 'Iogonek': 333,
  33878. 'kcommaaccent': 444,
  33879. 'minus': 675,
  33880. 'Icircumflex': 333,
  33881. 'ncaron': 500,
  33882. 'tcommaaccent': 278,
  33883. 'logicalnot': 675,
  33884. 'odieresis': 500,
  33885. 'udieresis': 500,
  33886. 'notequal': 549,
  33887. 'gcommaaccent': 500,
  33888. 'eth': 500,
  33889. 'zcaron': 389,
  33890. 'ncommaaccent': 500,
  33891. 'onesuperior': 300,
  33892. 'imacron': 278,
  33893. 'Euro': 500
  33894. },
  33895. 'ZapfDingbats': {
  33896. 'space': 278,
  33897. 'a1': 974,
  33898. 'a2': 961,
  33899. 'a202': 974,
  33900. 'a3': 980,
  33901. 'a4': 719,
  33902. 'a5': 789,
  33903. 'a119': 790,
  33904. 'a118': 791,
  33905. 'a117': 690,
  33906. 'a11': 960,
  33907. 'a12': 939,
  33908. 'a13': 549,
  33909. 'a14': 855,
  33910. 'a15': 911,
  33911. 'a16': 933,
  33912. 'a105': 911,
  33913. 'a17': 945,
  33914. 'a18': 974,
  33915. 'a19': 755,
  33916. 'a20': 846,
  33917. 'a21': 762,
  33918. 'a22': 761,
  33919. 'a23': 571,
  33920. 'a24': 677,
  33921. 'a25': 763,
  33922. 'a26': 760,
  33923. 'a27': 759,
  33924. 'a28': 754,
  33925. 'a6': 494,
  33926. 'a7': 552,
  33927. 'a8': 537,
  33928. 'a9': 577,
  33929. 'a10': 692,
  33930. 'a29': 786,
  33931. 'a30': 788,
  33932. 'a31': 788,
  33933. 'a32': 790,
  33934. 'a33': 793,
  33935. 'a34': 794,
  33936. 'a35': 816,
  33937. 'a36': 823,
  33938. 'a37': 789,
  33939. 'a38': 841,
  33940. 'a39': 823,
  33941. 'a40': 833,
  33942. 'a41': 816,
  33943. 'a42': 831,
  33944. 'a43': 923,
  33945. 'a44': 744,
  33946. 'a45': 723,
  33947. 'a46': 749,
  33948. 'a47': 790,
  33949. 'a48': 792,
  33950. 'a49': 695,
  33951. 'a50': 776,
  33952. 'a51': 768,
  33953. 'a52': 792,
  33954. 'a53': 759,
  33955. 'a54': 707,
  33956. 'a55': 708,
  33957. 'a56': 682,
  33958. 'a57': 701,
  33959. 'a58': 826,
  33960. 'a59': 815,
  33961. 'a60': 789,
  33962. 'a61': 789,
  33963. 'a62': 707,
  33964. 'a63': 687,
  33965. 'a64': 696,
  33966. 'a65': 689,
  33967. 'a66': 786,
  33968. 'a67': 787,
  33969. 'a68': 713,
  33970. 'a69': 791,
  33971. 'a70': 785,
  33972. 'a71': 791,
  33973. 'a72': 873,
  33974. 'a73': 761,
  33975. 'a74': 762,
  33976. 'a203': 762,
  33977. 'a75': 759,
  33978. 'a204': 759,
  33979. 'a76': 892,
  33980. 'a77': 892,
  33981. 'a78': 788,
  33982. 'a79': 784,
  33983. 'a81': 438,
  33984. 'a82': 138,
  33985. 'a83': 277,
  33986. 'a84': 415,
  33987. 'a97': 392,
  33988. 'a98': 392,
  33989. 'a99': 668,
  33990. 'a100': 668,
  33991. 'a89': 390,
  33992. 'a90': 390,
  33993. 'a93': 317,
  33994. 'a94': 317,
  33995. 'a91': 276,
  33996. 'a92': 276,
  33997. 'a205': 509,
  33998. 'a85': 509,
  33999. 'a206': 410,
  34000. 'a86': 410,
  34001. 'a87': 234,
  34002. 'a88': 234,
  34003. 'a95': 334,
  34004. 'a96': 334,
  34005. 'a101': 732,
  34006. 'a102': 544,
  34007. 'a103': 544,
  34008. 'a104': 910,
  34009. 'a106': 667,
  34010. 'a107': 760,
  34011. 'a108': 760,
  34012. 'a112': 776,
  34013. 'a111': 595,
  34014. 'a110': 694,
  34015. 'a109': 626,
  34016. 'a120': 788,
  34017. 'a121': 788,
  34018. 'a122': 788,
  34019. 'a123': 788,
  34020. 'a124': 788,
  34021. 'a125': 788,
  34022. 'a126': 788,
  34023. 'a127': 788,
  34024. 'a128': 788,
  34025. 'a129': 788,
  34026. 'a130': 788,
  34027. 'a131': 788,
  34028. 'a132': 788,
  34029. 'a133': 788,
  34030. 'a134': 788,
  34031. 'a135': 788,
  34032. 'a136': 788,
  34033. 'a137': 788,
  34034. 'a138': 788,
  34035. 'a139': 788,
  34036. 'a140': 788,
  34037. 'a141': 788,
  34038. 'a142': 788,
  34039. 'a143': 788,
  34040. 'a144': 788,
  34041. 'a145': 788,
  34042. 'a146': 788,
  34043. 'a147': 788,
  34044. 'a148': 788,
  34045. 'a149': 788,
  34046. 'a150': 788,
  34047. 'a151': 788,
  34048. 'a152': 788,
  34049. 'a153': 788,
  34050. 'a154': 788,
  34051. 'a155': 788,
  34052. 'a156': 788,
  34053. 'a157': 788,
  34054. 'a158': 788,
  34055. 'a159': 788,
  34056. 'a160': 894,
  34057. 'a161': 838,
  34058. 'a163': 1016,
  34059. 'a164': 458,
  34060. 'a196': 748,
  34061. 'a165': 924,
  34062. 'a192': 748,
  34063. 'a166': 918,
  34064. 'a167': 927,
  34065. 'a168': 928,
  34066. 'a169': 928,
  34067. 'a170': 834,
  34068. 'a171': 873,
  34069. 'a172': 828,
  34070. 'a173': 924,
  34071. 'a162': 924,
  34072. 'a174': 917,
  34073. 'a175': 930,
  34074. 'a176': 931,
  34075. 'a177': 463,
  34076. 'a178': 883,
  34077. 'a179': 836,
  34078. 'a193': 836,
  34079. 'a180': 867,
  34080. 'a199': 867,
  34081. 'a181': 696,
  34082. 'a200': 696,
  34083. 'a182': 874,
  34084. 'a201': 874,
  34085. 'a183': 760,
  34086. 'a184': 946,
  34087. 'a197': 771,
  34088. 'a185': 865,
  34089. 'a194': 771,
  34090. 'a198': 888,
  34091. 'a186': 967,
  34092. 'a195': 888,
  34093. 'a187': 831,
  34094. 'a188': 873,
  34095. 'a189': 927,
  34096. 'a190': 970,
  34097. 'a191': 918
  34098. }
  34099. };
  34100. var EOF = {};
  34101. function isEOF(v) {
  34102. return (v === EOF);
  34103. }
  34104. var MAX_LENGTH_TO_CACHE = 1000;
  34105. var Parser = (function ParserClosure() {
  34106. function Parser(lexer, allowStreams, xref) {
  34107. this.lexer = lexer;
  34108. this.allowStreams = allowStreams;
  34109. this.xref = xref;
  34110. this.imageCache = {};
  34111. this.refill();
  34112. }
  34113. Parser.prototype = {
  34114. refill: function Parser_refill() {
  34115. this.buf1 = this.lexer.getObj();
  34116. this.buf2 = this.lexer.getObj();
  34117. },
  34118. shift: function Parser_shift() {
  34119. if (isCmd(this.buf2, 'ID')) {
  34120. this.buf1 = this.buf2;
  34121. this.buf2 = null;
  34122. } else {
  34123. this.buf1 = this.buf2;
  34124. this.buf2 = this.lexer.getObj();
  34125. }
  34126. },
  34127. getObj: function Parser_getObj(cipherTransform) {
  34128. var buf1 = this.buf1;
  34129. this.shift();
  34130. if (buf1 instanceof Cmd) {
  34131. switch (buf1.cmd) {
  34132. case 'BI': // inline image
  34133. return this.makeInlineImage(cipherTransform);
  34134. case '[': // array
  34135. var array = [];
  34136. while (!isCmd(this.buf1, ']') && !isEOF(this.buf1)) {
  34137. array.push(this.getObj(cipherTransform));
  34138. }
  34139. if (isEOF(this.buf1)) {
  34140. error('End of file inside array');
  34141. }
  34142. this.shift();
  34143. return array;
  34144. case '<<': // dictionary or stream
  34145. var dict = new Dict(this.xref);
  34146. while (!isCmd(this.buf1, '>>') && !isEOF(this.buf1)) {
  34147. if (!isName(this.buf1)) {
  34148. info('Malformed dictionary: key must be a name object');
  34149. this.shift();
  34150. continue;
  34151. }
  34152. var key = this.buf1.name;
  34153. this.shift();
  34154. if (isEOF(this.buf1)) {
  34155. break;
  34156. }
  34157. dict.set(key, this.getObj(cipherTransform));
  34158. }
  34159. if (isEOF(this.buf1)) {
  34160. error('End of file inside dictionary');
  34161. }
  34162. // Stream objects are not allowed inside content streams or
  34163. // object streams.
  34164. if (isCmd(this.buf2, 'stream')) {
  34165. return (this.allowStreams ?
  34166. this.makeStream(dict, cipherTransform) : dict);
  34167. }
  34168. this.shift();
  34169. return dict;
  34170. default: // simple object
  34171. return buf1;
  34172. }
  34173. }
  34174. if (isInt(buf1)) { // indirect reference or integer
  34175. var num = buf1;
  34176. if (isInt(this.buf1) && isCmd(this.buf2, 'R')) {
  34177. var ref = new Ref(num, this.buf1);
  34178. this.shift();
  34179. this.shift();
  34180. return ref;
  34181. }
  34182. return num;
  34183. }
  34184. if (isString(buf1)) { // string
  34185. var str = buf1;
  34186. if (cipherTransform) {
  34187. str = cipherTransform.decryptString(str);
  34188. }
  34189. return str;
  34190. }
  34191. // simple object
  34192. return buf1;
  34193. },
  34194. /**
  34195. * Find the end of the stream by searching for the /EI\s/.
  34196. * @returns {number} The inline stream length.
  34197. */
  34198. findDefaultInlineStreamEnd:
  34199. function Parser_findDefaultInlineStreamEnd(stream) {
  34200. var E = 0x45, I = 0x49, SPACE = 0x20, LF = 0xA, CR = 0xD;
  34201. var startPos = stream.pos, state = 0, ch, i, n, followingBytes;
  34202. while ((ch = stream.getByte()) !== -1) {
  34203. if (state === 0) {
  34204. state = (ch === E) ? 1 : 0;
  34205. } else if (state === 1) {
  34206. state = (ch === I) ? 2 : 0;
  34207. } else {
  34208. assert(state === 2);
  34209. if (ch === SPACE || ch === LF || ch === CR) {
  34210. // Let's check the next five bytes are ASCII... just be sure.
  34211. n = 5;
  34212. followingBytes = stream.peekBytes(n);
  34213. for (i = 0; i < n; i++) {
  34214. ch = followingBytes[i];
  34215. if (ch !== LF && ch !== CR && (ch < SPACE || ch > 0x7F)) {
  34216. // Not a LF, CR, SPACE or any visible ASCII character, i.e.
  34217. // it's binary stuff. Resetting the state.
  34218. state = 0;
  34219. break;
  34220. }
  34221. }
  34222. if (state === 2) {
  34223. break; // Finished!
  34224. }
  34225. } else {
  34226. state = 0;
  34227. }
  34228. }
  34229. }
  34230. return ((stream.pos - 4) - startPos);
  34231. },
  34232. /**
  34233. * Find the EOI (end-of-image) marker 0xFFD9 of the stream.
  34234. * @returns {number} The inline stream length.
  34235. */
  34236. findDCTDecodeInlineStreamEnd:
  34237. function Parser_findDCTDecodeInlineStreamEnd(stream) {
  34238. var startPos = stream.pos, foundEOI = false, b, markerLength, length;
  34239. while ((b = stream.getByte()) !== -1) {
  34240. if (b !== 0xFF) { // Not a valid marker.
  34241. continue;
  34242. }
  34243. switch (stream.getByte()) {
  34244. case 0x00: // Byte stuffing.
  34245. // 0xFF00 appears to be a very common byte sequence in JPEG images.
  34246. break;
  34247. case 0xFF: // Fill byte.
  34248. // Avoid skipping a valid marker, resetting the stream position.
  34249. stream.skip(-1);
  34250. break;
  34251. case 0xD9: // EOI
  34252. foundEOI = true;
  34253. break;
  34254. case 0xC0: // SOF0
  34255. case 0xC1: // SOF1
  34256. case 0xC2: // SOF2
  34257. case 0xC3: // SOF3
  34258. case 0xC5: // SOF5
  34259. case 0xC6: // SOF6
  34260. case 0xC7: // SOF7
  34261. case 0xC9: // SOF9
  34262. case 0xCA: // SOF10
  34263. case 0xCB: // SOF11
  34264. case 0xCD: // SOF13
  34265. case 0xCE: // SOF14
  34266. case 0xCF: // SOF15
  34267. case 0xC4: // DHT
  34268. case 0xCC: // DAC
  34269. case 0xDA: // SOS
  34270. case 0xDB: // DQT
  34271. case 0xDC: // DNL
  34272. case 0xDD: // DRI
  34273. case 0xDE: // DHP
  34274. case 0xDF: // EXP
  34275. case 0xE0: // APP0
  34276. case 0xE1: // APP1
  34277. case 0xE2: // APP2
  34278. case 0xE3: // APP3
  34279. case 0xE4: // APP4
  34280. case 0xE5: // APP5
  34281. case 0xE6: // APP6
  34282. case 0xE7: // APP7
  34283. case 0xE8: // APP8
  34284. case 0xE9: // APP9
  34285. case 0xEA: // APP10
  34286. case 0xEB: // APP11
  34287. case 0xEC: // APP12
  34288. case 0xED: // APP13
  34289. case 0xEE: // APP14
  34290. case 0xEF: // APP15
  34291. case 0xFE: // COM
  34292. // The marker should be followed by the length of the segment.
  34293. markerLength = stream.getUint16();
  34294. if (markerLength > 2) {
  34295. // |markerLength| contains the byte length of the marker segment,
  34296. // including its own length (2 bytes) and excluding the marker.
  34297. stream.skip(markerLength - 2); // Jump to the next marker.
  34298. } else {
  34299. // The marker length is invalid, resetting the stream position.
  34300. stream.skip(-2);
  34301. }
  34302. break;
  34303. }
  34304. if (foundEOI) {
  34305. break;
  34306. }
  34307. }
  34308. length = stream.pos - startPos;
  34309. if (b === -1) {
  34310. warn('Inline DCTDecode image stream: ' +
  34311. 'EOI marker not found, searching for /EI/ instead.');
  34312. stream.skip(-length); // Reset the stream position.
  34313. return this.findDefaultInlineStreamEnd(stream);
  34314. }
  34315. this.inlineStreamSkipEI(stream);
  34316. return length;
  34317. },
  34318. /**
  34319. * Find the EOD (end-of-data) marker '~>' (i.e. TILDE + GT) of the stream.
  34320. * @returns {number} The inline stream length.
  34321. */
  34322. findASCII85DecodeInlineStreamEnd:
  34323. function Parser_findASCII85DecodeInlineStreamEnd(stream) {
  34324. var TILDE = 0x7E, GT = 0x3E;
  34325. var startPos = stream.pos, ch, length;
  34326. while ((ch = stream.getByte()) !== -1) {
  34327. if (ch === TILDE && stream.peekByte() === GT) {
  34328. stream.skip();
  34329. break;
  34330. }
  34331. }
  34332. length = stream.pos - startPos;
  34333. if (ch === -1) {
  34334. warn('Inline ASCII85Decode image stream: ' +
  34335. 'EOD marker not found, searching for /EI/ instead.');
  34336. stream.skip(-length); // Reset the stream position.
  34337. return this.findDefaultInlineStreamEnd(stream);
  34338. }
  34339. this.inlineStreamSkipEI(stream);
  34340. return length;
  34341. },
  34342. /**
  34343. * Find the EOD (end-of-data) marker '>' (i.e. GT) of the stream.
  34344. * @returns {number} The inline stream length.
  34345. */
  34346. findASCIIHexDecodeInlineStreamEnd:
  34347. function Parser_findASCIIHexDecodeInlineStreamEnd(stream) {
  34348. var GT = 0x3E;
  34349. var startPos = stream.pos, ch, length;
  34350. while ((ch = stream.getByte()) !== -1) {
  34351. if (ch === GT) {
  34352. break;
  34353. }
  34354. }
  34355. length = stream.pos - startPos;
  34356. if (ch === -1) {
  34357. warn('Inline ASCIIHexDecode image stream: ' +
  34358. 'EOD marker not found, searching for /EI/ instead.');
  34359. stream.skip(-length); // Reset the stream position.
  34360. return this.findDefaultInlineStreamEnd(stream);
  34361. }
  34362. this.inlineStreamSkipEI(stream);
  34363. return length;
  34364. },
  34365. /**
  34366. * Skip over the /EI/ for streams where we search for an EOD marker.
  34367. */
  34368. inlineStreamSkipEI: function Parser_inlineStreamSkipEI(stream) {
  34369. var E = 0x45, I = 0x49;
  34370. var state = 0, ch;
  34371. while ((ch = stream.getByte()) !== -1) {
  34372. if (state === 0) {
  34373. state = (ch === E) ? 1 : 0;
  34374. } else if (state === 1) {
  34375. state = (ch === I) ? 2 : 0;
  34376. } else if (state === 2) {
  34377. break;
  34378. }
  34379. }
  34380. },
  34381. makeInlineImage: function Parser_makeInlineImage(cipherTransform) {
  34382. var lexer = this.lexer;
  34383. var stream = lexer.stream;
  34384. // Parse dictionary.
  34385. var dict = new Dict(null);
  34386. while (!isCmd(this.buf1, 'ID') && !isEOF(this.buf1)) {
  34387. if (!isName(this.buf1)) {
  34388. error('Dictionary key must be a name object');
  34389. }
  34390. var key = this.buf1.name;
  34391. this.shift();
  34392. if (isEOF(this.buf1)) {
  34393. break;
  34394. }
  34395. dict.set(key, this.getObj(cipherTransform));
  34396. }
  34397. // Extract the name of the first (i.e. the current) image filter.
  34398. var filter = this.fetchIfRef(dict.get('Filter', 'F')), filterName;
  34399. if (isName(filter)) {
  34400. filterName = filter.name;
  34401. } else if (isArray(filter) && isName(filter[0])) {
  34402. filterName = filter[0].name;
  34403. }
  34404. // Parse image stream.
  34405. var startPos = stream.pos, length, i, ii;
  34406. if (filterName === 'DCTDecode' || filterName === 'DCT') {
  34407. length = this.findDCTDecodeInlineStreamEnd(stream);
  34408. } else if (filterName === 'ASCII85Decide' || filterName === 'A85') {
  34409. length = this.findASCII85DecodeInlineStreamEnd(stream);
  34410. } else if (filterName === 'ASCIIHexDecode' || filterName === 'AHx') {
  34411. length = this.findASCIIHexDecodeInlineStreamEnd(stream);
  34412. } else {
  34413. length = this.findDefaultInlineStreamEnd(stream);
  34414. }
  34415. var imageStream = stream.makeSubStream(startPos, length, dict);
  34416. // Cache all images below the MAX_LENGTH_TO_CACHE threshold by their
  34417. // adler32 checksum.
  34418. var adler32;
  34419. if (length < MAX_LENGTH_TO_CACHE) {
  34420. var imageBytes = imageStream.getBytes();
  34421. imageStream.reset();
  34422. var a = 1;
  34423. var b = 0;
  34424. for (i = 0, ii = imageBytes.length; i < ii; ++i) {
  34425. // No modulo required in the loop if imageBytes.length < 5552.
  34426. a += imageBytes[i] & 0xff;
  34427. b += a;
  34428. }
  34429. adler32 = ((b % 65521) << 16) | (a % 65521);
  34430. if (this.imageCache.adler32 === adler32) {
  34431. this.buf2 = Cmd.get('EI');
  34432. this.shift();
  34433. this.imageCache[adler32].reset();
  34434. return this.imageCache[adler32];
  34435. }
  34436. }
  34437. if (cipherTransform) {
  34438. imageStream = cipherTransform.createStream(imageStream, length);
  34439. }
  34440. imageStream = this.filter(imageStream, dict, length);
  34441. imageStream.dict = dict;
  34442. if (adler32 !== undefined) {
  34443. imageStream.cacheKey = 'inline_' + length + '_' + adler32;
  34444. this.imageCache[adler32] = imageStream;
  34445. }
  34446. this.buf2 = Cmd.get('EI');
  34447. this.shift();
  34448. return imageStream;
  34449. },
  34450. fetchIfRef: function Parser_fetchIfRef(obj) {
  34451. // not relying on the xref.fetchIfRef -- xref might not be set
  34452. return (isRef(obj) ? this.xref.fetch(obj) : obj);
  34453. },
  34454. makeStream: function Parser_makeStream(dict, cipherTransform) {
  34455. var lexer = this.lexer;
  34456. var stream = lexer.stream;
  34457. // get stream start position
  34458. lexer.skipToNextLine();
  34459. var pos = stream.pos - 1;
  34460. // get length
  34461. var length = this.fetchIfRef(dict.get('Length'));
  34462. if (!isInt(length)) {
  34463. info('Bad ' + length + ' attribute in stream');
  34464. length = 0;
  34465. }
  34466. // skip over the stream data
  34467. stream.pos = pos + length;
  34468. lexer.nextChar();
  34469. this.shift(); // '>>'
  34470. this.shift(); // 'stream'
  34471. if (!isCmd(this.buf1, 'endstream')) {
  34472. // bad stream length, scanning for endstream
  34473. stream.pos = pos;
  34474. var SCAN_BLOCK_SIZE = 2048;
  34475. var ENDSTREAM_SIGNATURE_LENGTH = 9;
  34476. var ENDSTREAM_SIGNATURE = [0x65, 0x6E, 0x64, 0x73, 0x74, 0x72, 0x65,
  34477. 0x61, 0x6D];
  34478. var skipped = 0, found = false, i, j;
  34479. while (stream.pos < stream.end) {
  34480. var scanBytes = stream.peekBytes(SCAN_BLOCK_SIZE);
  34481. var scanLength = scanBytes.length - ENDSTREAM_SIGNATURE_LENGTH;
  34482. if (scanLength <= 0) {
  34483. break;
  34484. }
  34485. found = false;
  34486. for (i = 0, j = 0; i < scanLength; i++) {
  34487. var b = scanBytes[i];
  34488. if (b !== ENDSTREAM_SIGNATURE[j]) {
  34489. i -= j;
  34490. j = 0;
  34491. } else {
  34492. j++;
  34493. if (j >= ENDSTREAM_SIGNATURE_LENGTH) {
  34494. i++;
  34495. found = true;
  34496. break;
  34497. }
  34498. }
  34499. }
  34500. if (found) {
  34501. skipped += i - ENDSTREAM_SIGNATURE_LENGTH;
  34502. stream.pos += i - ENDSTREAM_SIGNATURE_LENGTH;
  34503. break;
  34504. }
  34505. skipped += scanLength;
  34506. stream.pos += scanLength;
  34507. }
  34508. if (!found) {
  34509. error('Missing endstream');
  34510. }
  34511. length = skipped;
  34512. lexer.nextChar();
  34513. this.shift();
  34514. this.shift();
  34515. }
  34516. this.shift(); // 'endstream'
  34517. stream = stream.makeSubStream(pos, length, dict);
  34518. if (cipherTransform) {
  34519. stream = cipherTransform.createStream(stream, length);
  34520. }
  34521. stream = this.filter(stream, dict, length);
  34522. stream.dict = dict;
  34523. return stream;
  34524. },
  34525. filter: function Parser_filter(stream, dict, length) {
  34526. var filter = this.fetchIfRef(dict.get('Filter', 'F'));
  34527. var params = this.fetchIfRef(dict.get('DecodeParms', 'DP'));
  34528. if (isName(filter)) {
  34529. return this.makeFilter(stream, filter.name, length, params);
  34530. }
  34531. var maybeLength = length;
  34532. if (isArray(filter)) {
  34533. var filterArray = filter;
  34534. var paramsArray = params;
  34535. for (var i = 0, ii = filterArray.length; i < ii; ++i) {
  34536. filter = filterArray[i];
  34537. if (!isName(filter)) {
  34538. error('Bad filter name: ' + filter);
  34539. }
  34540. params = null;
  34541. if (isArray(paramsArray) && (i in paramsArray)) {
  34542. params = paramsArray[i];
  34543. }
  34544. stream = this.makeFilter(stream, filter.name, maybeLength, params);
  34545. // after the first stream the length variable is invalid
  34546. maybeLength = null;
  34547. }
  34548. }
  34549. return stream;
  34550. },
  34551. makeFilter: function Parser_makeFilter(stream, name, maybeLength, params) {
  34552. if (stream.dict.get('Length') === 0) {
  34553. return new NullStream(stream);
  34554. }
  34555. try {
  34556. if (params) {
  34557. params = this.fetchIfRef(params);
  34558. }
  34559. var xrefStreamStats = this.xref.stats.streamTypes;
  34560. if (name === 'FlateDecode' || name === 'Fl') {
  34561. xrefStreamStats[StreamType.FLATE] = true;
  34562. if (params) {
  34563. return new PredictorStream(new FlateStream(stream, maybeLength),
  34564. maybeLength, params);
  34565. }
  34566. return new FlateStream(stream, maybeLength);
  34567. }
  34568. if (name === 'LZWDecode' || name === 'LZW') {
  34569. xrefStreamStats[StreamType.LZW] = true;
  34570. var earlyChange = 1;
  34571. if (params) {
  34572. if (params.has('EarlyChange')) {
  34573. earlyChange = params.get('EarlyChange');
  34574. }
  34575. return new PredictorStream(
  34576. new LZWStream(stream, maybeLength, earlyChange),
  34577. maybeLength, params);
  34578. }
  34579. return new LZWStream(stream, maybeLength, earlyChange);
  34580. }
  34581. if (name === 'DCTDecode' || name === 'DCT') {
  34582. xrefStreamStats[StreamType.DCT] = true;
  34583. return new JpegStream(stream, maybeLength, stream.dict, this.xref);
  34584. }
  34585. if (name === 'JPXDecode' || name === 'JPX') {
  34586. xrefStreamStats[StreamType.JPX] = true;
  34587. return new JpxStream(stream, maybeLength, stream.dict);
  34588. }
  34589. if (name === 'ASCII85Decode' || name === 'A85') {
  34590. xrefStreamStats[StreamType.A85] = true;
  34591. return new Ascii85Stream(stream, maybeLength);
  34592. }
  34593. if (name === 'ASCIIHexDecode' || name === 'AHx') {
  34594. xrefStreamStats[StreamType.AHX] = true;
  34595. return new AsciiHexStream(stream, maybeLength);
  34596. }
  34597. if (name === 'CCITTFaxDecode' || name === 'CCF') {
  34598. xrefStreamStats[StreamType.CCF] = true;
  34599. return new CCITTFaxStream(stream, maybeLength, params);
  34600. }
  34601. if (name === 'RunLengthDecode' || name === 'RL') {
  34602. xrefStreamStats[StreamType.RL] = true;
  34603. return new RunLengthStream(stream, maybeLength);
  34604. }
  34605. if (name === 'JBIG2Decode') {
  34606. xrefStreamStats[StreamType.JBIG] = true;
  34607. return new Jbig2Stream(stream, maybeLength, stream.dict);
  34608. }
  34609. warn('filter "' + name + '" not supported yet');
  34610. return stream;
  34611. } catch (ex) {
  34612. if (ex instanceof MissingDataException) {
  34613. throw ex;
  34614. }
  34615. warn('Invalid stream: \"' + ex + '\"');
  34616. return new NullStream(stream);
  34617. }
  34618. }
  34619. };
  34620. return Parser;
  34621. })();
  34622. var Lexer = (function LexerClosure() {
  34623. function Lexer(stream, knownCommands) {
  34624. this.stream = stream;
  34625. this.nextChar();
  34626. // While lexing, we build up many strings one char at a time. Using += for
  34627. // this can result in lots of garbage strings. It's better to build an
  34628. // array of single-char strings and then join() them together at the end.
  34629. // And reusing a single array (i.e. |this.strBuf|) over and over for this
  34630. // purpose uses less memory than using a new array for each string.
  34631. this.strBuf = [];
  34632. // The PDFs might have "glued" commands with other commands, operands or
  34633. // literals, e.g. "q1". The knownCommands is a dictionary of the valid
  34634. // commands and their prefixes. The prefixes are built the following way:
  34635. // if there a command that is a prefix of the other valid command or
  34636. // literal (e.g. 'f' and 'false') the following prefixes must be included,
  34637. // 'fa', 'fal', 'fals'. The prefixes are not needed, if the command has no
  34638. // other commands or literals as a prefix. The knowCommands is optional.
  34639. this.knownCommands = knownCommands;
  34640. }
  34641. Lexer.isSpace = function Lexer_isSpace(ch) {
  34642. // Space is one of the following characters: SPACE, TAB, CR or LF.
  34643. return (ch === 0x20 || ch === 0x09 || ch === 0x0D || ch === 0x0A);
  34644. };
  34645. // A '1' in this array means the character is white space. A '1' or
  34646. // '2' means the character ends a name or command.
  34647. var specialChars = [
  34648. 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, // 0x
  34649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1x
  34650. 1, 0, 0, 0, 0, 2, 0, 0, 2, 2, 0, 0, 0, 0, 0, 2, // 2x
  34651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, // 3x
  34652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 4x
  34653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, // 5x
  34654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 6x
  34655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, // 7x
  34656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 8x
  34657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 9x
  34658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // ax
  34659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // bx
  34660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // cx
  34661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // dx
  34662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // ex
  34663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // fx
  34664. ];
  34665. function toHexDigit(ch) {
  34666. if (ch >= 0x30 && ch <= 0x39) { // '0'-'9'
  34667. return ch & 0x0F;
  34668. }
  34669. if ((ch >= 0x41 && ch <= 0x46) || (ch >= 0x61 && ch <= 0x66)) {
  34670. // 'A'-'F', 'a'-'f'
  34671. return (ch & 0x0F) + 9;
  34672. }
  34673. return -1;
  34674. }
  34675. Lexer.prototype = {
  34676. nextChar: function Lexer_nextChar() {
  34677. return (this.currentChar = this.stream.getByte());
  34678. },
  34679. peekChar: function Lexer_peekChar() {
  34680. return this.stream.peekByte();
  34681. },
  34682. getNumber: function Lexer_getNumber() {
  34683. var ch = this.currentChar;
  34684. var eNotation = false;
  34685. var divideBy = 0; // different from 0 if it's a floating point value
  34686. var sign = 1;
  34687. if (ch === 0x2D) { // '-'
  34688. sign = -1;
  34689. ch = this.nextChar();
  34690. } else if (ch === 0x2B) { // '+'
  34691. ch = this.nextChar();
  34692. }
  34693. if (ch === 0x2E) { // '.'
  34694. divideBy = 10;
  34695. ch = this.nextChar();
  34696. }
  34697. if (ch < 0x30 || ch > 0x39) { // '0' - '9'
  34698. error('Invalid number: ' + String.fromCharCode(ch));
  34699. return 0;
  34700. }
  34701. var baseValue = ch - 0x30; // '0'
  34702. var powerValue = 0;
  34703. var powerValueSign = 1;
  34704. while ((ch = this.nextChar()) >= 0) {
  34705. if (0x30 <= ch && ch <= 0x39) { // '0' - '9'
  34706. var currentDigit = ch - 0x30; // '0'
  34707. if (eNotation) { // We are after an 'e' or 'E'
  34708. powerValue = powerValue * 10 + currentDigit;
  34709. } else {
  34710. if (divideBy !== 0) { // We are after a point
  34711. divideBy *= 10;
  34712. }
  34713. baseValue = baseValue * 10 + currentDigit;
  34714. }
  34715. } else if (ch === 0x2E) { // '.'
  34716. if (divideBy === 0) {
  34717. divideBy = 1;
  34718. } else {
  34719. // A number can have only one '.'
  34720. break;
  34721. }
  34722. } else if (ch === 0x2D) { // '-'
  34723. // ignore minus signs in the middle of numbers to match
  34724. // Adobe's behavior
  34725. warn('Badly formated number');
  34726. } else if (ch === 0x45 || ch === 0x65) { // 'E', 'e'
  34727. // 'E' can be either a scientific notation or the beginning of a new
  34728. // operator
  34729. ch = this.peekChar();
  34730. if (ch === 0x2B || ch === 0x2D) { // '+', '-'
  34731. powerValueSign = (ch === 0x2D) ? -1 : 1;
  34732. this.nextChar(); // Consume the sign character
  34733. } else if (ch < 0x30 || ch > 0x39) { // '0' - '9'
  34734. // The 'E' must be the beginning of a new operator
  34735. break;
  34736. }
  34737. eNotation = true;
  34738. } else {
  34739. // the last character doesn't belong to us
  34740. break;
  34741. }
  34742. }
  34743. if (divideBy !== 0) {
  34744. baseValue /= divideBy;
  34745. }
  34746. if (eNotation) {
  34747. baseValue *= Math.pow(10, powerValueSign * powerValue);
  34748. }
  34749. return sign * baseValue;
  34750. },
  34751. getString: function Lexer_getString() {
  34752. var numParen = 1;
  34753. var done = false;
  34754. var strBuf = this.strBuf;
  34755. strBuf.length = 0;
  34756. var ch = this.nextChar();
  34757. while (true) {
  34758. var charBuffered = false;
  34759. switch (ch | 0) {
  34760. case -1:
  34761. warn('Unterminated string');
  34762. done = true;
  34763. break;
  34764. case 0x28: // '('
  34765. ++numParen;
  34766. strBuf.push('(');
  34767. break;
  34768. case 0x29: // ')'
  34769. if (--numParen === 0) {
  34770. this.nextChar(); // consume strings ')'
  34771. done = true;
  34772. } else {
  34773. strBuf.push(')');
  34774. }
  34775. break;
  34776. case 0x5C: // '\\'
  34777. ch = this.nextChar();
  34778. switch (ch) {
  34779. case -1:
  34780. warn('Unterminated string');
  34781. done = true;
  34782. break;
  34783. case 0x6E: // 'n'
  34784. strBuf.push('\n');
  34785. break;
  34786. case 0x72: // 'r'
  34787. strBuf.push('\r');
  34788. break;
  34789. case 0x74: // 't'
  34790. strBuf.push('\t');
  34791. break;
  34792. case 0x62: // 'b'
  34793. strBuf.push('\b');
  34794. break;
  34795. case 0x66: // 'f'
  34796. strBuf.push('\f');
  34797. break;
  34798. case 0x5C: // '\'
  34799. case 0x28: // '('
  34800. case 0x29: // ')'
  34801. strBuf.push(String.fromCharCode(ch));
  34802. break;
  34803. case 0x30: case 0x31: case 0x32: case 0x33: // '0'-'3'
  34804. case 0x34: case 0x35: case 0x36: case 0x37: // '4'-'7'
  34805. var x = ch & 0x0F;
  34806. ch = this.nextChar();
  34807. charBuffered = true;
  34808. if (ch >= 0x30 && ch <= 0x37) { // '0'-'7'
  34809. x = (x << 3) + (ch & 0x0F);
  34810. ch = this.nextChar();
  34811. if (ch >= 0x30 && ch <= 0x37) { // '0'-'7'
  34812. charBuffered = false;
  34813. x = (x << 3) + (ch & 0x0F);
  34814. }
  34815. }
  34816. strBuf.push(String.fromCharCode(x));
  34817. break;
  34818. case 0x0D: // CR
  34819. if (this.peekChar() === 0x0A) { // LF
  34820. this.nextChar();
  34821. }
  34822. break;
  34823. case 0x0A: // LF
  34824. break;
  34825. default:
  34826. strBuf.push(String.fromCharCode(ch));
  34827. break;
  34828. }
  34829. break;
  34830. default:
  34831. strBuf.push(String.fromCharCode(ch));
  34832. break;
  34833. }
  34834. if (done) {
  34835. break;
  34836. }
  34837. if (!charBuffered) {
  34838. ch = this.nextChar();
  34839. }
  34840. }
  34841. return strBuf.join('');
  34842. },
  34843. getName: function Lexer_getName() {
  34844. var ch;
  34845. var strBuf = this.strBuf;
  34846. strBuf.length = 0;
  34847. while ((ch = this.nextChar()) >= 0 && !specialChars[ch]) {
  34848. if (ch === 0x23) { // '#'
  34849. ch = this.nextChar();
  34850. var x = toHexDigit(ch);
  34851. if (x !== -1) {
  34852. var x2 = toHexDigit(this.nextChar());
  34853. if (x2 === -1) {
  34854. error('Illegal digit in hex char in name: ' + x2);
  34855. }
  34856. strBuf.push(String.fromCharCode((x << 4) | x2));
  34857. } else {
  34858. strBuf.push('#', String.fromCharCode(ch));
  34859. }
  34860. } else {
  34861. strBuf.push(String.fromCharCode(ch));
  34862. }
  34863. }
  34864. if (strBuf.length > 128) {
  34865. error('Warning: name token is longer than allowed by the spec: ' +
  34866. strBuf.length);
  34867. }
  34868. return Name.get(strBuf.join(''));
  34869. },
  34870. getHexString: function Lexer_getHexString() {
  34871. var strBuf = this.strBuf;
  34872. strBuf.length = 0;
  34873. var ch = this.currentChar;
  34874. var isFirstHex = true;
  34875. var firstDigit;
  34876. var secondDigit;
  34877. while (true) {
  34878. if (ch < 0) {
  34879. warn('Unterminated hex string');
  34880. break;
  34881. } else if (ch === 0x3E) { // '>'
  34882. this.nextChar();
  34883. break;
  34884. } else if (specialChars[ch] === 1) {
  34885. ch = this.nextChar();
  34886. continue;
  34887. } else {
  34888. if (isFirstHex) {
  34889. firstDigit = toHexDigit(ch);
  34890. if (firstDigit === -1) {
  34891. warn('Ignoring invalid character "' + ch + '" in hex string');
  34892. ch = this.nextChar();
  34893. continue;
  34894. }
  34895. } else {
  34896. secondDigit = toHexDigit(ch);
  34897. if (secondDigit === -1) {
  34898. warn('Ignoring invalid character "' + ch + '" in hex string');
  34899. ch = this.nextChar();
  34900. continue;
  34901. }
  34902. strBuf.push(String.fromCharCode((firstDigit << 4) | secondDigit));
  34903. }
  34904. isFirstHex = !isFirstHex;
  34905. ch = this.nextChar();
  34906. }
  34907. }
  34908. return strBuf.join('');
  34909. },
  34910. getObj: function Lexer_getObj() {
  34911. // skip whitespace and comments
  34912. var comment = false;
  34913. var ch = this.currentChar;
  34914. while (true) {
  34915. if (ch < 0) {
  34916. return EOF;
  34917. }
  34918. if (comment) {
  34919. if (ch === 0x0A || ch === 0x0D) { // LF, CR
  34920. comment = false;
  34921. }
  34922. } else if (ch === 0x25) { // '%'
  34923. comment = true;
  34924. } else if (specialChars[ch] !== 1) {
  34925. break;
  34926. }
  34927. ch = this.nextChar();
  34928. }
  34929. // start reading token
  34930. switch (ch | 0) {
  34931. case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: // '0'-'4'
  34932. case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: // '5'-'9'
  34933. case 0x2B: case 0x2D: case 0x2E: // '+', '-', '.'
  34934. return this.getNumber();
  34935. case 0x28: // '('
  34936. return this.getString();
  34937. case 0x2F: // '/'
  34938. return this.getName();
  34939. // array punctuation
  34940. case 0x5B: // '['
  34941. this.nextChar();
  34942. return Cmd.get('[');
  34943. case 0x5D: // ']'
  34944. this.nextChar();
  34945. return Cmd.get(']');
  34946. // hex string or dict punctuation
  34947. case 0x3C: // '<'
  34948. ch = this.nextChar();
  34949. if (ch === 0x3C) {
  34950. // dict punctuation
  34951. this.nextChar();
  34952. return Cmd.get('<<');
  34953. }
  34954. return this.getHexString();
  34955. // dict punctuation
  34956. case 0x3E: // '>'
  34957. ch = this.nextChar();
  34958. if (ch === 0x3E) {
  34959. this.nextChar();
  34960. return Cmd.get('>>');
  34961. }
  34962. return Cmd.get('>');
  34963. case 0x7B: // '{'
  34964. this.nextChar();
  34965. return Cmd.get('{');
  34966. case 0x7D: // '}'
  34967. this.nextChar();
  34968. return Cmd.get('}');
  34969. case 0x29: // ')'
  34970. error('Illegal character: ' + ch);
  34971. break;
  34972. }
  34973. // command
  34974. var str = String.fromCharCode(ch);
  34975. var knownCommands = this.knownCommands;
  34976. var knownCommandFound = knownCommands && knownCommands[str] !== undefined;
  34977. while ((ch = this.nextChar()) >= 0 && !specialChars[ch]) {
  34978. // stop if known command is found and next character does not make
  34979. // the str a command
  34980. var possibleCommand = str + String.fromCharCode(ch);
  34981. if (knownCommandFound && knownCommands[possibleCommand] === undefined) {
  34982. break;
  34983. }
  34984. if (str.length === 128) {
  34985. error('Command token too long: ' + str.length);
  34986. }
  34987. str = possibleCommand;
  34988. knownCommandFound = knownCommands && knownCommands[str] !== undefined;
  34989. }
  34990. if (str === 'true') {
  34991. return true;
  34992. }
  34993. if (str === 'false') {
  34994. return false;
  34995. }
  34996. if (str === 'null') {
  34997. return null;
  34998. }
  34999. return Cmd.get(str);
  35000. },
  35001. skipToNextLine: function Lexer_skipToNextLine() {
  35002. var ch = this.currentChar;
  35003. while (ch >= 0) {
  35004. if (ch === 0x0D) { // CR
  35005. ch = this.nextChar();
  35006. if (ch === 0x0A) { // LF
  35007. this.nextChar();
  35008. }
  35009. break;
  35010. } else if (ch === 0x0A) { // LF
  35011. this.nextChar();
  35012. break;
  35013. }
  35014. ch = this.nextChar();
  35015. }
  35016. }
  35017. };
  35018. return Lexer;
  35019. })();
  35020. var Linearization = {
  35021. create: function LinearizationCreate(stream) {
  35022. function getInt(name, allowZeroValue) {
  35023. var obj = linDict.get(name);
  35024. if (isInt(obj) && (allowZeroValue ? obj >= 0 : obj > 0)) {
  35025. return obj;
  35026. }
  35027. throw new Error('The "' + name + '" parameter in the linearization ' +
  35028. 'dictionary is invalid.');
  35029. }
  35030. function getHints() {
  35031. var hints = linDict.get('H'), hintsLength, item;
  35032. if (isArray(hints) &&
  35033. ((hintsLength = hints.length) === 2 || hintsLength === 4)) {
  35034. for (var index = 0; index < hintsLength; index++) {
  35035. if (!(isInt(item = hints[index]) && item > 0)) {
  35036. throw new Error('Hint (' + index +
  35037. ') in the linearization dictionary is invalid.');
  35038. }
  35039. }
  35040. return hints;
  35041. }
  35042. throw new Error('Hint array in the linearization dictionary is invalid.');
  35043. }
  35044. var parser = new Parser(new Lexer(stream), false, null);
  35045. var obj1 = parser.getObj();
  35046. var obj2 = parser.getObj();
  35047. var obj3 = parser.getObj();
  35048. var linDict = parser.getObj();
  35049. var obj, length;
  35050. if (!(isInt(obj1) && isInt(obj2) && isCmd(obj3, 'obj') && isDict(linDict) &&
  35051. isNum(obj = linDict.get('Linearized')) && obj > 0)) {
  35052. return null; // No valid linearization dictionary found.
  35053. } else if ((length = getInt('L')) !== stream.length) {
  35054. throw new Error('The "L" parameter in the linearization dictionary ' +
  35055. 'does not equal the stream length.');
  35056. }
  35057. return {
  35058. length: length,
  35059. hints: getHints(),
  35060. objectNumberFirst: getInt('O'),
  35061. endFirst: getInt('E'),
  35062. numPages: getInt('N'),
  35063. mainXRefEntriesOffset: getInt('T'),
  35064. pageFirst: (linDict.has('P') ? getInt('P', true) : 0)
  35065. };
  35066. }
  35067. };
  35068. var PostScriptParser = (function PostScriptParserClosure() {
  35069. function PostScriptParser(lexer) {
  35070. this.lexer = lexer;
  35071. this.operators = [];
  35072. this.token = null;
  35073. this.prev = null;
  35074. }
  35075. PostScriptParser.prototype = {
  35076. nextToken: function PostScriptParser_nextToken() {
  35077. this.prev = this.token;
  35078. this.token = this.lexer.getToken();
  35079. },
  35080. accept: function PostScriptParser_accept(type) {
  35081. if (this.token.type === type) {
  35082. this.nextToken();
  35083. return true;
  35084. }
  35085. return false;
  35086. },
  35087. expect: function PostScriptParser_expect(type) {
  35088. if (this.accept(type)) {
  35089. return true;
  35090. }
  35091. error('Unexpected symbol: found ' + this.token.type + ' expected ' +
  35092. type + '.');
  35093. },
  35094. parse: function PostScriptParser_parse() {
  35095. this.nextToken();
  35096. this.expect(PostScriptTokenTypes.LBRACE);
  35097. this.parseBlock();
  35098. this.expect(PostScriptTokenTypes.RBRACE);
  35099. return this.operators;
  35100. },
  35101. parseBlock: function PostScriptParser_parseBlock() {
  35102. while (true) {
  35103. if (this.accept(PostScriptTokenTypes.NUMBER)) {
  35104. this.operators.push(this.prev.value);
  35105. } else if (this.accept(PostScriptTokenTypes.OPERATOR)) {
  35106. this.operators.push(this.prev.value);
  35107. } else if (this.accept(PostScriptTokenTypes.LBRACE)) {
  35108. this.parseCondition();
  35109. } else {
  35110. return;
  35111. }
  35112. }
  35113. },
  35114. parseCondition: function PostScriptParser_parseCondition() {
  35115. // Add two place holders that will be updated later
  35116. var conditionLocation = this.operators.length;
  35117. this.operators.push(null, null);
  35118. this.parseBlock();
  35119. this.expect(PostScriptTokenTypes.RBRACE);
  35120. if (this.accept(PostScriptTokenTypes.IF)) {
  35121. // The true block is right after the 'if' so it just falls through on
  35122. // true else it jumps and skips the true block.
  35123. this.operators[conditionLocation] = this.operators.length;
  35124. this.operators[conditionLocation + 1] = 'jz';
  35125. } else if (this.accept(PostScriptTokenTypes.LBRACE)) {
  35126. var jumpLocation = this.operators.length;
  35127. this.operators.push(null, null);
  35128. var endOfTrue = this.operators.length;
  35129. this.parseBlock();
  35130. this.expect(PostScriptTokenTypes.RBRACE);
  35131. this.expect(PostScriptTokenTypes.IFELSE);
  35132. // The jump is added at the end of the true block to skip the false
  35133. // block.
  35134. this.operators[jumpLocation] = this.operators.length;
  35135. this.operators[jumpLocation + 1] = 'j';
  35136. this.operators[conditionLocation] = endOfTrue;
  35137. this.operators[conditionLocation + 1] = 'jz';
  35138. } else {
  35139. error('PS Function: error parsing conditional.');
  35140. }
  35141. }
  35142. };
  35143. return PostScriptParser;
  35144. })();
  35145. var PostScriptTokenTypes = {
  35146. LBRACE: 0,
  35147. RBRACE: 1,
  35148. NUMBER: 2,
  35149. OPERATOR: 3,
  35150. IF: 4,
  35151. IFELSE: 5
  35152. };
  35153. var PostScriptToken = (function PostScriptTokenClosure() {
  35154. function PostScriptToken(type, value) {
  35155. this.type = type;
  35156. this.value = value;
  35157. }
  35158. var opCache = {};
  35159. PostScriptToken.getOperator = function PostScriptToken_getOperator(op) {
  35160. var opValue = opCache[op];
  35161. if (opValue) {
  35162. return opValue;
  35163. }
  35164. return opCache[op] = new PostScriptToken(PostScriptTokenTypes.OPERATOR, op);
  35165. };
  35166. PostScriptToken.LBRACE = new PostScriptToken(PostScriptTokenTypes.LBRACE,
  35167. '{');
  35168. PostScriptToken.RBRACE = new PostScriptToken(PostScriptTokenTypes.RBRACE,
  35169. '}');
  35170. PostScriptToken.IF = new PostScriptToken(PostScriptTokenTypes.IF, 'IF');
  35171. PostScriptToken.IFELSE = new PostScriptToken(PostScriptTokenTypes.IFELSE,
  35172. 'IFELSE');
  35173. return PostScriptToken;
  35174. })();
  35175. var PostScriptLexer = (function PostScriptLexerClosure() {
  35176. function PostScriptLexer(stream) {
  35177. this.stream = stream;
  35178. this.nextChar();
  35179. this.strBuf = [];
  35180. }
  35181. PostScriptLexer.prototype = {
  35182. nextChar: function PostScriptLexer_nextChar() {
  35183. return (this.currentChar = this.stream.getByte());
  35184. },
  35185. getToken: function PostScriptLexer_getToken() {
  35186. var comment = false;
  35187. var ch = this.currentChar;
  35188. // skip comments
  35189. while (true) {
  35190. if (ch < 0) {
  35191. return EOF;
  35192. }
  35193. if (comment) {
  35194. if (ch === 0x0A || ch === 0x0D) {
  35195. comment = false;
  35196. }
  35197. } else if (ch === 0x25) { // '%'
  35198. comment = true;
  35199. } else if (!Lexer.isSpace(ch)) {
  35200. break;
  35201. }
  35202. ch = this.nextChar();
  35203. }
  35204. switch (ch | 0) {
  35205. case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: // '0'-'4'
  35206. case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: // '5'-'9'
  35207. case 0x2B: case 0x2D: case 0x2E: // '+', '-', '.'
  35208. return new PostScriptToken(PostScriptTokenTypes.NUMBER,
  35209. this.getNumber());
  35210. case 0x7B: // '{'
  35211. this.nextChar();
  35212. return PostScriptToken.LBRACE;
  35213. case 0x7D: // '}'
  35214. this.nextChar();
  35215. return PostScriptToken.RBRACE;
  35216. }
  35217. // operator
  35218. var strBuf = this.strBuf;
  35219. strBuf.length = 0;
  35220. strBuf[0] = String.fromCharCode(ch);
  35221. while ((ch = this.nextChar()) >= 0 && // and 'A'-'Z', 'a'-'z'
  35222. ((ch >= 0x41 && ch <= 0x5A) || (ch >= 0x61 && ch <= 0x7A))) {
  35223. strBuf.push(String.fromCharCode(ch));
  35224. }
  35225. var str = strBuf.join('');
  35226. switch (str.toLowerCase()) {
  35227. case 'if':
  35228. return PostScriptToken.IF;
  35229. case 'ifelse':
  35230. return PostScriptToken.IFELSE;
  35231. default:
  35232. return PostScriptToken.getOperator(str);
  35233. }
  35234. },
  35235. getNumber: function PostScriptLexer_getNumber() {
  35236. var ch = this.currentChar;
  35237. var strBuf = this.strBuf;
  35238. strBuf.length = 0;
  35239. strBuf[0] = String.fromCharCode(ch);
  35240. while ((ch = this.nextChar()) >= 0) {
  35241. if ((ch >= 0x30 && ch <= 0x39) || // '0'-'9'
  35242. ch === 0x2D || ch === 0x2E) { // '-', '.'
  35243. strBuf.push(String.fromCharCode(ch));
  35244. } else {
  35245. break;
  35246. }
  35247. }
  35248. var value = parseFloat(strBuf.join(''));
  35249. if (isNaN(value)) {
  35250. error('Invalid floating point number: ' + value);
  35251. }
  35252. return value;
  35253. }
  35254. };
  35255. return PostScriptLexer;
  35256. })();
  35257. var Stream = (function StreamClosure() {
  35258. function Stream(arrayBuffer, start, length, dict) {
  35259. this.bytes = (arrayBuffer instanceof Uint8Array ?
  35260. arrayBuffer : new Uint8Array(arrayBuffer));
  35261. this.start = start || 0;
  35262. this.pos = this.start;
  35263. this.end = (start + length) || this.bytes.length;
  35264. this.dict = dict;
  35265. }
  35266. // required methods for a stream. if a particular stream does not
  35267. // implement these, an error should be thrown
  35268. Stream.prototype = {
  35269. get length() {
  35270. return this.end - this.start;
  35271. },
  35272. get isEmpty() {
  35273. return this.length === 0;
  35274. },
  35275. getByte: function Stream_getByte() {
  35276. if (this.pos >= this.end) {
  35277. return -1;
  35278. }
  35279. return this.bytes[this.pos++];
  35280. },
  35281. getUint16: function Stream_getUint16() {
  35282. var b0 = this.getByte();
  35283. var b1 = this.getByte();
  35284. if (b0 === -1 || b1 === -1) {
  35285. return -1;
  35286. }
  35287. return (b0 << 8) + b1;
  35288. },
  35289. getInt32: function Stream_getInt32() {
  35290. var b0 = this.getByte();
  35291. var b1 = this.getByte();
  35292. var b2 = this.getByte();
  35293. var b3 = this.getByte();
  35294. return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;
  35295. },
  35296. // returns subarray of original buffer
  35297. // should only be read
  35298. getBytes: function Stream_getBytes(length) {
  35299. var bytes = this.bytes;
  35300. var pos = this.pos;
  35301. var strEnd = this.end;
  35302. if (!length) {
  35303. return bytes.subarray(pos, strEnd);
  35304. }
  35305. var end = pos + length;
  35306. if (end > strEnd) {
  35307. end = strEnd;
  35308. }
  35309. this.pos = end;
  35310. return bytes.subarray(pos, end);
  35311. },
  35312. peekByte: function Stream_peekByte() {
  35313. var peekedByte = this.getByte();
  35314. this.pos--;
  35315. return peekedByte;
  35316. },
  35317. peekBytes: function Stream_peekBytes(length) {
  35318. var bytes = this.getBytes(length);
  35319. this.pos -= bytes.length;
  35320. return bytes;
  35321. },
  35322. skip: function Stream_skip(n) {
  35323. if (!n) {
  35324. n = 1;
  35325. }
  35326. this.pos += n;
  35327. },
  35328. reset: function Stream_reset() {
  35329. this.pos = this.start;
  35330. },
  35331. moveStart: function Stream_moveStart() {
  35332. this.start = this.pos;
  35333. },
  35334. makeSubStream: function Stream_makeSubStream(start, length, dict) {
  35335. return new Stream(this.bytes.buffer, start, length, dict);
  35336. },
  35337. isStream: true
  35338. };
  35339. return Stream;
  35340. })();
  35341. var StringStream = (function StringStreamClosure() {
  35342. function StringStream(str) {
  35343. var length = str.length;
  35344. var bytes = new Uint8Array(length);
  35345. for (var n = 0; n < length; ++n) {
  35346. bytes[n] = str.charCodeAt(n);
  35347. }
  35348. Stream.call(this, bytes);
  35349. }
  35350. StringStream.prototype = Stream.prototype;
  35351. return StringStream;
  35352. })();
  35353. // super class for the decoding streams
  35354. var DecodeStream = (function DecodeStreamClosure() {
  35355. // Lots of DecodeStreams are created whose buffers are never used. For these
  35356. // we share a single empty buffer. This is (a) space-efficient and (b) avoids
  35357. // having special cases that would be required if we used |null| for an empty
  35358. // buffer.
  35359. var emptyBuffer = new Uint8Array(0);
  35360. function DecodeStream(maybeMinBufferLength) {
  35361. this.pos = 0;
  35362. this.bufferLength = 0;
  35363. this.eof = false;
  35364. this.buffer = emptyBuffer;
  35365. this.minBufferLength = 512;
  35366. if (maybeMinBufferLength) {
  35367. // Compute the first power of two that is as big as maybeMinBufferLength.
  35368. while (this.minBufferLength < maybeMinBufferLength) {
  35369. this.minBufferLength *= 2;
  35370. }
  35371. }
  35372. }
  35373. DecodeStream.prototype = {
  35374. get isEmpty() {
  35375. while (!this.eof && this.bufferLength === 0) {
  35376. this.readBlock();
  35377. }
  35378. return this.bufferLength === 0;
  35379. },
  35380. ensureBuffer: function DecodeStream_ensureBuffer(requested) {
  35381. var buffer = this.buffer;
  35382. if (requested <= buffer.byteLength) {
  35383. return buffer;
  35384. }
  35385. var size = this.minBufferLength;
  35386. while (size < requested) {
  35387. size *= 2;
  35388. }
  35389. var buffer2 = new Uint8Array(size);
  35390. buffer2.set(buffer);
  35391. return (this.buffer = buffer2);
  35392. },
  35393. getByte: function DecodeStream_getByte() {
  35394. var pos = this.pos;
  35395. while (this.bufferLength <= pos) {
  35396. if (this.eof) {
  35397. return -1;
  35398. }
  35399. this.readBlock();
  35400. }
  35401. return this.buffer[this.pos++];
  35402. },
  35403. getUint16: function DecodeStream_getUint16() {
  35404. var b0 = this.getByte();
  35405. var b1 = this.getByte();
  35406. if (b0 === -1 || b1 === -1) {
  35407. return -1;
  35408. }
  35409. return (b0 << 8) + b1;
  35410. },
  35411. getInt32: function DecodeStream_getInt32() {
  35412. var b0 = this.getByte();
  35413. var b1 = this.getByte();
  35414. var b2 = this.getByte();
  35415. var b3 = this.getByte();
  35416. return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;
  35417. },
  35418. getBytes: function DecodeStream_getBytes(length) {
  35419. var end, pos = this.pos;
  35420. if (length) {
  35421. this.ensureBuffer(pos + length);
  35422. end = pos + length;
  35423. while (!this.eof && this.bufferLength < end) {
  35424. this.readBlock();
  35425. }
  35426. var bufEnd = this.bufferLength;
  35427. if (end > bufEnd) {
  35428. end = bufEnd;
  35429. }
  35430. } else {
  35431. while (!this.eof) {
  35432. this.readBlock();
  35433. }
  35434. end = this.bufferLength;
  35435. }
  35436. this.pos = end;
  35437. return this.buffer.subarray(pos, end);
  35438. },
  35439. peekByte: function DecodeStream_peekByte() {
  35440. var peekedByte = this.getByte();
  35441. this.pos--;
  35442. return peekedByte;
  35443. },
  35444. peekBytes: function DecodeStream_peekBytes(length) {
  35445. var bytes = this.getBytes(length);
  35446. this.pos -= bytes.length;
  35447. return bytes;
  35448. },
  35449. makeSubStream: function DecodeStream_makeSubStream(start, length, dict) {
  35450. var end = start + length;
  35451. while (this.bufferLength <= end && !this.eof) {
  35452. this.readBlock();
  35453. }
  35454. return new Stream(this.buffer, start, length, dict);
  35455. },
  35456. skip: function DecodeStream_skip(n) {
  35457. if (!n) {
  35458. n = 1;
  35459. }
  35460. this.pos += n;
  35461. },
  35462. reset: function DecodeStream_reset() {
  35463. this.pos = 0;
  35464. },
  35465. getBaseStreams: function DecodeStream_getBaseStreams() {
  35466. if (this.str && this.str.getBaseStreams) {
  35467. return this.str.getBaseStreams();
  35468. }
  35469. return [];
  35470. }
  35471. };
  35472. return DecodeStream;
  35473. })();
  35474. var StreamsSequenceStream = (function StreamsSequenceStreamClosure() {
  35475. function StreamsSequenceStream(streams) {
  35476. this.streams = streams;
  35477. DecodeStream.call(this, /* maybeLength = */ null);
  35478. }
  35479. StreamsSequenceStream.prototype = Object.create(DecodeStream.prototype);
  35480. StreamsSequenceStream.prototype.readBlock =
  35481. function streamSequenceStreamReadBlock() {
  35482. var streams = this.streams;
  35483. if (streams.length === 0) {
  35484. this.eof = true;
  35485. return;
  35486. }
  35487. var stream = streams.shift();
  35488. var chunk = stream.getBytes();
  35489. var bufferLength = this.bufferLength;
  35490. var newLength = bufferLength + chunk.length;
  35491. var buffer = this.ensureBuffer(newLength);
  35492. buffer.set(chunk, bufferLength);
  35493. this.bufferLength = newLength;
  35494. };
  35495. StreamsSequenceStream.prototype.getBaseStreams =
  35496. function StreamsSequenceStream_getBaseStreams() {
  35497. var baseStreams = [];
  35498. for (var i = 0, ii = this.streams.length; i < ii; i++) {
  35499. var stream = this.streams[i];
  35500. if (stream.getBaseStreams) {
  35501. Util.appendToArray(baseStreams, stream.getBaseStreams());
  35502. }
  35503. }
  35504. return baseStreams;
  35505. };
  35506. return StreamsSequenceStream;
  35507. })();
  35508. var FlateStream = (function FlateStreamClosure() {
  35509. var codeLenCodeMap = new Int32Array([
  35510. 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
  35511. ]);
  35512. var lengthDecode = new Int32Array([
  35513. 0x00003, 0x00004, 0x00005, 0x00006, 0x00007, 0x00008, 0x00009, 0x0000a,
  35514. 0x1000b, 0x1000d, 0x1000f, 0x10011, 0x20013, 0x20017, 0x2001b, 0x2001f,
  35515. 0x30023, 0x3002b, 0x30033, 0x3003b, 0x40043, 0x40053, 0x40063, 0x40073,
  35516. 0x50083, 0x500a3, 0x500c3, 0x500e3, 0x00102, 0x00102, 0x00102
  35517. ]);
  35518. var distDecode = new Int32Array([
  35519. 0x00001, 0x00002, 0x00003, 0x00004, 0x10005, 0x10007, 0x20009, 0x2000d,
  35520. 0x30011, 0x30019, 0x40021, 0x40031, 0x50041, 0x50061, 0x60081, 0x600c1,
  35521. 0x70101, 0x70181, 0x80201, 0x80301, 0x90401, 0x90601, 0xa0801, 0xa0c01,
  35522. 0xb1001, 0xb1801, 0xc2001, 0xc3001, 0xd4001, 0xd6001
  35523. ]);
  35524. var fixedLitCodeTab = [new Int32Array([
  35525. 0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c0,
  35526. 0x70108, 0x80060, 0x80020, 0x900a0, 0x80000, 0x80080, 0x80040, 0x900e0,
  35527. 0x70104, 0x80058, 0x80018, 0x90090, 0x70114, 0x80078, 0x80038, 0x900d0,
  35528. 0x7010c, 0x80068, 0x80028, 0x900b0, 0x80008, 0x80088, 0x80048, 0x900f0,
  35529. 0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c8,
  35530. 0x7010a, 0x80064, 0x80024, 0x900a8, 0x80004, 0x80084, 0x80044, 0x900e8,
  35531. 0x70106, 0x8005c, 0x8001c, 0x90098, 0x70116, 0x8007c, 0x8003c, 0x900d8,
  35532. 0x7010e, 0x8006c, 0x8002c, 0x900b8, 0x8000c, 0x8008c, 0x8004c, 0x900f8,
  35533. 0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c4,
  35534. 0x70109, 0x80062, 0x80022, 0x900a4, 0x80002, 0x80082, 0x80042, 0x900e4,
  35535. 0x70105, 0x8005a, 0x8001a, 0x90094, 0x70115, 0x8007a, 0x8003a, 0x900d4,
  35536. 0x7010d, 0x8006a, 0x8002a, 0x900b4, 0x8000a, 0x8008a, 0x8004a, 0x900f4,
  35537. 0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cc,
  35538. 0x7010b, 0x80066, 0x80026, 0x900ac, 0x80006, 0x80086, 0x80046, 0x900ec,
  35539. 0x70107, 0x8005e, 0x8001e, 0x9009c, 0x70117, 0x8007e, 0x8003e, 0x900dc,
  35540. 0x7010f, 0x8006e, 0x8002e, 0x900bc, 0x8000e, 0x8008e, 0x8004e, 0x900fc,
  35541. 0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c2,
  35542. 0x70108, 0x80061, 0x80021, 0x900a2, 0x80001, 0x80081, 0x80041, 0x900e2,
  35543. 0x70104, 0x80059, 0x80019, 0x90092, 0x70114, 0x80079, 0x80039, 0x900d2,
  35544. 0x7010c, 0x80069, 0x80029, 0x900b2, 0x80009, 0x80089, 0x80049, 0x900f2,
  35545. 0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900ca,
  35546. 0x7010a, 0x80065, 0x80025, 0x900aa, 0x80005, 0x80085, 0x80045, 0x900ea,
  35547. 0x70106, 0x8005d, 0x8001d, 0x9009a, 0x70116, 0x8007d, 0x8003d, 0x900da,
  35548. 0x7010e, 0x8006d, 0x8002d, 0x900ba, 0x8000d, 0x8008d, 0x8004d, 0x900fa,
  35549. 0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c6,
  35550. 0x70109, 0x80063, 0x80023, 0x900a6, 0x80003, 0x80083, 0x80043, 0x900e6,
  35551. 0x70105, 0x8005b, 0x8001b, 0x90096, 0x70115, 0x8007b, 0x8003b, 0x900d6,
  35552. 0x7010d, 0x8006b, 0x8002b, 0x900b6, 0x8000b, 0x8008b, 0x8004b, 0x900f6,
  35553. 0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900ce,
  35554. 0x7010b, 0x80067, 0x80027, 0x900ae, 0x80007, 0x80087, 0x80047, 0x900ee,
  35555. 0x70107, 0x8005f, 0x8001f, 0x9009e, 0x70117, 0x8007f, 0x8003f, 0x900de,
  35556. 0x7010f, 0x8006f, 0x8002f, 0x900be, 0x8000f, 0x8008f, 0x8004f, 0x900fe,
  35557. 0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c1,
  35558. 0x70108, 0x80060, 0x80020, 0x900a1, 0x80000, 0x80080, 0x80040, 0x900e1,
  35559. 0x70104, 0x80058, 0x80018, 0x90091, 0x70114, 0x80078, 0x80038, 0x900d1,
  35560. 0x7010c, 0x80068, 0x80028, 0x900b1, 0x80008, 0x80088, 0x80048, 0x900f1,
  35561. 0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c9,
  35562. 0x7010a, 0x80064, 0x80024, 0x900a9, 0x80004, 0x80084, 0x80044, 0x900e9,
  35563. 0x70106, 0x8005c, 0x8001c, 0x90099, 0x70116, 0x8007c, 0x8003c, 0x900d9,
  35564. 0x7010e, 0x8006c, 0x8002c, 0x900b9, 0x8000c, 0x8008c, 0x8004c, 0x900f9,
  35565. 0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c5,
  35566. 0x70109, 0x80062, 0x80022, 0x900a5, 0x80002, 0x80082, 0x80042, 0x900e5,
  35567. 0x70105, 0x8005a, 0x8001a, 0x90095, 0x70115, 0x8007a, 0x8003a, 0x900d5,
  35568. 0x7010d, 0x8006a, 0x8002a, 0x900b5, 0x8000a, 0x8008a, 0x8004a, 0x900f5,
  35569. 0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cd,
  35570. 0x7010b, 0x80066, 0x80026, 0x900ad, 0x80006, 0x80086, 0x80046, 0x900ed,
  35571. 0x70107, 0x8005e, 0x8001e, 0x9009d, 0x70117, 0x8007e, 0x8003e, 0x900dd,
  35572. 0x7010f, 0x8006e, 0x8002e, 0x900bd, 0x8000e, 0x8008e, 0x8004e, 0x900fd,
  35573. 0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c3,
  35574. 0x70108, 0x80061, 0x80021, 0x900a3, 0x80001, 0x80081, 0x80041, 0x900e3,
  35575. 0x70104, 0x80059, 0x80019, 0x90093, 0x70114, 0x80079, 0x80039, 0x900d3,
  35576. 0x7010c, 0x80069, 0x80029, 0x900b3, 0x80009, 0x80089, 0x80049, 0x900f3,
  35577. 0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900cb,
  35578. 0x7010a, 0x80065, 0x80025, 0x900ab, 0x80005, 0x80085, 0x80045, 0x900eb,
  35579. 0x70106, 0x8005d, 0x8001d, 0x9009b, 0x70116, 0x8007d, 0x8003d, 0x900db,
  35580. 0x7010e, 0x8006d, 0x8002d, 0x900bb, 0x8000d, 0x8008d, 0x8004d, 0x900fb,
  35581. 0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c7,
  35582. 0x70109, 0x80063, 0x80023, 0x900a7, 0x80003, 0x80083, 0x80043, 0x900e7,
  35583. 0x70105, 0x8005b, 0x8001b, 0x90097, 0x70115, 0x8007b, 0x8003b, 0x900d7,
  35584. 0x7010d, 0x8006b, 0x8002b, 0x900b7, 0x8000b, 0x8008b, 0x8004b, 0x900f7,
  35585. 0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900cf,
  35586. 0x7010b, 0x80067, 0x80027, 0x900af, 0x80007, 0x80087, 0x80047, 0x900ef,
  35587. 0x70107, 0x8005f, 0x8001f, 0x9009f, 0x70117, 0x8007f, 0x8003f, 0x900df,
  35588. 0x7010f, 0x8006f, 0x8002f, 0x900bf, 0x8000f, 0x8008f, 0x8004f, 0x900ff
  35589. ]), 9];
  35590. var fixedDistCodeTab = [new Int32Array([
  35591. 0x50000, 0x50010, 0x50008, 0x50018, 0x50004, 0x50014, 0x5000c, 0x5001c,
  35592. 0x50002, 0x50012, 0x5000a, 0x5001a, 0x50006, 0x50016, 0x5000e, 0x00000,
  35593. 0x50001, 0x50011, 0x50009, 0x50019, 0x50005, 0x50015, 0x5000d, 0x5001d,
  35594. 0x50003, 0x50013, 0x5000b, 0x5001b, 0x50007, 0x50017, 0x5000f, 0x00000
  35595. ]), 5];
  35596. function FlateStream(str, maybeLength) {
  35597. this.str = str;
  35598. this.dict = str.dict;
  35599. var cmf = str.getByte();
  35600. var flg = str.getByte();
  35601. if (cmf === -1 || flg === -1) {
  35602. error('Invalid header in flate stream: ' + cmf + ', ' + flg);
  35603. }
  35604. if ((cmf & 0x0f) !== 0x08) {
  35605. error('Unknown compression method in flate stream: ' + cmf + ', ' + flg);
  35606. }
  35607. if ((((cmf << 8) + flg) % 31) !== 0) {
  35608. error('Bad FCHECK in flate stream: ' + cmf + ', ' + flg);
  35609. }
  35610. if (flg & 0x20) {
  35611. error('FDICT bit set in flate stream: ' + cmf + ', ' + flg);
  35612. }
  35613. this.codeSize = 0;
  35614. this.codeBuf = 0;
  35615. DecodeStream.call(this, maybeLength);
  35616. }
  35617. FlateStream.prototype = Object.create(DecodeStream.prototype);
  35618. FlateStream.prototype.getBits = function FlateStream_getBits(bits) {
  35619. var str = this.str;
  35620. var codeSize = this.codeSize;
  35621. var codeBuf = this.codeBuf;
  35622. var b;
  35623. while (codeSize < bits) {
  35624. if ((b = str.getByte()) === -1) {
  35625. error('Bad encoding in flate stream');
  35626. }
  35627. codeBuf |= b << codeSize;
  35628. codeSize += 8;
  35629. }
  35630. b = codeBuf & ((1 << bits) - 1);
  35631. this.codeBuf = codeBuf >> bits;
  35632. this.codeSize = codeSize -= bits;
  35633. return b;
  35634. };
  35635. FlateStream.prototype.getCode = function FlateStream_getCode(table) {
  35636. var str = this.str;
  35637. var codes = table[0];
  35638. var maxLen = table[1];
  35639. var codeSize = this.codeSize;
  35640. var codeBuf = this.codeBuf;
  35641. var b;
  35642. while (codeSize < maxLen) {
  35643. if ((b = str.getByte()) === -1) {
  35644. // premature end of stream. code might however still be valid.
  35645. // codeSize < codeLen check below guards against incomplete codeVal.
  35646. break;
  35647. }
  35648. codeBuf |= (b << codeSize);
  35649. codeSize += 8;
  35650. }
  35651. var code = codes[codeBuf & ((1 << maxLen) - 1)];
  35652. var codeLen = code >> 16;
  35653. var codeVal = code & 0xffff;
  35654. if (codeLen < 1 || codeSize < codeLen) {
  35655. error('Bad encoding in flate stream');
  35656. }
  35657. this.codeBuf = (codeBuf >> codeLen);
  35658. this.codeSize = (codeSize - codeLen);
  35659. return codeVal;
  35660. };
  35661. FlateStream.prototype.generateHuffmanTable =
  35662. function flateStreamGenerateHuffmanTable(lengths) {
  35663. var n = lengths.length;
  35664. // find max code length
  35665. var maxLen = 0;
  35666. var i;
  35667. for (i = 0; i < n; ++i) {
  35668. if (lengths[i] > maxLen) {
  35669. maxLen = lengths[i];
  35670. }
  35671. }
  35672. // build the table
  35673. var size = 1 << maxLen;
  35674. var codes = new Int32Array(size);
  35675. for (var len = 1, code = 0, skip = 2;
  35676. len <= maxLen;
  35677. ++len, code <<= 1, skip <<= 1) {
  35678. for (var val = 0; val < n; ++val) {
  35679. if (lengths[val] === len) {
  35680. // bit-reverse the code
  35681. var code2 = 0;
  35682. var t = code;
  35683. for (i = 0; i < len; ++i) {
  35684. code2 = (code2 << 1) | (t & 1);
  35685. t >>= 1;
  35686. }
  35687. // fill the table entries
  35688. for (i = code2; i < size; i += skip) {
  35689. codes[i] = (len << 16) | val;
  35690. }
  35691. ++code;
  35692. }
  35693. }
  35694. }
  35695. return [codes, maxLen];
  35696. };
  35697. FlateStream.prototype.readBlock = function FlateStream_readBlock() {
  35698. var buffer, len;
  35699. var str = this.str;
  35700. // read block header
  35701. var hdr = this.getBits(3);
  35702. if (hdr & 1) {
  35703. this.eof = true;
  35704. }
  35705. hdr >>= 1;
  35706. if (hdr === 0) { // uncompressed block
  35707. var b;
  35708. if ((b = str.getByte()) === -1) {
  35709. error('Bad block header in flate stream');
  35710. }
  35711. var blockLen = b;
  35712. if ((b = str.getByte()) === -1) {
  35713. error('Bad block header in flate stream');
  35714. }
  35715. blockLen |= (b << 8);
  35716. if ((b = str.getByte()) === -1) {
  35717. error('Bad block header in flate stream');
  35718. }
  35719. var check = b;
  35720. if ((b = str.getByte()) === -1) {
  35721. error('Bad block header in flate stream');
  35722. }
  35723. check |= (b << 8);
  35724. if (check !== (~blockLen & 0xffff) &&
  35725. (blockLen !== 0 || check !== 0)) {
  35726. // Ignoring error for bad "empty" block (see issue 1277)
  35727. error('Bad uncompressed block length in flate stream');
  35728. }
  35729. this.codeBuf = 0;
  35730. this.codeSize = 0;
  35731. var bufferLength = this.bufferLength;
  35732. buffer = this.ensureBuffer(bufferLength + blockLen);
  35733. var end = bufferLength + blockLen;
  35734. this.bufferLength = end;
  35735. if (blockLen === 0) {
  35736. if (str.peekByte() === -1) {
  35737. this.eof = true;
  35738. }
  35739. } else {
  35740. for (var n = bufferLength; n < end; ++n) {
  35741. if ((b = str.getByte()) === -1) {
  35742. this.eof = true;
  35743. break;
  35744. }
  35745. buffer[n] = b;
  35746. }
  35747. }
  35748. return;
  35749. }
  35750. var litCodeTable;
  35751. var distCodeTable;
  35752. if (hdr === 1) { // compressed block, fixed codes
  35753. litCodeTable = fixedLitCodeTab;
  35754. distCodeTable = fixedDistCodeTab;
  35755. } else if (hdr === 2) { // compressed block, dynamic codes
  35756. var numLitCodes = this.getBits(5) + 257;
  35757. var numDistCodes = this.getBits(5) + 1;
  35758. var numCodeLenCodes = this.getBits(4) + 4;
  35759. // build the code lengths code table
  35760. var codeLenCodeLengths = new Uint8Array(codeLenCodeMap.length);
  35761. var i;
  35762. for (i = 0; i < numCodeLenCodes; ++i) {
  35763. codeLenCodeLengths[codeLenCodeMap[i]] = this.getBits(3);
  35764. }
  35765. var codeLenCodeTab = this.generateHuffmanTable(codeLenCodeLengths);
  35766. // build the literal and distance code tables
  35767. len = 0;
  35768. i = 0;
  35769. var codes = numLitCodes + numDistCodes;
  35770. var codeLengths = new Uint8Array(codes);
  35771. var bitsLength, bitsOffset, what;
  35772. while (i < codes) {
  35773. var code = this.getCode(codeLenCodeTab);
  35774. if (code === 16) {
  35775. bitsLength = 2; bitsOffset = 3; what = len;
  35776. } else if (code === 17) {
  35777. bitsLength = 3; bitsOffset = 3; what = (len = 0);
  35778. } else if (code === 18) {
  35779. bitsLength = 7; bitsOffset = 11; what = (len = 0);
  35780. } else {
  35781. codeLengths[i++] = len = code;
  35782. continue;
  35783. }
  35784. var repeatLength = this.getBits(bitsLength) + bitsOffset;
  35785. while (repeatLength-- > 0) {
  35786. codeLengths[i++] = what;
  35787. }
  35788. }
  35789. litCodeTable =
  35790. this.generateHuffmanTable(codeLengths.subarray(0, numLitCodes));
  35791. distCodeTable =
  35792. this.generateHuffmanTable(codeLengths.subarray(numLitCodes, codes));
  35793. } else {
  35794. error('Unknown block type in flate stream');
  35795. }
  35796. buffer = this.buffer;
  35797. var limit = buffer ? buffer.length : 0;
  35798. var pos = this.bufferLength;
  35799. while (true) {
  35800. var code1 = this.getCode(litCodeTable);
  35801. if (code1 < 256) {
  35802. if (pos + 1 >= limit) {
  35803. buffer = this.ensureBuffer(pos + 1);
  35804. limit = buffer.length;
  35805. }
  35806. buffer[pos++] = code1;
  35807. continue;
  35808. }
  35809. if (code1 === 256) {
  35810. this.bufferLength = pos;
  35811. return;
  35812. }
  35813. code1 -= 257;
  35814. code1 = lengthDecode[code1];
  35815. var code2 = code1 >> 16;
  35816. if (code2 > 0) {
  35817. code2 = this.getBits(code2);
  35818. }
  35819. len = (code1 & 0xffff) + code2;
  35820. code1 = this.getCode(distCodeTable);
  35821. code1 = distDecode[code1];
  35822. code2 = code1 >> 16;
  35823. if (code2 > 0) {
  35824. code2 = this.getBits(code2);
  35825. }
  35826. var dist = (code1 & 0xffff) + code2;
  35827. if (pos + len >= limit) {
  35828. buffer = this.ensureBuffer(pos + len);
  35829. limit = buffer.length;
  35830. }
  35831. for (var k = 0; k < len; ++k, ++pos) {
  35832. buffer[pos] = buffer[pos - dist];
  35833. }
  35834. }
  35835. };
  35836. return FlateStream;
  35837. })();
  35838. var PredictorStream = (function PredictorStreamClosure() {
  35839. function PredictorStream(str, maybeLength, params) {
  35840. var predictor = this.predictor = params.get('Predictor') || 1;
  35841. if (predictor <= 1) {
  35842. return str; // no prediction
  35843. }
  35844. if (predictor !== 2 && (predictor < 10 || predictor > 15)) {
  35845. error('Unsupported predictor: ' + predictor);
  35846. }
  35847. if (predictor === 2) {
  35848. this.readBlock = this.readBlockTiff;
  35849. } else {
  35850. this.readBlock = this.readBlockPng;
  35851. }
  35852. this.str = str;
  35853. this.dict = str.dict;
  35854. var colors = this.colors = params.get('Colors') || 1;
  35855. var bits = this.bits = params.get('BitsPerComponent') || 8;
  35856. var columns = this.columns = params.get('Columns') || 1;
  35857. this.pixBytes = (colors * bits + 7) >> 3;
  35858. this.rowBytes = (columns * colors * bits + 7) >> 3;
  35859. DecodeStream.call(this, maybeLength);
  35860. return this;
  35861. }
  35862. PredictorStream.prototype = Object.create(DecodeStream.prototype);
  35863. PredictorStream.prototype.readBlockTiff =
  35864. function predictorStreamReadBlockTiff() {
  35865. var rowBytes = this.rowBytes;
  35866. var bufferLength = this.bufferLength;
  35867. var buffer = this.ensureBuffer(bufferLength + rowBytes);
  35868. var bits = this.bits;
  35869. var colors = this.colors;
  35870. var rawBytes = this.str.getBytes(rowBytes);
  35871. this.eof = !rawBytes.length;
  35872. if (this.eof) {
  35873. return;
  35874. }
  35875. var inbuf = 0, outbuf = 0;
  35876. var inbits = 0, outbits = 0;
  35877. var pos = bufferLength;
  35878. var i;
  35879. if (bits === 1) {
  35880. for (i = 0; i < rowBytes; ++i) {
  35881. var c = rawBytes[i];
  35882. inbuf = (inbuf << 8) | c;
  35883. // bitwise addition is exclusive or
  35884. // first shift inbuf and then add
  35885. buffer[pos++] = (c ^ (inbuf >> colors)) & 0xFF;
  35886. // truncate inbuf (assumes colors < 16)
  35887. inbuf &= 0xFFFF;
  35888. }
  35889. } else if (bits === 8) {
  35890. for (i = 0; i < colors; ++i) {
  35891. buffer[pos++] = rawBytes[i];
  35892. }
  35893. for (; i < rowBytes; ++i) {
  35894. buffer[pos] = buffer[pos - colors] + rawBytes[i];
  35895. pos++;
  35896. }
  35897. } else {
  35898. var compArray = new Uint8Array(colors + 1);
  35899. var bitMask = (1 << bits) - 1;
  35900. var j = 0, k = bufferLength;
  35901. var columns = this.columns;
  35902. for (i = 0; i < columns; ++i) {
  35903. for (var kk = 0; kk < colors; ++kk) {
  35904. if (inbits < bits) {
  35905. inbuf = (inbuf << 8) | (rawBytes[j++] & 0xFF);
  35906. inbits += 8;
  35907. }
  35908. compArray[kk] = (compArray[kk] +
  35909. (inbuf >> (inbits - bits))) & bitMask;
  35910. inbits -= bits;
  35911. outbuf = (outbuf << bits) | compArray[kk];
  35912. outbits += bits;
  35913. if (outbits >= 8) {
  35914. buffer[k++] = (outbuf >> (outbits - 8)) & 0xFF;
  35915. outbits -= 8;
  35916. }
  35917. }
  35918. }
  35919. if (outbits > 0) {
  35920. buffer[k++] = (outbuf << (8 - outbits)) +
  35921. (inbuf & ((1 << (8 - outbits)) - 1));
  35922. }
  35923. }
  35924. this.bufferLength += rowBytes;
  35925. };
  35926. PredictorStream.prototype.readBlockPng =
  35927. function predictorStreamReadBlockPng() {
  35928. var rowBytes = this.rowBytes;
  35929. var pixBytes = this.pixBytes;
  35930. var predictor = this.str.getByte();
  35931. var rawBytes = this.str.getBytes(rowBytes);
  35932. this.eof = !rawBytes.length;
  35933. if (this.eof) {
  35934. return;
  35935. }
  35936. var bufferLength = this.bufferLength;
  35937. var buffer = this.ensureBuffer(bufferLength + rowBytes);
  35938. var prevRow = buffer.subarray(bufferLength - rowBytes, bufferLength);
  35939. if (prevRow.length === 0) {
  35940. prevRow = new Uint8Array(rowBytes);
  35941. }
  35942. var i, j = bufferLength, up, c;
  35943. switch (predictor) {
  35944. case 0:
  35945. for (i = 0; i < rowBytes; ++i) {
  35946. buffer[j++] = rawBytes[i];
  35947. }
  35948. break;
  35949. case 1:
  35950. for (i = 0; i < pixBytes; ++i) {
  35951. buffer[j++] = rawBytes[i];
  35952. }
  35953. for (; i < rowBytes; ++i) {
  35954. buffer[j] = (buffer[j - pixBytes] + rawBytes[i]) & 0xFF;
  35955. j++;
  35956. }
  35957. break;
  35958. case 2:
  35959. for (i = 0; i < rowBytes; ++i) {
  35960. buffer[j++] = (prevRow[i] + rawBytes[i]) & 0xFF;
  35961. }
  35962. break;
  35963. case 3:
  35964. for (i = 0; i < pixBytes; ++i) {
  35965. buffer[j++] = (prevRow[i] >> 1) + rawBytes[i];
  35966. }
  35967. for (; i < rowBytes; ++i) {
  35968. buffer[j] = (((prevRow[i] + buffer[j - pixBytes]) >> 1) +
  35969. rawBytes[i]) & 0xFF;
  35970. j++;
  35971. }
  35972. break;
  35973. case 4:
  35974. // we need to save the up left pixels values. the simplest way
  35975. // is to create a new buffer
  35976. for (i = 0; i < pixBytes; ++i) {
  35977. up = prevRow[i];
  35978. c = rawBytes[i];
  35979. buffer[j++] = up + c;
  35980. }
  35981. for (; i < rowBytes; ++i) {
  35982. up = prevRow[i];
  35983. var upLeft = prevRow[i - pixBytes];
  35984. var left = buffer[j - pixBytes];
  35985. var p = left + up - upLeft;
  35986. var pa = p - left;
  35987. if (pa < 0) {
  35988. pa = -pa;
  35989. }
  35990. var pb = p - up;
  35991. if (pb < 0) {
  35992. pb = -pb;
  35993. }
  35994. var pc = p - upLeft;
  35995. if (pc < 0) {
  35996. pc = -pc;
  35997. }
  35998. c = rawBytes[i];
  35999. if (pa <= pb && pa <= pc) {
  36000. buffer[j++] = left + c;
  36001. } else if (pb <= pc) {
  36002. buffer[j++] = up + c;
  36003. } else {
  36004. buffer[j++] = upLeft + c;
  36005. }
  36006. }
  36007. break;
  36008. default:
  36009. error('Unsupported predictor: ' + predictor);
  36010. }
  36011. this.bufferLength += rowBytes;
  36012. };
  36013. return PredictorStream;
  36014. })();
  36015. /**
  36016. * Depending on the type of JPEG a JpegStream is handled in different ways. For
  36017. * JPEG's that are supported natively such as DeviceGray and DeviceRGB the image
  36018. * data is stored and then loaded by the browser. For unsupported JPEG's we use
  36019. * a library to decode these images and the stream behaves like all the other
  36020. * DecodeStreams.
  36021. */
  36022. var JpegStream = (function JpegStreamClosure() {
  36023. function JpegStream(stream, maybeLength, dict, xref) {
  36024. // Some images may contain 'junk' before the SOI (start-of-image) marker.
  36025. // Note: this seems to mainly affect inline images.
  36026. var ch;
  36027. while ((ch = stream.getByte()) !== -1) {
  36028. if (ch === 0xFF) { // Find the first byte of the SOI marker (0xFFD8).
  36029. stream.skip(-1); // Reset the stream position to the SOI.
  36030. break;
  36031. }
  36032. }
  36033. this.stream = stream;
  36034. this.maybeLength = maybeLength;
  36035. this.dict = dict;
  36036. DecodeStream.call(this, maybeLength);
  36037. }
  36038. JpegStream.prototype = Object.create(DecodeStream.prototype);
  36039. Object.defineProperty(JpegStream.prototype, 'bytes', {
  36040. get: function JpegStream_bytes() {
  36041. // If this.maybeLength is null, we'll get the entire stream.
  36042. return shadow(this, 'bytes', this.stream.getBytes(this.maybeLength));
  36043. },
  36044. configurable: true
  36045. });
  36046. JpegStream.prototype.ensureBuffer = function JpegStream_ensureBuffer(req) {
  36047. if (this.bufferLength) {
  36048. return;
  36049. }
  36050. try {
  36051. var jpegImage = new JpegImage();
  36052. // checking if values needs to be transformed before conversion
  36053. if (this.forceRGB && this.dict && isArray(this.dict.get('Decode'))) {
  36054. var decodeArr = this.dict.get('Decode');
  36055. var bitsPerComponent = this.dict.get('BitsPerComponent') || 8;
  36056. var decodeArrLength = decodeArr.length;
  36057. var transform = new Int32Array(decodeArrLength);
  36058. var transformNeeded = false;
  36059. var maxValue = (1 << bitsPerComponent) - 1;
  36060. for (var i = 0; i < decodeArrLength; i += 2) {
  36061. transform[i] = ((decodeArr[i + 1] - decodeArr[i]) * 256) | 0;
  36062. transform[i + 1] = (decodeArr[i] * maxValue) | 0;
  36063. if (transform[i] !== 256 || transform[i + 1] !== 0) {
  36064. transformNeeded = true;
  36065. }
  36066. }
  36067. if (transformNeeded) {
  36068. jpegImage.decodeTransform = transform;
  36069. }
  36070. }
  36071. jpegImage.parse(this.bytes);
  36072. var data = jpegImage.getData(this.drawWidth, this.drawHeight,
  36073. this.forceRGB);
  36074. this.buffer = data;
  36075. this.bufferLength = data.length;
  36076. this.eof = true;
  36077. } catch (e) {
  36078. error('JPEG error: ' + e);
  36079. }
  36080. };
  36081. JpegStream.prototype.getBytes = function JpegStream_getBytes(length) {
  36082. this.ensureBuffer();
  36083. return this.buffer;
  36084. };
  36085. JpegStream.prototype.getIR = function JpegStream_getIR() {
  36086. return PDFJS.createObjectURL(this.bytes, 'image/jpeg');
  36087. };
  36088. /**
  36089. * Checks if the image can be decoded and displayed by the browser without any
  36090. * further processing such as color space conversions.
  36091. */
  36092. JpegStream.prototype.isNativelySupported =
  36093. function JpegStream_isNativelySupported(xref, res) {
  36094. var cs = ColorSpace.parse(this.dict.get('ColorSpace', 'CS'), xref, res);
  36095. return cs.name === 'DeviceGray' || cs.name === 'DeviceRGB';
  36096. };
  36097. /**
  36098. * Checks if the image can be decoded by the browser.
  36099. */
  36100. JpegStream.prototype.isNativelyDecodable =
  36101. function JpegStream_isNativelyDecodable(xref, res) {
  36102. var cs = ColorSpace.parse(this.dict.get('ColorSpace', 'CS'), xref, res);
  36103. var numComps = cs.numComps;
  36104. return numComps === 1 || numComps === 3;
  36105. };
  36106. return JpegStream;
  36107. })();
  36108. /**
  36109. * For JPEG 2000's we use a library to decode these images and
  36110. * the stream behaves like all the other DecodeStreams.
  36111. */
  36112. var JpxStream = (function JpxStreamClosure() {
  36113. function JpxStream(stream, maybeLength, dict) {
  36114. this.stream = stream;
  36115. this.maybeLength = maybeLength;
  36116. this.dict = dict;
  36117. DecodeStream.call(this, maybeLength);
  36118. }
  36119. JpxStream.prototype = Object.create(DecodeStream.prototype);
  36120. Object.defineProperty(JpxStream.prototype, 'bytes', {
  36121. get: function JpxStream_bytes() {
  36122. // If this.maybeLength is null, we'll get the entire stream.
  36123. return shadow(this, 'bytes', this.stream.getBytes(this.maybeLength));
  36124. },
  36125. configurable: true
  36126. });
  36127. JpxStream.prototype.ensureBuffer = function JpxStream_ensureBuffer(req) {
  36128. if (this.bufferLength) {
  36129. return;
  36130. }
  36131. var jpxImage = new JpxImage();
  36132. jpxImage.parse(this.bytes);
  36133. var width = jpxImage.width;
  36134. var height = jpxImage.height;
  36135. var componentsCount = jpxImage.componentsCount;
  36136. var tileCount = jpxImage.tiles.length;
  36137. if (tileCount === 1) {
  36138. this.buffer = jpxImage.tiles[0].items;
  36139. } else {
  36140. var data = new Uint8Array(width * height * componentsCount);
  36141. for (var k = 0; k < tileCount; k++) {
  36142. var tileComponents = jpxImage.tiles[k];
  36143. var tileWidth = tileComponents.width;
  36144. var tileHeight = tileComponents.height;
  36145. var tileLeft = tileComponents.left;
  36146. var tileTop = tileComponents.top;
  36147. var src = tileComponents.items;
  36148. var srcPosition = 0;
  36149. var dataPosition = (width * tileTop + tileLeft) * componentsCount;
  36150. var imgRowSize = width * componentsCount;
  36151. var tileRowSize = tileWidth * componentsCount;
  36152. for (var j = 0; j < tileHeight; j++) {
  36153. var rowBytes = src.subarray(srcPosition, srcPosition + tileRowSize);
  36154. data.set(rowBytes, dataPosition);
  36155. srcPosition += tileRowSize;
  36156. dataPosition += imgRowSize;
  36157. }
  36158. }
  36159. this.buffer = data;
  36160. }
  36161. this.bufferLength = this.buffer.length;
  36162. this.eof = true;
  36163. };
  36164. return JpxStream;
  36165. })();
  36166. /**
  36167. * For JBIG2's we use a library to decode these images and
  36168. * the stream behaves like all the other DecodeStreams.
  36169. */
  36170. var Jbig2Stream = (function Jbig2StreamClosure() {
  36171. function Jbig2Stream(stream, maybeLength, dict) {
  36172. this.stream = stream;
  36173. this.maybeLength = maybeLength;
  36174. this.dict = dict;
  36175. DecodeStream.call(this, maybeLength);
  36176. }
  36177. Jbig2Stream.prototype = Object.create(DecodeStream.prototype);
  36178. Object.defineProperty(Jbig2Stream.prototype, 'bytes', {
  36179. get: function Jbig2Stream_bytes() {
  36180. // If this.maybeLength is null, we'll get the entire stream.
  36181. return shadow(this, 'bytes', this.stream.getBytes(this.maybeLength));
  36182. },
  36183. configurable: true
  36184. });
  36185. Jbig2Stream.prototype.ensureBuffer = function Jbig2Stream_ensureBuffer(req) {
  36186. if (this.bufferLength) {
  36187. return;
  36188. }
  36189. var jbig2Image = new Jbig2Image();
  36190. var chunks = [], xref = this.dict.xref;
  36191. var decodeParams = xref.fetchIfRef(this.dict.get('DecodeParms'));
  36192. // According to the PDF specification, DecodeParms can be either
  36193. // a dictionary, or an array whose elements are dictionaries.
  36194. if (isArray(decodeParams)) {
  36195. if (decodeParams.length > 1) {
  36196. warn('JBIG2 - \'DecodeParms\' array with multiple elements ' +
  36197. 'not supported.');
  36198. }
  36199. decodeParams = xref.fetchIfRef(decodeParams[0]);
  36200. }
  36201. if (decodeParams && decodeParams.has('JBIG2Globals')) {
  36202. var globalsStream = decodeParams.get('JBIG2Globals');
  36203. var globals = globalsStream.getBytes();
  36204. chunks.push({data: globals, start: 0, end: globals.length});
  36205. }
  36206. chunks.push({data: this.bytes, start: 0, end: this.bytes.length});
  36207. var data = jbig2Image.parseChunks(chunks);
  36208. var dataLength = data.length;
  36209. // JBIG2 had black as 1 and white as 0, inverting the colors
  36210. for (var i = 0; i < dataLength; i++) {
  36211. data[i] ^= 0xFF;
  36212. }
  36213. this.buffer = data;
  36214. this.bufferLength = dataLength;
  36215. this.eof = true;
  36216. };
  36217. return Jbig2Stream;
  36218. })();
  36219. var DecryptStream = (function DecryptStreamClosure() {
  36220. function DecryptStream(str, maybeLength, decrypt) {
  36221. this.str = str;
  36222. this.dict = str.dict;
  36223. this.decrypt = decrypt;
  36224. this.nextChunk = null;
  36225. this.initialized = false;
  36226. DecodeStream.call(this, maybeLength);
  36227. }
  36228. var chunkSize = 512;
  36229. DecryptStream.prototype = Object.create(DecodeStream.prototype);
  36230. DecryptStream.prototype.readBlock = function DecryptStream_readBlock() {
  36231. var chunk;
  36232. if (this.initialized) {
  36233. chunk = this.nextChunk;
  36234. } else {
  36235. chunk = this.str.getBytes(chunkSize);
  36236. this.initialized = true;
  36237. }
  36238. if (!chunk || chunk.length === 0) {
  36239. this.eof = true;
  36240. return;
  36241. }
  36242. this.nextChunk = this.str.getBytes(chunkSize);
  36243. var hasMoreData = this.nextChunk && this.nextChunk.length > 0;
  36244. var decrypt = this.decrypt;
  36245. chunk = decrypt(chunk, !hasMoreData);
  36246. var bufferLength = this.bufferLength;
  36247. var i, n = chunk.length;
  36248. var buffer = this.ensureBuffer(bufferLength + n);
  36249. for (i = 0; i < n; i++) {
  36250. buffer[bufferLength++] = chunk[i];
  36251. }
  36252. this.bufferLength = bufferLength;
  36253. };
  36254. return DecryptStream;
  36255. })();
  36256. var Ascii85Stream = (function Ascii85StreamClosure() {
  36257. function Ascii85Stream(str, maybeLength) {
  36258. this.str = str;
  36259. this.dict = str.dict;
  36260. this.input = new Uint8Array(5);
  36261. // Most streams increase in size when decoded, but Ascii85 streams
  36262. // typically shrink by ~20%.
  36263. if (maybeLength) {
  36264. maybeLength = 0.8 * maybeLength;
  36265. }
  36266. DecodeStream.call(this, maybeLength);
  36267. }
  36268. Ascii85Stream.prototype = Object.create(DecodeStream.prototype);
  36269. Ascii85Stream.prototype.readBlock = function Ascii85Stream_readBlock() {
  36270. var TILDA_CHAR = 0x7E; // '~'
  36271. var Z_LOWER_CHAR = 0x7A; // 'z'
  36272. var EOF = -1;
  36273. var str = this.str;
  36274. var c = str.getByte();
  36275. while (Lexer.isSpace(c)) {
  36276. c = str.getByte();
  36277. }
  36278. if (c === EOF || c === TILDA_CHAR) {
  36279. this.eof = true;
  36280. return;
  36281. }
  36282. var bufferLength = this.bufferLength, buffer;
  36283. var i;
  36284. // special code for z
  36285. if (c === Z_LOWER_CHAR) {
  36286. buffer = this.ensureBuffer(bufferLength + 4);
  36287. for (i = 0; i < 4; ++i) {
  36288. buffer[bufferLength + i] = 0;
  36289. }
  36290. this.bufferLength += 4;
  36291. } else {
  36292. var input = this.input;
  36293. input[0] = c;
  36294. for (i = 1; i < 5; ++i) {
  36295. c = str.getByte();
  36296. while (Lexer.isSpace(c)) {
  36297. c = str.getByte();
  36298. }
  36299. input[i] = c;
  36300. if (c === EOF || c === TILDA_CHAR) {
  36301. break;
  36302. }
  36303. }
  36304. buffer = this.ensureBuffer(bufferLength + i - 1);
  36305. this.bufferLength += i - 1;
  36306. // partial ending;
  36307. if (i < 5) {
  36308. for (; i < 5; ++i) {
  36309. input[i] = 0x21 + 84;
  36310. }
  36311. this.eof = true;
  36312. }
  36313. var t = 0;
  36314. for (i = 0; i < 5; ++i) {
  36315. t = t * 85 + (input[i] - 0x21);
  36316. }
  36317. for (i = 3; i >= 0; --i) {
  36318. buffer[bufferLength + i] = t & 0xFF;
  36319. t >>= 8;
  36320. }
  36321. }
  36322. };
  36323. return Ascii85Stream;
  36324. })();
  36325. var AsciiHexStream = (function AsciiHexStreamClosure() {
  36326. function AsciiHexStream(str, maybeLength) {
  36327. this.str = str;
  36328. this.dict = str.dict;
  36329. this.firstDigit = -1;
  36330. // Most streams increase in size when decoded, but AsciiHex streams shrink
  36331. // by 50%.
  36332. if (maybeLength) {
  36333. maybeLength = 0.5 * maybeLength;
  36334. }
  36335. DecodeStream.call(this, maybeLength);
  36336. }
  36337. AsciiHexStream.prototype = Object.create(DecodeStream.prototype);
  36338. AsciiHexStream.prototype.readBlock = function AsciiHexStream_readBlock() {
  36339. var UPSTREAM_BLOCK_SIZE = 8000;
  36340. var bytes = this.str.getBytes(UPSTREAM_BLOCK_SIZE);
  36341. if (!bytes.length) {
  36342. this.eof = true;
  36343. return;
  36344. }
  36345. var maxDecodeLength = (bytes.length + 1) >> 1;
  36346. var buffer = this.ensureBuffer(this.bufferLength + maxDecodeLength);
  36347. var bufferLength = this.bufferLength;
  36348. var firstDigit = this.firstDigit;
  36349. for (var i = 0, ii = bytes.length; i < ii; i++) {
  36350. var ch = bytes[i], digit;
  36351. if (ch >= 0x30 && ch <= 0x39) { // '0'-'9'
  36352. digit = ch & 0x0F;
  36353. } else if ((ch >= 0x41 && ch <= 0x46) || (ch >= 0x61 && ch <= 0x66)) {
  36354. // 'A'-'Z', 'a'-'z'
  36355. digit = (ch & 0x0F) + 9;
  36356. } else if (ch === 0x3E) { // '>'
  36357. this.eof = true;
  36358. break;
  36359. } else { // probably whitespace
  36360. continue; // ignoring
  36361. }
  36362. if (firstDigit < 0) {
  36363. firstDigit = digit;
  36364. } else {
  36365. buffer[bufferLength++] = (firstDigit << 4) | digit;
  36366. firstDigit = -1;
  36367. }
  36368. }
  36369. if (firstDigit >= 0 && this.eof) {
  36370. // incomplete byte
  36371. buffer[bufferLength++] = (firstDigit << 4);
  36372. firstDigit = -1;
  36373. }
  36374. this.firstDigit = firstDigit;
  36375. this.bufferLength = bufferLength;
  36376. };
  36377. return AsciiHexStream;
  36378. })();
  36379. var RunLengthStream = (function RunLengthStreamClosure() {
  36380. function RunLengthStream(str, maybeLength) {
  36381. this.str = str;
  36382. this.dict = str.dict;
  36383. DecodeStream.call(this, maybeLength);
  36384. }
  36385. RunLengthStream.prototype = Object.create(DecodeStream.prototype);
  36386. RunLengthStream.prototype.readBlock = function RunLengthStream_readBlock() {
  36387. // The repeatHeader has following format. The first byte defines type of run
  36388. // and amount of bytes to repeat/copy: n = 0 through 127 - copy next n bytes
  36389. // (in addition to the second byte from the header), n = 129 through 255 -
  36390. // duplicate the second byte from the header (257 - n) times, n = 128 - end.
  36391. var repeatHeader = this.str.getBytes(2);
  36392. if (!repeatHeader || repeatHeader.length < 2 || repeatHeader[0] === 128) {
  36393. this.eof = true;
  36394. return;
  36395. }
  36396. var buffer;
  36397. var bufferLength = this.bufferLength;
  36398. var n = repeatHeader[0];
  36399. if (n < 128) {
  36400. // copy n bytes
  36401. buffer = this.ensureBuffer(bufferLength + n + 1);
  36402. buffer[bufferLength++] = repeatHeader[1];
  36403. if (n > 0) {
  36404. var source = this.str.getBytes(n);
  36405. buffer.set(source, bufferLength);
  36406. bufferLength += n;
  36407. }
  36408. } else {
  36409. n = 257 - n;
  36410. var b = repeatHeader[1];
  36411. buffer = this.ensureBuffer(bufferLength + n + 1);
  36412. for (var i = 0; i < n; i++) {
  36413. buffer[bufferLength++] = b;
  36414. }
  36415. }
  36416. this.bufferLength = bufferLength;
  36417. };
  36418. return RunLengthStream;
  36419. })();
  36420. var CCITTFaxStream = (function CCITTFaxStreamClosure() {
  36421. var ccittEOL = -2;
  36422. var twoDimPass = 0;
  36423. var twoDimHoriz = 1;
  36424. var twoDimVert0 = 2;
  36425. var twoDimVertR1 = 3;
  36426. var twoDimVertL1 = 4;
  36427. var twoDimVertR2 = 5;
  36428. var twoDimVertL2 = 6;
  36429. var twoDimVertR3 = 7;
  36430. var twoDimVertL3 = 8;
  36431. var twoDimTable = [
  36432. [-1, -1], [-1, -1], // 000000x
  36433. [7, twoDimVertL3], // 0000010
  36434. [7, twoDimVertR3], // 0000011
  36435. [6, twoDimVertL2], [6, twoDimVertL2], // 000010x
  36436. [6, twoDimVertR2], [6, twoDimVertR2], // 000011x
  36437. [4, twoDimPass], [4, twoDimPass], // 0001xxx
  36438. [4, twoDimPass], [4, twoDimPass],
  36439. [4, twoDimPass], [4, twoDimPass],
  36440. [4, twoDimPass], [4, twoDimPass],
  36441. [3, twoDimHoriz], [3, twoDimHoriz], // 001xxxx
  36442. [3, twoDimHoriz], [3, twoDimHoriz],
  36443. [3, twoDimHoriz], [3, twoDimHoriz],
  36444. [3, twoDimHoriz], [3, twoDimHoriz],
  36445. [3, twoDimHoriz], [3, twoDimHoriz],
  36446. [3, twoDimHoriz], [3, twoDimHoriz],
  36447. [3, twoDimHoriz], [3, twoDimHoriz],
  36448. [3, twoDimHoriz], [3, twoDimHoriz],
  36449. [3, twoDimVertL1], [3, twoDimVertL1], // 010xxxx
  36450. [3, twoDimVertL1], [3, twoDimVertL1],
  36451. [3, twoDimVertL1], [3, twoDimVertL1],
  36452. [3, twoDimVertL1], [3, twoDimVertL1],
  36453. [3, twoDimVertL1], [3, twoDimVertL1],
  36454. [3, twoDimVertL1], [3, twoDimVertL1],
  36455. [3, twoDimVertL1], [3, twoDimVertL1],
  36456. [3, twoDimVertL1], [3, twoDimVertL1],
  36457. [3, twoDimVertR1], [3, twoDimVertR1], // 011xxxx
  36458. [3, twoDimVertR1], [3, twoDimVertR1],
  36459. [3, twoDimVertR1], [3, twoDimVertR1],
  36460. [3, twoDimVertR1], [3, twoDimVertR1],
  36461. [3, twoDimVertR1], [3, twoDimVertR1],
  36462. [3, twoDimVertR1], [3, twoDimVertR1],
  36463. [3, twoDimVertR1], [3, twoDimVertR1],
  36464. [3, twoDimVertR1], [3, twoDimVertR1],
  36465. [1, twoDimVert0], [1, twoDimVert0], // 1xxxxxx
  36466. [1, twoDimVert0], [1, twoDimVert0],
  36467. [1, twoDimVert0], [1, twoDimVert0],
  36468. [1, twoDimVert0], [1, twoDimVert0],
  36469. [1, twoDimVert0], [1, twoDimVert0],
  36470. [1, twoDimVert0], [1, twoDimVert0],
  36471. [1, twoDimVert0], [1, twoDimVert0],
  36472. [1, twoDimVert0], [1, twoDimVert0],
  36473. [1, twoDimVert0], [1, twoDimVert0],
  36474. [1, twoDimVert0], [1, twoDimVert0],
  36475. [1, twoDimVert0], [1, twoDimVert0],
  36476. [1, twoDimVert0], [1, twoDimVert0],
  36477. [1, twoDimVert0], [1, twoDimVert0],
  36478. [1, twoDimVert0], [1, twoDimVert0],
  36479. [1, twoDimVert0], [1, twoDimVert0],
  36480. [1, twoDimVert0], [1, twoDimVert0],
  36481. [1, twoDimVert0], [1, twoDimVert0],
  36482. [1, twoDimVert0], [1, twoDimVert0],
  36483. [1, twoDimVert0], [1, twoDimVert0],
  36484. [1, twoDimVert0], [1, twoDimVert0],
  36485. [1, twoDimVert0], [1, twoDimVert0],
  36486. [1, twoDimVert0], [1, twoDimVert0],
  36487. [1, twoDimVert0], [1, twoDimVert0],
  36488. [1, twoDimVert0], [1, twoDimVert0],
  36489. [1, twoDimVert0], [1, twoDimVert0],
  36490. [1, twoDimVert0], [1, twoDimVert0],
  36491. [1, twoDimVert0], [1, twoDimVert0],
  36492. [1, twoDimVert0], [1, twoDimVert0],
  36493. [1, twoDimVert0], [1, twoDimVert0],
  36494. [1, twoDimVert0], [1, twoDimVert0],
  36495. [1, twoDimVert0], [1, twoDimVert0],
  36496. [1, twoDimVert0], [1, twoDimVert0]
  36497. ];
  36498. var whiteTable1 = [
  36499. [-1, -1], // 00000
  36500. [12, ccittEOL], // 00001
  36501. [-1, -1], [-1, -1], // 0001x
  36502. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 001xx
  36503. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 010xx
  36504. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 011xx
  36505. [11, 1792], [11, 1792], // 1000x
  36506. [12, 1984], // 10010
  36507. [12, 2048], // 10011
  36508. [12, 2112], // 10100
  36509. [12, 2176], // 10101
  36510. [12, 2240], // 10110
  36511. [12, 2304], // 10111
  36512. [11, 1856], [11, 1856], // 1100x
  36513. [11, 1920], [11, 1920], // 1101x
  36514. [12, 2368], // 11100
  36515. [12, 2432], // 11101
  36516. [12, 2496], // 11110
  36517. [12, 2560] // 11111
  36518. ];
  36519. var whiteTable2 = [
  36520. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 0000000xx
  36521. [8, 29], [8, 29], // 00000010x
  36522. [8, 30], [8, 30], // 00000011x
  36523. [8, 45], [8, 45], // 00000100x
  36524. [8, 46], [8, 46], // 00000101x
  36525. [7, 22], [7, 22], [7, 22], [7, 22], // 0000011xx
  36526. [7, 23], [7, 23], [7, 23], [7, 23], // 0000100xx
  36527. [8, 47], [8, 47], // 00001010x
  36528. [8, 48], [8, 48], // 00001011x
  36529. [6, 13], [6, 13], [6, 13], [6, 13], // 000011xxx
  36530. [6, 13], [6, 13], [6, 13], [6, 13],
  36531. [7, 20], [7, 20], [7, 20], [7, 20], // 0001000xx
  36532. [8, 33], [8, 33], // 00010010x
  36533. [8, 34], [8, 34], // 00010011x
  36534. [8, 35], [8, 35], // 00010100x
  36535. [8, 36], [8, 36], // 00010101x
  36536. [8, 37], [8, 37], // 00010110x
  36537. [8, 38], [8, 38], // 00010111x
  36538. [7, 19], [7, 19], [7, 19], [7, 19], // 0001100xx
  36539. [8, 31], [8, 31], // 00011010x
  36540. [8, 32], [8, 32], // 00011011x
  36541. [6, 1], [6, 1], [6, 1], [6, 1], // 000111xxx
  36542. [6, 1], [6, 1], [6, 1], [6, 1],
  36543. [6, 12], [6, 12], [6, 12], [6, 12], // 001000xxx
  36544. [6, 12], [6, 12], [6, 12], [6, 12],
  36545. [8, 53], [8, 53], // 00100100x
  36546. [8, 54], [8, 54], // 00100101x
  36547. [7, 26], [7, 26], [7, 26], [7, 26], // 0010011xx
  36548. [8, 39], [8, 39], // 00101000x
  36549. [8, 40], [8, 40], // 00101001x
  36550. [8, 41], [8, 41], // 00101010x
  36551. [8, 42], [8, 42], // 00101011x
  36552. [8, 43], [8, 43], // 00101100x
  36553. [8, 44], [8, 44], // 00101101x
  36554. [7, 21], [7, 21], [7, 21], [7, 21], // 0010111xx
  36555. [7, 28], [7, 28], [7, 28], [7, 28], // 0011000xx
  36556. [8, 61], [8, 61], // 00110010x
  36557. [8, 62], [8, 62], // 00110011x
  36558. [8, 63], [8, 63], // 00110100x
  36559. [8, 0], [8, 0], // 00110101x
  36560. [8, 320], [8, 320], // 00110110x
  36561. [8, 384], [8, 384], // 00110111x
  36562. [5, 10], [5, 10], [5, 10], [5, 10], // 00111xxxx
  36563. [5, 10], [5, 10], [5, 10], [5, 10],
  36564. [5, 10], [5, 10], [5, 10], [5, 10],
  36565. [5, 10], [5, 10], [5, 10], [5, 10],
  36566. [5, 11], [5, 11], [5, 11], [5, 11], // 01000xxxx
  36567. [5, 11], [5, 11], [5, 11], [5, 11],
  36568. [5, 11], [5, 11], [5, 11], [5, 11],
  36569. [5, 11], [5, 11], [5, 11], [5, 11],
  36570. [7, 27], [7, 27], [7, 27], [7, 27], // 0100100xx
  36571. [8, 59], [8, 59], // 01001010x
  36572. [8, 60], [8, 60], // 01001011x
  36573. [9, 1472], // 010011000
  36574. [9, 1536], // 010011001
  36575. [9, 1600], // 010011010
  36576. [9, 1728], // 010011011
  36577. [7, 18], [7, 18], [7, 18], [7, 18], // 0100111xx
  36578. [7, 24], [7, 24], [7, 24], [7, 24], // 0101000xx
  36579. [8, 49], [8, 49], // 01010010x
  36580. [8, 50], [8, 50], // 01010011x
  36581. [8, 51], [8, 51], // 01010100x
  36582. [8, 52], [8, 52], // 01010101x
  36583. [7, 25], [7, 25], [7, 25], [7, 25], // 0101011xx
  36584. [8, 55], [8, 55], // 01011000x
  36585. [8, 56], [8, 56], // 01011001x
  36586. [8, 57], [8, 57], // 01011010x
  36587. [8, 58], [8, 58], // 01011011x
  36588. [6, 192], [6, 192], [6, 192], [6, 192], // 010111xxx
  36589. [6, 192], [6, 192], [6, 192], [6, 192],
  36590. [6, 1664], [6, 1664], [6, 1664], [6, 1664], // 011000xxx
  36591. [6, 1664], [6, 1664], [6, 1664], [6, 1664],
  36592. [8, 448], [8, 448], // 01100100x
  36593. [8, 512], [8, 512], // 01100101x
  36594. [9, 704], // 011001100
  36595. [9, 768], // 011001101
  36596. [8, 640], [8, 640], // 01100111x
  36597. [8, 576], [8, 576], // 01101000x
  36598. [9, 832], // 011010010
  36599. [9, 896], // 011010011
  36600. [9, 960], // 011010100
  36601. [9, 1024], // 011010101
  36602. [9, 1088], // 011010110
  36603. [9, 1152], // 011010111
  36604. [9, 1216], // 011011000
  36605. [9, 1280], // 011011001
  36606. [9, 1344], // 011011010
  36607. [9, 1408], // 011011011
  36608. [7, 256], [7, 256], [7, 256], [7, 256], // 0110111xx
  36609. [4, 2], [4, 2], [4, 2], [4, 2], // 0111xxxxx
  36610. [4, 2], [4, 2], [4, 2], [4, 2],
  36611. [4, 2], [4, 2], [4, 2], [4, 2],
  36612. [4, 2], [4, 2], [4, 2], [4, 2],
  36613. [4, 2], [4, 2], [4, 2], [4, 2],
  36614. [4, 2], [4, 2], [4, 2], [4, 2],
  36615. [4, 2], [4, 2], [4, 2], [4, 2],
  36616. [4, 2], [4, 2], [4, 2], [4, 2],
  36617. [4, 3], [4, 3], [4, 3], [4, 3], // 1000xxxxx
  36618. [4, 3], [4, 3], [4, 3], [4, 3],
  36619. [4, 3], [4, 3], [4, 3], [4, 3],
  36620. [4, 3], [4, 3], [4, 3], [4, 3],
  36621. [4, 3], [4, 3], [4, 3], [4, 3],
  36622. [4, 3], [4, 3], [4, 3], [4, 3],
  36623. [4, 3], [4, 3], [4, 3], [4, 3],
  36624. [4, 3], [4, 3], [4, 3], [4, 3],
  36625. [5, 128], [5, 128], [5, 128], [5, 128], // 10010xxxx
  36626. [5, 128], [5, 128], [5, 128], [5, 128],
  36627. [5, 128], [5, 128], [5, 128], [5, 128],
  36628. [5, 128], [5, 128], [5, 128], [5, 128],
  36629. [5, 8], [5, 8], [5, 8], [5, 8], // 10011xxxx
  36630. [5, 8], [5, 8], [5, 8], [5, 8],
  36631. [5, 8], [5, 8], [5, 8], [5, 8],
  36632. [5, 8], [5, 8], [5, 8], [5, 8],
  36633. [5, 9], [5, 9], [5, 9], [5, 9], // 10100xxxx
  36634. [5, 9], [5, 9], [5, 9], [5, 9],
  36635. [5, 9], [5, 9], [5, 9], [5, 9],
  36636. [5, 9], [5, 9], [5, 9], [5, 9],
  36637. [6, 16], [6, 16], [6, 16], [6, 16], // 101010xxx
  36638. [6, 16], [6, 16], [6, 16], [6, 16],
  36639. [6, 17], [6, 17], [6, 17], [6, 17], // 101011xxx
  36640. [6, 17], [6, 17], [6, 17], [6, 17],
  36641. [4, 4], [4, 4], [4, 4], [4, 4], // 1011xxxxx
  36642. [4, 4], [4, 4], [4, 4], [4, 4],
  36643. [4, 4], [4, 4], [4, 4], [4, 4],
  36644. [4, 4], [4, 4], [4, 4], [4, 4],
  36645. [4, 4], [4, 4], [4, 4], [4, 4],
  36646. [4, 4], [4, 4], [4, 4], [4, 4],
  36647. [4, 4], [4, 4], [4, 4], [4, 4],
  36648. [4, 4], [4, 4], [4, 4], [4, 4],
  36649. [4, 5], [4, 5], [4, 5], [4, 5], // 1100xxxxx
  36650. [4, 5], [4, 5], [4, 5], [4, 5],
  36651. [4, 5], [4, 5], [4, 5], [4, 5],
  36652. [4, 5], [4, 5], [4, 5], [4, 5],
  36653. [4, 5], [4, 5], [4, 5], [4, 5],
  36654. [4, 5], [4, 5], [4, 5], [4, 5],
  36655. [4, 5], [4, 5], [4, 5], [4, 5],
  36656. [4, 5], [4, 5], [4, 5], [4, 5],
  36657. [6, 14], [6, 14], [6, 14], [6, 14], // 110100xxx
  36658. [6, 14], [6, 14], [6, 14], [6, 14],
  36659. [6, 15], [6, 15], [6, 15], [6, 15], // 110101xxx
  36660. [6, 15], [6, 15], [6, 15], [6, 15],
  36661. [5, 64], [5, 64], [5, 64], [5, 64], // 11011xxxx
  36662. [5, 64], [5, 64], [5, 64], [5, 64],
  36663. [5, 64], [5, 64], [5, 64], [5, 64],
  36664. [5, 64], [5, 64], [5, 64], [5, 64],
  36665. [4, 6], [4, 6], [4, 6], [4, 6], // 1110xxxxx
  36666. [4, 6], [4, 6], [4, 6], [4, 6],
  36667. [4, 6], [4, 6], [4, 6], [4, 6],
  36668. [4, 6], [4, 6], [4, 6], [4, 6],
  36669. [4, 6], [4, 6], [4, 6], [4, 6],
  36670. [4, 6], [4, 6], [4, 6], [4, 6],
  36671. [4, 6], [4, 6], [4, 6], [4, 6],
  36672. [4, 6], [4, 6], [4, 6], [4, 6],
  36673. [4, 7], [4, 7], [4, 7], [4, 7], // 1111xxxxx
  36674. [4, 7], [4, 7], [4, 7], [4, 7],
  36675. [4, 7], [4, 7], [4, 7], [4, 7],
  36676. [4, 7], [4, 7], [4, 7], [4, 7],
  36677. [4, 7], [4, 7], [4, 7], [4, 7],
  36678. [4, 7], [4, 7], [4, 7], [4, 7],
  36679. [4, 7], [4, 7], [4, 7], [4, 7],
  36680. [4, 7], [4, 7], [4, 7], [4, 7]
  36681. ];
  36682. var blackTable1 = [
  36683. [-1, -1], [-1, -1], // 000000000000x
  36684. [12, ccittEOL], [12, ccittEOL], // 000000000001x
  36685. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000001xx
  36686. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000010xx
  36687. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000011xx
  36688. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000100xx
  36689. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000101xx
  36690. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000110xx
  36691. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000111xx
  36692. [11, 1792], [11, 1792], [11, 1792], [11, 1792], // 00000001000xx
  36693. [12, 1984], [12, 1984], // 000000010010x
  36694. [12, 2048], [12, 2048], // 000000010011x
  36695. [12, 2112], [12, 2112], // 000000010100x
  36696. [12, 2176], [12, 2176], // 000000010101x
  36697. [12, 2240], [12, 2240], // 000000010110x
  36698. [12, 2304], [12, 2304], // 000000010111x
  36699. [11, 1856], [11, 1856], [11, 1856], [11, 1856], // 00000001100xx
  36700. [11, 1920], [11, 1920], [11, 1920], [11, 1920], // 00000001101xx
  36701. [12, 2368], [12, 2368], // 000000011100x
  36702. [12, 2432], [12, 2432], // 000000011101x
  36703. [12, 2496], [12, 2496], // 000000011110x
  36704. [12, 2560], [12, 2560], // 000000011111x
  36705. [10, 18], [10, 18], [10, 18], [10, 18], // 0000001000xxx
  36706. [10, 18], [10, 18], [10, 18], [10, 18],
  36707. [12, 52], [12, 52], // 000000100100x
  36708. [13, 640], // 0000001001010
  36709. [13, 704], // 0000001001011
  36710. [13, 768], // 0000001001100
  36711. [13, 832], // 0000001001101
  36712. [12, 55], [12, 55], // 000000100111x
  36713. [12, 56], [12, 56], // 000000101000x
  36714. [13, 1280], // 0000001010010
  36715. [13, 1344], // 0000001010011
  36716. [13, 1408], // 0000001010100
  36717. [13, 1472], // 0000001010101
  36718. [12, 59], [12, 59], // 000000101011x
  36719. [12, 60], [12, 60], // 000000101100x
  36720. [13, 1536], // 0000001011010
  36721. [13, 1600], // 0000001011011
  36722. [11, 24], [11, 24], [11, 24], [11, 24], // 00000010111xx
  36723. [11, 25], [11, 25], [11, 25], [11, 25], // 00000011000xx
  36724. [13, 1664], // 0000001100100
  36725. [13, 1728], // 0000001100101
  36726. [12, 320], [12, 320], // 000000110011x
  36727. [12, 384], [12, 384], // 000000110100x
  36728. [12, 448], [12, 448], // 000000110101x
  36729. [13, 512], // 0000001101100
  36730. [13, 576], // 0000001101101
  36731. [12, 53], [12, 53], // 000000110111x
  36732. [12, 54], [12, 54], // 000000111000x
  36733. [13, 896], // 0000001110010
  36734. [13, 960], // 0000001110011
  36735. [13, 1024], // 0000001110100
  36736. [13, 1088], // 0000001110101
  36737. [13, 1152], // 0000001110110
  36738. [13, 1216], // 0000001110111
  36739. [10, 64], [10, 64], [10, 64], [10, 64], // 0000001111xxx
  36740. [10, 64], [10, 64], [10, 64], [10, 64]
  36741. ];
  36742. var blackTable2 = [
  36743. [8, 13], [8, 13], [8, 13], [8, 13], // 00000100xxxx
  36744. [8, 13], [8, 13], [8, 13], [8, 13],
  36745. [8, 13], [8, 13], [8, 13], [8, 13],
  36746. [8, 13], [8, 13], [8, 13], [8, 13],
  36747. [11, 23], [11, 23], // 00000101000x
  36748. [12, 50], // 000001010010
  36749. [12, 51], // 000001010011
  36750. [12, 44], // 000001010100
  36751. [12, 45], // 000001010101
  36752. [12, 46], // 000001010110
  36753. [12, 47], // 000001010111
  36754. [12, 57], // 000001011000
  36755. [12, 58], // 000001011001
  36756. [12, 61], // 000001011010
  36757. [12, 256], // 000001011011
  36758. [10, 16], [10, 16], [10, 16], [10, 16], // 0000010111xx
  36759. [10, 17], [10, 17], [10, 17], [10, 17], // 0000011000xx
  36760. [12, 48], // 000001100100
  36761. [12, 49], // 000001100101
  36762. [12, 62], // 000001100110
  36763. [12, 63], // 000001100111
  36764. [12, 30], // 000001101000
  36765. [12, 31], // 000001101001
  36766. [12, 32], // 000001101010
  36767. [12, 33], // 000001101011
  36768. [12, 40], // 000001101100
  36769. [12, 41], // 000001101101
  36770. [11, 22], [11, 22], // 00000110111x
  36771. [8, 14], [8, 14], [8, 14], [8, 14], // 00000111xxxx
  36772. [8, 14], [8, 14], [8, 14], [8, 14],
  36773. [8, 14], [8, 14], [8, 14], [8, 14],
  36774. [8, 14], [8, 14], [8, 14], [8, 14],
  36775. [7, 10], [7, 10], [7, 10], [7, 10], // 0000100xxxxx
  36776. [7, 10], [7, 10], [7, 10], [7, 10],
  36777. [7, 10], [7, 10], [7, 10], [7, 10],
  36778. [7, 10], [7, 10], [7, 10], [7, 10],
  36779. [7, 10], [7, 10], [7, 10], [7, 10],
  36780. [7, 10], [7, 10], [7, 10], [7, 10],
  36781. [7, 10], [7, 10], [7, 10], [7, 10],
  36782. [7, 10], [7, 10], [7, 10], [7, 10],
  36783. [7, 11], [7, 11], [7, 11], [7, 11], // 0000101xxxxx
  36784. [7, 11], [7, 11], [7, 11], [7, 11],
  36785. [7, 11], [7, 11], [7, 11], [7, 11],
  36786. [7, 11], [7, 11], [7, 11], [7, 11],
  36787. [7, 11], [7, 11], [7, 11], [7, 11],
  36788. [7, 11], [7, 11], [7, 11], [7, 11],
  36789. [7, 11], [7, 11], [7, 11], [7, 11],
  36790. [7, 11], [7, 11], [7, 11], [7, 11],
  36791. [9, 15], [9, 15], [9, 15], [9, 15], // 000011000xxx
  36792. [9, 15], [9, 15], [9, 15], [9, 15],
  36793. [12, 128], // 000011001000
  36794. [12, 192], // 000011001001
  36795. [12, 26], // 000011001010
  36796. [12, 27], // 000011001011
  36797. [12, 28], // 000011001100
  36798. [12, 29], // 000011001101
  36799. [11, 19], [11, 19], // 00001100111x
  36800. [11, 20], [11, 20], // 00001101000x
  36801. [12, 34], // 000011010010
  36802. [12, 35], // 000011010011
  36803. [12, 36], // 000011010100
  36804. [12, 37], // 000011010101
  36805. [12, 38], // 000011010110
  36806. [12, 39], // 000011010111
  36807. [11, 21], [11, 21], // 00001101100x
  36808. [12, 42], // 000011011010
  36809. [12, 43], // 000011011011
  36810. [10, 0], [10, 0], [10, 0], [10, 0], // 0000110111xx
  36811. [7, 12], [7, 12], [7, 12], [7, 12], // 0000111xxxxx
  36812. [7, 12], [7, 12], [7, 12], [7, 12],
  36813. [7, 12], [7, 12], [7, 12], [7, 12],
  36814. [7, 12], [7, 12], [7, 12], [7, 12],
  36815. [7, 12], [7, 12], [7, 12], [7, 12],
  36816. [7, 12], [7, 12], [7, 12], [7, 12],
  36817. [7, 12], [7, 12], [7, 12], [7, 12],
  36818. [7, 12], [7, 12], [7, 12], [7, 12]
  36819. ];
  36820. var blackTable3 = [
  36821. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 0000xx
  36822. [6, 9], // 000100
  36823. [6, 8], // 000101
  36824. [5, 7], [5, 7], // 00011x
  36825. [4, 6], [4, 6], [4, 6], [4, 6], // 0010xx
  36826. [4, 5], [4, 5], [4, 5], [4, 5], // 0011xx
  36827. [3, 1], [3, 1], [3, 1], [3, 1], // 010xxx
  36828. [3, 1], [3, 1], [3, 1], [3, 1],
  36829. [3, 4], [3, 4], [3, 4], [3, 4], // 011xxx
  36830. [3, 4], [3, 4], [3, 4], [3, 4],
  36831. [2, 3], [2, 3], [2, 3], [2, 3], // 10xxxx
  36832. [2, 3], [2, 3], [2, 3], [2, 3],
  36833. [2, 3], [2, 3], [2, 3], [2, 3],
  36834. [2, 3], [2, 3], [2, 3], [2, 3],
  36835. [2, 2], [2, 2], [2, 2], [2, 2], // 11xxxx
  36836. [2, 2], [2, 2], [2, 2], [2, 2],
  36837. [2, 2], [2, 2], [2, 2], [2, 2],
  36838. [2, 2], [2, 2], [2, 2], [2, 2]
  36839. ];
  36840. function CCITTFaxStream(str, maybeLength, params) {
  36841. this.str = str;
  36842. this.dict = str.dict;
  36843. params = params || Dict.empty;
  36844. this.encoding = params.get('K') || 0;
  36845. this.eoline = params.get('EndOfLine') || false;
  36846. this.byteAlign = params.get('EncodedByteAlign') || false;
  36847. this.columns = params.get('Columns') || 1728;
  36848. this.rows = params.get('Rows') || 0;
  36849. var eoblock = params.get('EndOfBlock');
  36850. if (eoblock === null || eoblock === undefined) {
  36851. eoblock = true;
  36852. }
  36853. this.eoblock = eoblock;
  36854. this.black = params.get('BlackIs1') || false;
  36855. this.codingLine = new Uint32Array(this.columns + 1);
  36856. this.refLine = new Uint32Array(this.columns + 2);
  36857. this.codingLine[0] = this.columns;
  36858. this.codingPos = 0;
  36859. this.row = 0;
  36860. this.nextLine2D = this.encoding < 0;
  36861. this.inputBits = 0;
  36862. this.inputBuf = 0;
  36863. this.outputBits = 0;
  36864. var code1;
  36865. while ((code1 = this.lookBits(12)) === 0) {
  36866. this.eatBits(1);
  36867. }
  36868. if (code1 === 1) {
  36869. this.eatBits(12);
  36870. }
  36871. if (this.encoding > 0) {
  36872. this.nextLine2D = !this.lookBits(1);
  36873. this.eatBits(1);
  36874. }
  36875. DecodeStream.call(this, maybeLength);
  36876. }
  36877. CCITTFaxStream.prototype = Object.create(DecodeStream.prototype);
  36878. CCITTFaxStream.prototype.readBlock = function CCITTFaxStream_readBlock() {
  36879. while (!this.eof) {
  36880. var c = this.lookChar();
  36881. this.ensureBuffer(this.bufferLength + 1);
  36882. this.buffer[this.bufferLength++] = c;
  36883. }
  36884. };
  36885. CCITTFaxStream.prototype.addPixels =
  36886. function ccittFaxStreamAddPixels(a1, blackPixels) {
  36887. var codingLine = this.codingLine;
  36888. var codingPos = this.codingPos;
  36889. if (a1 > codingLine[codingPos]) {
  36890. if (a1 > this.columns) {
  36891. info('row is wrong length');
  36892. this.err = true;
  36893. a1 = this.columns;
  36894. }
  36895. if ((codingPos & 1) ^ blackPixels) {
  36896. ++codingPos;
  36897. }
  36898. codingLine[codingPos] = a1;
  36899. }
  36900. this.codingPos = codingPos;
  36901. };
  36902. CCITTFaxStream.prototype.addPixelsNeg =
  36903. function ccittFaxStreamAddPixelsNeg(a1, blackPixels) {
  36904. var codingLine = this.codingLine;
  36905. var codingPos = this.codingPos;
  36906. if (a1 > codingLine[codingPos]) {
  36907. if (a1 > this.columns) {
  36908. info('row is wrong length');
  36909. this.err = true;
  36910. a1 = this.columns;
  36911. }
  36912. if ((codingPos & 1) ^ blackPixels) {
  36913. ++codingPos;
  36914. }
  36915. codingLine[codingPos] = a1;
  36916. } else if (a1 < codingLine[codingPos]) {
  36917. if (a1 < 0) {
  36918. info('invalid code');
  36919. this.err = true;
  36920. a1 = 0;
  36921. }
  36922. while (codingPos > 0 && a1 < codingLine[codingPos - 1]) {
  36923. --codingPos;
  36924. }
  36925. codingLine[codingPos] = a1;
  36926. }
  36927. this.codingPos = codingPos;
  36928. };
  36929. CCITTFaxStream.prototype.lookChar = function CCITTFaxStream_lookChar() {
  36930. var refLine = this.refLine;
  36931. var codingLine = this.codingLine;
  36932. var columns = this.columns;
  36933. var refPos, blackPixels, bits, i;
  36934. if (this.outputBits === 0) {
  36935. if (this.eof) {
  36936. return null;
  36937. }
  36938. this.err = false;
  36939. var code1, code2, code3;
  36940. if (this.nextLine2D) {
  36941. for (i = 0; codingLine[i] < columns; ++i) {
  36942. refLine[i] = codingLine[i];
  36943. }
  36944. refLine[i++] = columns;
  36945. refLine[i] = columns;
  36946. codingLine[0] = 0;
  36947. this.codingPos = 0;
  36948. refPos = 0;
  36949. blackPixels = 0;
  36950. while (codingLine[this.codingPos] < columns) {
  36951. code1 = this.getTwoDimCode();
  36952. switch (code1) {
  36953. case twoDimPass:
  36954. this.addPixels(refLine[refPos + 1], blackPixels);
  36955. if (refLine[refPos + 1] < columns) {
  36956. refPos += 2;
  36957. }
  36958. break;
  36959. case twoDimHoriz:
  36960. code1 = code2 = 0;
  36961. if (blackPixels) {
  36962. do {
  36963. code1 += (code3 = this.getBlackCode());
  36964. } while (code3 >= 64);
  36965. do {
  36966. code2 += (code3 = this.getWhiteCode());
  36967. } while (code3 >= 64);
  36968. } else {
  36969. do {
  36970. code1 += (code3 = this.getWhiteCode());
  36971. } while (code3 >= 64);
  36972. do {
  36973. code2 += (code3 = this.getBlackCode());
  36974. } while (code3 >= 64);
  36975. }
  36976. this.addPixels(codingLine[this.codingPos] +
  36977. code1, blackPixels);
  36978. if (codingLine[this.codingPos] < columns) {
  36979. this.addPixels(codingLine[this.codingPos] + code2,
  36980. blackPixels ^ 1);
  36981. }
  36982. while (refLine[refPos] <= codingLine[this.codingPos] &&
  36983. refLine[refPos] < columns) {
  36984. refPos += 2;
  36985. }
  36986. break;
  36987. case twoDimVertR3:
  36988. this.addPixels(refLine[refPos] + 3, blackPixels);
  36989. blackPixels ^= 1;
  36990. if (codingLine[this.codingPos] < columns) {
  36991. ++refPos;
  36992. while (refLine[refPos] <= codingLine[this.codingPos] &&
  36993. refLine[refPos] < columns) {
  36994. refPos += 2;
  36995. }
  36996. }
  36997. break;
  36998. case twoDimVertR2:
  36999. this.addPixels(refLine[refPos] + 2, blackPixels);
  37000. blackPixels ^= 1;
  37001. if (codingLine[this.codingPos] < columns) {
  37002. ++refPos;
  37003. while (refLine[refPos] <= codingLine[this.codingPos] &&
  37004. refLine[refPos] < columns) {
  37005. refPos += 2;
  37006. }
  37007. }
  37008. break;
  37009. case twoDimVertR1:
  37010. this.addPixels(refLine[refPos] + 1, blackPixels);
  37011. blackPixels ^= 1;
  37012. if (codingLine[this.codingPos] < columns) {
  37013. ++refPos;
  37014. while (refLine[refPos] <= codingLine[this.codingPos] &&
  37015. refLine[refPos] < columns) {
  37016. refPos += 2;
  37017. }
  37018. }
  37019. break;
  37020. case twoDimVert0:
  37021. this.addPixels(refLine[refPos], blackPixels);
  37022. blackPixels ^= 1;
  37023. if (codingLine[this.codingPos] < columns) {
  37024. ++refPos;
  37025. while (refLine[refPos] <= codingLine[this.codingPos] &&
  37026. refLine[refPos] < columns) {
  37027. refPos += 2;
  37028. }
  37029. }
  37030. break;
  37031. case twoDimVertL3:
  37032. this.addPixelsNeg(refLine[refPos] - 3, blackPixels);
  37033. blackPixels ^= 1;
  37034. if (codingLine[this.codingPos] < columns) {
  37035. if (refPos > 0) {
  37036. --refPos;
  37037. } else {
  37038. ++refPos;
  37039. }
  37040. while (refLine[refPos] <= codingLine[this.codingPos] &&
  37041. refLine[refPos] < columns) {
  37042. refPos += 2;
  37043. }
  37044. }
  37045. break;
  37046. case twoDimVertL2:
  37047. this.addPixelsNeg(refLine[refPos] - 2, blackPixels);
  37048. blackPixels ^= 1;
  37049. if (codingLine[this.codingPos] < columns) {
  37050. if (refPos > 0) {
  37051. --refPos;
  37052. } else {
  37053. ++refPos;
  37054. }
  37055. while (refLine[refPos] <= codingLine[this.codingPos] &&
  37056. refLine[refPos] < columns) {
  37057. refPos += 2;
  37058. }
  37059. }
  37060. break;
  37061. case twoDimVertL1:
  37062. this.addPixelsNeg(refLine[refPos] - 1, blackPixels);
  37063. blackPixels ^= 1;
  37064. if (codingLine[this.codingPos] < columns) {
  37065. if (refPos > 0) {
  37066. --refPos;
  37067. } else {
  37068. ++refPos;
  37069. }
  37070. while (refLine[refPos] <= codingLine[this.codingPos] &&
  37071. refLine[refPos] < columns) {
  37072. refPos += 2;
  37073. }
  37074. }
  37075. break;
  37076. case EOF:
  37077. this.addPixels(columns, 0);
  37078. this.eof = true;
  37079. break;
  37080. default:
  37081. info('bad 2d code');
  37082. this.addPixels(columns, 0);
  37083. this.err = true;
  37084. }
  37085. }
  37086. } else {
  37087. codingLine[0] = 0;
  37088. this.codingPos = 0;
  37089. blackPixels = 0;
  37090. while (codingLine[this.codingPos] < columns) {
  37091. code1 = 0;
  37092. if (blackPixels) {
  37093. do {
  37094. code1 += (code3 = this.getBlackCode());
  37095. } while (code3 >= 64);
  37096. } else {
  37097. do {
  37098. code1 += (code3 = this.getWhiteCode());
  37099. } while (code3 >= 64);
  37100. }
  37101. this.addPixels(codingLine[this.codingPos] + code1, blackPixels);
  37102. blackPixels ^= 1;
  37103. }
  37104. }
  37105. var gotEOL = false;
  37106. if (this.byteAlign) {
  37107. this.inputBits &= ~7;
  37108. }
  37109. if (!this.eoblock && this.row === this.rows - 1) {
  37110. this.eof = true;
  37111. } else {
  37112. code1 = this.lookBits(12);
  37113. if (this.eoline) {
  37114. while (code1 !== EOF && code1 !== 1) {
  37115. this.eatBits(1);
  37116. code1 = this.lookBits(12);
  37117. }
  37118. } else {
  37119. while (code1 === 0) {
  37120. this.eatBits(1);
  37121. code1 = this.lookBits(12);
  37122. }
  37123. }
  37124. if (code1 === 1) {
  37125. this.eatBits(12);
  37126. gotEOL = true;
  37127. } else if (code1 === EOF) {
  37128. this.eof = true;
  37129. }
  37130. }
  37131. if (!this.eof && this.encoding > 0) {
  37132. this.nextLine2D = !this.lookBits(1);
  37133. this.eatBits(1);
  37134. }
  37135. if (this.eoblock && gotEOL && this.byteAlign) {
  37136. code1 = this.lookBits(12);
  37137. if (code1 === 1) {
  37138. this.eatBits(12);
  37139. if (this.encoding > 0) {
  37140. this.lookBits(1);
  37141. this.eatBits(1);
  37142. }
  37143. if (this.encoding >= 0) {
  37144. for (i = 0; i < 4; ++i) {
  37145. code1 = this.lookBits(12);
  37146. if (code1 !== 1) {
  37147. info('bad rtc code: ' + code1);
  37148. }
  37149. this.eatBits(12);
  37150. if (this.encoding > 0) {
  37151. this.lookBits(1);
  37152. this.eatBits(1);
  37153. }
  37154. }
  37155. }
  37156. this.eof = true;
  37157. }
  37158. } else if (this.err && this.eoline) {
  37159. while (true) {
  37160. code1 = this.lookBits(13);
  37161. if (code1 === EOF) {
  37162. this.eof = true;
  37163. return null;
  37164. }
  37165. if ((code1 >> 1) === 1) {
  37166. break;
  37167. }
  37168. this.eatBits(1);
  37169. }
  37170. this.eatBits(12);
  37171. if (this.encoding > 0) {
  37172. this.eatBits(1);
  37173. this.nextLine2D = !(code1 & 1);
  37174. }
  37175. }
  37176. if (codingLine[0] > 0) {
  37177. this.outputBits = codingLine[this.codingPos = 0];
  37178. } else {
  37179. this.outputBits = codingLine[this.codingPos = 1];
  37180. }
  37181. this.row++;
  37182. }
  37183. var c;
  37184. if (this.outputBits >= 8) {
  37185. c = (this.codingPos & 1) ? 0 : 0xFF;
  37186. this.outputBits -= 8;
  37187. if (this.outputBits === 0 && codingLine[this.codingPos] < columns) {
  37188. this.codingPos++;
  37189. this.outputBits = (codingLine[this.codingPos] -
  37190. codingLine[this.codingPos - 1]);
  37191. }
  37192. } else {
  37193. bits = 8;
  37194. c = 0;
  37195. do {
  37196. if (this.outputBits > bits) {
  37197. c <<= bits;
  37198. if (!(this.codingPos & 1)) {
  37199. c |= 0xFF >> (8 - bits);
  37200. }
  37201. this.outputBits -= bits;
  37202. bits = 0;
  37203. } else {
  37204. c <<= this.outputBits;
  37205. if (!(this.codingPos & 1)) {
  37206. c |= 0xFF >> (8 - this.outputBits);
  37207. }
  37208. bits -= this.outputBits;
  37209. this.outputBits = 0;
  37210. if (codingLine[this.codingPos] < columns) {
  37211. this.codingPos++;
  37212. this.outputBits = (codingLine[this.codingPos] -
  37213. codingLine[this.codingPos - 1]);
  37214. } else if (bits > 0) {
  37215. c <<= bits;
  37216. bits = 0;
  37217. }
  37218. }
  37219. } while (bits);
  37220. }
  37221. if (this.black) {
  37222. c ^= 0xFF;
  37223. }
  37224. return c;
  37225. };
  37226. // This functions returns the code found from the table.
  37227. // The start and end parameters set the boundaries for searching the table.
  37228. // The limit parameter is optional. Function returns an array with three
  37229. // values. The first array element indicates whether a valid code is being
  37230. // returned. The second array element is the actual code. The third array
  37231. // element indicates whether EOF was reached.
  37232. CCITTFaxStream.prototype.findTableCode =
  37233. function ccittFaxStreamFindTableCode(start, end, table, limit) {
  37234. var limitValue = limit || 0;
  37235. for (var i = start; i <= end; ++i) {
  37236. var code = this.lookBits(i);
  37237. if (code === EOF) {
  37238. return [true, 1, false];
  37239. }
  37240. if (i < end) {
  37241. code <<= end - i;
  37242. }
  37243. if (!limitValue || code >= limitValue) {
  37244. var p = table[code - limitValue];
  37245. if (p[0] === i) {
  37246. this.eatBits(i);
  37247. return [true, p[1], true];
  37248. }
  37249. }
  37250. }
  37251. return [false, 0, false];
  37252. };
  37253. CCITTFaxStream.prototype.getTwoDimCode =
  37254. function ccittFaxStreamGetTwoDimCode() {
  37255. var code = 0;
  37256. var p;
  37257. if (this.eoblock) {
  37258. code = this.lookBits(7);
  37259. p = twoDimTable[code];
  37260. if (p && p[0] > 0) {
  37261. this.eatBits(p[0]);
  37262. return p[1];
  37263. }
  37264. } else {
  37265. var result = this.findTableCode(1, 7, twoDimTable);
  37266. if (result[0] && result[2]) {
  37267. return result[1];
  37268. }
  37269. }
  37270. info('Bad two dim code');
  37271. return EOF;
  37272. };
  37273. CCITTFaxStream.prototype.getWhiteCode =
  37274. function ccittFaxStreamGetWhiteCode() {
  37275. var code = 0;
  37276. var p;
  37277. if (this.eoblock) {
  37278. code = this.lookBits(12);
  37279. if (code === EOF) {
  37280. return 1;
  37281. }
  37282. if ((code >> 5) === 0) {
  37283. p = whiteTable1[code];
  37284. } else {
  37285. p = whiteTable2[code >> 3];
  37286. }
  37287. if (p[0] > 0) {
  37288. this.eatBits(p[0]);
  37289. return p[1];
  37290. }
  37291. } else {
  37292. var result = this.findTableCode(1, 9, whiteTable2);
  37293. if (result[0]) {
  37294. return result[1];
  37295. }
  37296. result = this.findTableCode(11, 12, whiteTable1);
  37297. if (result[0]) {
  37298. return result[1];
  37299. }
  37300. }
  37301. info('bad white code');
  37302. this.eatBits(1);
  37303. return 1;
  37304. };
  37305. CCITTFaxStream.prototype.getBlackCode =
  37306. function ccittFaxStreamGetBlackCode() {
  37307. var code, p;
  37308. if (this.eoblock) {
  37309. code = this.lookBits(13);
  37310. if (code === EOF) {
  37311. return 1;
  37312. }
  37313. if ((code >> 7) === 0) {
  37314. p = blackTable1[code];
  37315. } else if ((code >> 9) === 0 && (code >> 7) !== 0) {
  37316. p = blackTable2[(code >> 1) - 64];
  37317. } else {
  37318. p = blackTable3[code >> 7];
  37319. }
  37320. if (p[0] > 0) {
  37321. this.eatBits(p[0]);
  37322. return p[1];
  37323. }
  37324. } else {
  37325. var result = this.findTableCode(2, 6, blackTable3);
  37326. if (result[0]) {
  37327. return result[1];
  37328. }
  37329. result = this.findTableCode(7, 12, blackTable2, 64);
  37330. if (result[0]) {
  37331. return result[1];
  37332. }
  37333. result = this.findTableCode(10, 13, blackTable1);
  37334. if (result[0]) {
  37335. return result[1];
  37336. }
  37337. }
  37338. info('bad black code');
  37339. this.eatBits(1);
  37340. return 1;
  37341. };
  37342. CCITTFaxStream.prototype.lookBits = function CCITTFaxStream_lookBits(n) {
  37343. var c;
  37344. while (this.inputBits < n) {
  37345. if ((c = this.str.getByte()) === -1) {
  37346. if (this.inputBits === 0) {
  37347. return EOF;
  37348. }
  37349. return ((this.inputBuf << (n - this.inputBits)) &
  37350. (0xFFFF >> (16 - n)));
  37351. }
  37352. this.inputBuf = (this.inputBuf << 8) + c;
  37353. this.inputBits += 8;
  37354. }
  37355. return (this.inputBuf >> (this.inputBits - n)) & (0xFFFF >> (16 - n));
  37356. };
  37357. CCITTFaxStream.prototype.eatBits = function CCITTFaxStream_eatBits(n) {
  37358. if ((this.inputBits -= n) < 0) {
  37359. this.inputBits = 0;
  37360. }
  37361. };
  37362. return CCITTFaxStream;
  37363. })();
  37364. var LZWStream = (function LZWStreamClosure() {
  37365. function LZWStream(str, maybeLength, earlyChange) {
  37366. this.str = str;
  37367. this.dict = str.dict;
  37368. this.cachedData = 0;
  37369. this.bitsCached = 0;
  37370. var maxLzwDictionarySize = 4096;
  37371. var lzwState = {
  37372. earlyChange: earlyChange,
  37373. codeLength: 9,
  37374. nextCode: 258,
  37375. dictionaryValues: new Uint8Array(maxLzwDictionarySize),
  37376. dictionaryLengths: new Uint16Array(maxLzwDictionarySize),
  37377. dictionaryPrevCodes: new Uint16Array(maxLzwDictionarySize),
  37378. currentSequence: new Uint8Array(maxLzwDictionarySize),
  37379. currentSequenceLength: 0
  37380. };
  37381. for (var i = 0; i < 256; ++i) {
  37382. lzwState.dictionaryValues[i] = i;
  37383. lzwState.dictionaryLengths[i] = 1;
  37384. }
  37385. this.lzwState = lzwState;
  37386. DecodeStream.call(this, maybeLength);
  37387. }
  37388. LZWStream.prototype = Object.create(DecodeStream.prototype);
  37389. LZWStream.prototype.readBits = function LZWStream_readBits(n) {
  37390. var bitsCached = this.bitsCached;
  37391. var cachedData = this.cachedData;
  37392. while (bitsCached < n) {
  37393. var c = this.str.getByte();
  37394. if (c === -1) {
  37395. this.eof = true;
  37396. return null;
  37397. }
  37398. cachedData = (cachedData << 8) | c;
  37399. bitsCached += 8;
  37400. }
  37401. this.bitsCached = (bitsCached -= n);
  37402. this.cachedData = cachedData;
  37403. this.lastCode = null;
  37404. return (cachedData >>> bitsCached) & ((1 << n) - 1);
  37405. };
  37406. LZWStream.prototype.readBlock = function LZWStream_readBlock() {
  37407. var blockSize = 512;
  37408. var estimatedDecodedSize = blockSize * 2, decodedSizeDelta = blockSize;
  37409. var i, j, q;
  37410. var lzwState = this.lzwState;
  37411. if (!lzwState) {
  37412. return; // eof was found
  37413. }
  37414. var earlyChange = lzwState.earlyChange;
  37415. var nextCode = lzwState.nextCode;
  37416. var dictionaryValues = lzwState.dictionaryValues;
  37417. var dictionaryLengths = lzwState.dictionaryLengths;
  37418. var dictionaryPrevCodes = lzwState.dictionaryPrevCodes;
  37419. var codeLength = lzwState.codeLength;
  37420. var prevCode = lzwState.prevCode;
  37421. var currentSequence = lzwState.currentSequence;
  37422. var currentSequenceLength = lzwState.currentSequenceLength;
  37423. var decodedLength = 0;
  37424. var currentBufferLength = this.bufferLength;
  37425. var buffer = this.ensureBuffer(this.bufferLength + estimatedDecodedSize);
  37426. for (i = 0; i < blockSize; i++) {
  37427. var code = this.readBits(codeLength);
  37428. var hasPrev = currentSequenceLength > 0;
  37429. if (code < 256) {
  37430. currentSequence[0] = code;
  37431. currentSequenceLength = 1;
  37432. } else if (code >= 258) {
  37433. if (code < nextCode) {
  37434. currentSequenceLength = dictionaryLengths[code];
  37435. for (j = currentSequenceLength - 1, q = code; j >= 0; j--) {
  37436. currentSequence[j] = dictionaryValues[q];
  37437. q = dictionaryPrevCodes[q];
  37438. }
  37439. } else {
  37440. currentSequence[currentSequenceLength++] = currentSequence[0];
  37441. }
  37442. } else if (code === 256) {
  37443. codeLength = 9;
  37444. nextCode = 258;
  37445. currentSequenceLength = 0;
  37446. continue;
  37447. } else {
  37448. this.eof = true;
  37449. delete this.lzwState;
  37450. break;
  37451. }
  37452. if (hasPrev) {
  37453. dictionaryPrevCodes[nextCode] = prevCode;
  37454. dictionaryLengths[nextCode] = dictionaryLengths[prevCode] + 1;
  37455. dictionaryValues[nextCode] = currentSequence[0];
  37456. nextCode++;
  37457. codeLength = (nextCode + earlyChange) & (nextCode + earlyChange - 1) ?
  37458. codeLength : Math.min(Math.log(nextCode + earlyChange) /
  37459. 0.6931471805599453 + 1, 12) | 0;
  37460. }
  37461. prevCode = code;
  37462. decodedLength += currentSequenceLength;
  37463. if (estimatedDecodedSize < decodedLength) {
  37464. do {
  37465. estimatedDecodedSize += decodedSizeDelta;
  37466. } while (estimatedDecodedSize < decodedLength);
  37467. buffer = this.ensureBuffer(this.bufferLength + estimatedDecodedSize);
  37468. }
  37469. for (j = 0; j < currentSequenceLength; j++) {
  37470. buffer[currentBufferLength++] = currentSequence[j];
  37471. }
  37472. }
  37473. lzwState.nextCode = nextCode;
  37474. lzwState.codeLength = codeLength;
  37475. lzwState.prevCode = prevCode;
  37476. lzwState.currentSequenceLength = currentSequenceLength;
  37477. this.bufferLength = currentBufferLength;
  37478. };
  37479. return LZWStream;
  37480. })();
  37481. var NullStream = (function NullStreamClosure() {
  37482. function NullStream() {
  37483. Stream.call(this, new Uint8Array(0));
  37484. }
  37485. NullStream.prototype = Stream.prototype;
  37486. return NullStream;
  37487. })();
  37488. var WorkerMessageHandler = PDFJS.WorkerMessageHandler = {
  37489. setup: function wphSetup(handler) {
  37490. var pdfManager;
  37491. function loadDocument(recoveryMode) {
  37492. var loadDocumentCapability = createPromiseCapability();
  37493. var parseSuccess = function parseSuccess() {
  37494. var numPagesPromise = pdfManager.ensureDoc('numPages');
  37495. var fingerprintPromise = pdfManager.ensureDoc('fingerprint');
  37496. var encryptedPromise = pdfManager.ensureXRef('encrypt');
  37497. Promise.all([numPagesPromise, fingerprintPromise,
  37498. encryptedPromise]).then(function onDocReady(results) {
  37499. var doc = {
  37500. numPages: results[0],
  37501. fingerprint: results[1],
  37502. encrypted: !!results[2],
  37503. };
  37504. loadDocumentCapability.resolve(doc);
  37505. },
  37506. parseFailure);
  37507. };
  37508. var parseFailure = function parseFailure(e) {
  37509. loadDocumentCapability.reject(e);
  37510. };
  37511. pdfManager.ensureDoc('checkHeader', []).then(function() {
  37512. pdfManager.ensureDoc('parseStartXRef', []).then(function() {
  37513. pdfManager.ensureDoc('parse', [recoveryMode]).then(
  37514. parseSuccess, parseFailure);
  37515. }, parseFailure);
  37516. }, parseFailure);
  37517. return loadDocumentCapability.promise;
  37518. }
  37519. function getPdfManager(data) {
  37520. var pdfManagerCapability = createPromiseCapability();
  37521. var source = data.source;
  37522. var disableRange = data.disableRange;
  37523. if (source.data) {
  37524. try {
  37525. pdfManager = new LocalPdfManager(source.data, source.password);
  37526. pdfManagerCapability.resolve();
  37527. } catch (ex) {
  37528. pdfManagerCapability.reject(ex);
  37529. }
  37530. return pdfManagerCapability.promise;
  37531. } else if (source.chunkedViewerLoading) {
  37532. try {
  37533. pdfManager = new NetworkPdfManager(source, handler);
  37534. pdfManagerCapability.resolve();
  37535. } catch (ex) {
  37536. pdfManagerCapability.reject(ex);
  37537. }
  37538. return pdfManagerCapability.promise;
  37539. }
  37540. var networkManager = new NetworkManager(source.url, {
  37541. httpHeaders: source.httpHeaders,
  37542. withCredentials: source.withCredentials
  37543. });
  37544. var cachedChunks = [];
  37545. var fullRequestXhrId = networkManager.requestFull({
  37546. onHeadersReceived: function onHeadersReceived() {
  37547. if (disableRange) {
  37548. return;
  37549. }
  37550. var fullRequestXhr = networkManager.getRequestXhr(fullRequestXhrId);
  37551. if (fullRequestXhr.getResponseHeader('Accept-Ranges') !== 'bytes') {
  37552. return;
  37553. }
  37554. var contentEncoding =
  37555. fullRequestXhr.getResponseHeader('Content-Encoding') || 'identity';
  37556. if (contentEncoding !== 'identity') {
  37557. return;
  37558. }
  37559. var length = fullRequestXhr.getResponseHeader('Content-Length');
  37560. length = parseInt(length, 10);
  37561. if (!isInt(length)) {
  37562. return;
  37563. }
  37564. source.length = length;
  37565. if (length <= 2 * RANGE_CHUNK_SIZE) {
  37566. // The file size is smaller than the size of two chunks, so it does
  37567. // not make any sense to abort the request and retry with a range
  37568. // request.
  37569. return;
  37570. }
  37571. if (networkManager.isStreamingRequest(fullRequestXhrId)) {
  37572. // We can continue fetching when progressive loading is enabled,
  37573. // and we don't need the autoFetch feature.
  37574. source.disableAutoFetch = true;
  37575. } else {
  37576. // NOTE: by cancelling the full request, and then issuing range
  37577. // requests, there will be an issue for sites where you can only
  37578. // request the pdf once. However, if this is the case, then the
  37579. // server should not be returning that it can support range
  37580. // requests.
  37581. networkManager.abortRequest(fullRequestXhrId);
  37582. }
  37583. try {
  37584. pdfManager = new NetworkPdfManager(source, handler);
  37585. pdfManagerCapability.resolve(pdfManager);
  37586. } catch (ex) {
  37587. pdfManagerCapability.reject(ex);
  37588. }
  37589. },
  37590. onProgressiveData: source.disableStream ? null :
  37591. function onProgressiveData(chunk) {
  37592. if (!pdfManager) {
  37593. cachedChunks.push(chunk);
  37594. return;
  37595. }
  37596. pdfManager.sendProgressiveData(chunk);
  37597. },
  37598. onDone: function onDone(args) {
  37599. if (pdfManager) {
  37600. return; // already processed
  37601. }
  37602. var pdfFile;
  37603. if (args === null) {
  37604. // TODO add some streaming manager, e.g. for unknown length files.
  37605. // The data was returned in the onProgressiveData, combining...
  37606. var pdfFileLength = 0, pos = 0;
  37607. cachedChunks.forEach(function (chunk) {
  37608. pdfFileLength += chunk.byteLength;
  37609. });
  37610. if (source.length && pdfFileLength !== source.length) {
  37611. warn('reported HTTP length is different from actual');
  37612. }
  37613. var pdfFileArray = new Uint8Array(pdfFileLength);
  37614. cachedChunks.forEach(function (chunk) {
  37615. pdfFileArray.set(new Uint8Array(chunk), pos);
  37616. pos += chunk.byteLength;
  37617. });
  37618. pdfFile = pdfFileArray.buffer;
  37619. } else {
  37620. pdfFile = args.chunk;
  37621. }
  37622. // the data is array, instantiating directly from it
  37623. try {
  37624. pdfManager = new LocalPdfManager(pdfFile, source.password);
  37625. pdfManagerCapability.resolve();
  37626. } catch (ex) {
  37627. pdfManagerCapability.reject(ex);
  37628. }
  37629. },
  37630. onError: function onError(status) {
  37631. var exception;
  37632. if (status === 404) {
  37633. exception = new MissingPDFException('Missing PDF "' +
  37634. source.url + '".');
  37635. handler.send('MissingPDF', exception);
  37636. } else {
  37637. exception = new UnexpectedResponseException(
  37638. 'Unexpected server response (' + status +
  37639. ') while retrieving PDF "' + source.url + '".', status);
  37640. handler.send('UnexpectedResponse', exception);
  37641. }
  37642. },
  37643. onProgress: function onProgress(evt) {
  37644. handler.send('DocProgress', {
  37645. loaded: evt.loaded,
  37646. total: evt.lengthComputable ? evt.total : source.length
  37647. });
  37648. }
  37649. });
  37650. return pdfManagerCapability.promise;
  37651. }
  37652. handler.on('test', function wphSetupTest(data) {
  37653. // check if Uint8Array can be sent to worker
  37654. if (!(data instanceof Uint8Array)) {
  37655. handler.send('test', false);
  37656. return;
  37657. }
  37658. // making sure postMessage transfers are working
  37659. var supportTransfers = data[0] === 255;
  37660. handler.postMessageTransfers = supportTransfers;
  37661. // check if the response property is supported by xhr
  37662. var xhr = new XMLHttpRequest();
  37663. var responseExists = 'response' in xhr;
  37664. // check if the property is actually implemented
  37665. try {
  37666. var dummy = xhr.responseType;
  37667. } catch (e) {
  37668. responseExists = false;
  37669. }
  37670. if (!responseExists) {
  37671. handler.send('test', false);
  37672. return;
  37673. }
  37674. handler.send('test', {
  37675. supportTypedArray: true,
  37676. supportTransfers: supportTransfers
  37677. });
  37678. });
  37679. handler.on('GetDocRequest', function wphSetupDoc(data) {
  37680. var onSuccess = function(doc) {
  37681. handler.send('GetDoc', { pdfInfo: doc });
  37682. };
  37683. var onFailure = function(e) {
  37684. if (e instanceof PasswordException) {
  37685. if (e.code === PasswordResponses.NEED_PASSWORD) {
  37686. handler.send('NeedPassword', e);
  37687. } else if (e.code === PasswordResponses.INCORRECT_PASSWORD) {
  37688. handler.send('IncorrectPassword', e);
  37689. }
  37690. } else if (e instanceof InvalidPDFException) {
  37691. handler.send('InvalidPDF', e);
  37692. } else if (e instanceof MissingPDFException) {
  37693. handler.send('MissingPDF', e);
  37694. } else if (e instanceof UnexpectedResponseException) {
  37695. handler.send('UnexpectedResponse', e);
  37696. } else {
  37697. handler.send('UnknownError',
  37698. new UnknownErrorException(e.message, e.toString()));
  37699. }
  37700. };
  37701. PDFJS.maxImageSize = data.maxImageSize === undefined ?
  37702. -1 : data.maxImageSize;
  37703. PDFJS.disableFontFace = data.disableFontFace;
  37704. PDFJS.disableCreateObjectURL = data.disableCreateObjectURL;
  37705. PDFJS.verbosity = data.verbosity;
  37706. PDFJS.cMapUrl = data.cMapUrl === undefined ?
  37707. null : data.cMapUrl;
  37708. PDFJS.cMapPacked = data.cMapPacked === true;
  37709. getPdfManager(data).then(function () {
  37710. handler.send('PDFManagerReady', null);
  37711. pdfManager.onLoadedStream().then(function(stream) {
  37712. handler.send('DataLoaded', { length: stream.bytes.byteLength });
  37713. });
  37714. }).then(function pdfManagerReady() {
  37715. loadDocument(false).then(onSuccess, function loadFailure(ex) {
  37716. // Try again with recoveryMode == true
  37717. if (!(ex instanceof XRefParseException)) {
  37718. if (ex instanceof PasswordException) {
  37719. // after password exception prepare to receive a new password
  37720. // to repeat loading
  37721. pdfManager.passwordChanged().then(pdfManagerReady);
  37722. }
  37723. onFailure(ex);
  37724. return;
  37725. }
  37726. pdfManager.requestLoadedStream();
  37727. pdfManager.onLoadedStream().then(function() {
  37728. loadDocument(true).then(onSuccess, onFailure);
  37729. });
  37730. }, onFailure);
  37731. }, onFailure);
  37732. });
  37733. handler.on('GetPage', function wphSetupGetPage(data) {
  37734. return pdfManager.getPage(data.pageIndex).then(function(page) {
  37735. var rotatePromise = pdfManager.ensure(page, 'rotate');
  37736. var refPromise = pdfManager.ensure(page, 'ref');
  37737. var viewPromise = pdfManager.ensure(page, 'view');
  37738. return Promise.all([rotatePromise, refPromise, viewPromise]).then(
  37739. function(results) {
  37740. return {
  37741. rotate: results[0],
  37742. ref: results[1],
  37743. view: results[2]
  37744. };
  37745. });
  37746. });
  37747. });
  37748. handler.on('GetPageIndex', function wphSetupGetPageIndex(data) {
  37749. var ref = new Ref(data.ref.num, data.ref.gen);
  37750. var catalog = pdfManager.pdfDocument.catalog;
  37751. return catalog.getPageIndex(ref);
  37752. });
  37753. handler.on('GetDestinations',
  37754. function wphSetupGetDestinations(data) {
  37755. return pdfManager.ensureCatalog('destinations');
  37756. }
  37757. );
  37758. handler.on('GetDestination',
  37759. function wphSetupGetDestination(data) {
  37760. return pdfManager.ensureCatalog('getDestination', [ data.id ]);
  37761. }
  37762. );
  37763. handler.on('GetAttachments',
  37764. function wphSetupGetAttachments(data) {
  37765. return pdfManager.ensureCatalog('attachments');
  37766. }
  37767. );
  37768. handler.on('GetJavaScript',
  37769. function wphSetupGetJavaScript(data) {
  37770. return pdfManager.ensureCatalog('javaScript');
  37771. }
  37772. );
  37773. handler.on('GetOutline',
  37774. function wphSetupGetOutline(data) {
  37775. return pdfManager.ensureCatalog('documentOutline');
  37776. }
  37777. );
  37778. handler.on('GetMetadata',
  37779. function wphSetupGetMetadata(data) {
  37780. return Promise.all([pdfManager.ensureDoc('documentInfo'),
  37781. pdfManager.ensureCatalog('metadata')]);
  37782. }
  37783. );
  37784. handler.on('GetData', function wphSetupGetData(data) {
  37785. pdfManager.requestLoadedStream();
  37786. return pdfManager.onLoadedStream().then(function(stream) {
  37787. return stream.bytes;
  37788. });
  37789. });
  37790. handler.on('GetStats',
  37791. function wphSetupGetStats(data) {
  37792. return pdfManager.pdfDocument.xref.stats;
  37793. }
  37794. );
  37795. handler.on('UpdatePassword', function wphSetupUpdatePassword(data) {
  37796. pdfManager.updatePassword(data);
  37797. });
  37798. handler.on('GetAnnotations', function wphSetupGetAnnotations(data) {
  37799. return pdfManager.getPage(data.pageIndex).then(function(page) {
  37800. return pdfManager.ensure(page, 'getAnnotationsData', []);
  37801. });
  37802. });
  37803. handler.on('RenderPageRequest', function wphSetupRenderPage(data) {
  37804. pdfManager.getPage(data.pageIndex).then(function(page) {
  37805. var pageNum = data.pageIndex + 1;
  37806. var start = Date.now();
  37807. // Pre compile the pdf page and fetch the fonts/images.
  37808. page.getOperatorList(handler, data.intent).then(function(operatorList) {
  37809. info('page=' + pageNum + ' - getOperatorList: time=' +
  37810. (Date.now() - start) + 'ms, len=' + operatorList.fnArray.length);
  37811. }, function(e) {
  37812. var minimumStackMessage =
  37813. 'worker.js: while trying to getPage() and getOperatorList()';
  37814. var wrappedException;
  37815. // Turn the error into an obj that can be serialized
  37816. if (typeof e === 'string') {
  37817. wrappedException = {
  37818. message: e,
  37819. stack: minimumStackMessage
  37820. };
  37821. } else if (typeof e === 'object') {
  37822. wrappedException = {
  37823. message: e.message || e.toString(),
  37824. stack: e.stack || minimumStackMessage
  37825. };
  37826. } else {
  37827. wrappedException = {
  37828. message: 'Unknown exception type: ' + (typeof e),
  37829. stack: minimumStackMessage
  37830. };
  37831. }
  37832. handler.send('PageError', {
  37833. pageNum: pageNum,
  37834. error: wrappedException,
  37835. intent: data.intent
  37836. });
  37837. });
  37838. });
  37839. }, this);
  37840. handler.on('GetTextContent', function wphExtractText(data) {
  37841. return pdfManager.getPage(data.pageIndex).then(function(page) {
  37842. var pageNum = data.pageIndex + 1;
  37843. var start = Date.now();
  37844. return page.extractTextContent().then(function(textContent) {
  37845. info('text indexing: page=' + pageNum + ' - time=' +
  37846. (Date.now() - start) + 'ms');
  37847. return textContent;
  37848. });
  37849. });
  37850. });
  37851. handler.on('Cleanup', function wphCleanup(data) {
  37852. return pdfManager.cleanup();
  37853. });
  37854. handler.on('Terminate', function wphTerminate(data) {
  37855. pdfManager.terminate();
  37856. });
  37857. }
  37858. };
  37859. var consoleTimer = {};
  37860. var workerConsole = {
  37861. log: function log() {
  37862. var args = Array.prototype.slice.call(arguments);
  37863. globalScope.postMessage({
  37864. action: 'console_log',
  37865. data: args
  37866. });
  37867. },
  37868. error: function error() {
  37869. var args = Array.prototype.slice.call(arguments);
  37870. globalScope.postMessage({
  37871. action: 'console_error',
  37872. data: args
  37873. });
  37874. throw 'pdf.js execution error';
  37875. },
  37876. time: function time(name) {
  37877. consoleTimer[name] = Date.now();
  37878. },
  37879. timeEnd: function timeEnd(name) {
  37880. var time = consoleTimer[name];
  37881. if (!time) {
  37882. error('Unknown timer name ' + name);
  37883. }
  37884. this.log('Timer:', name, Date.now() - time);
  37885. }
  37886. };
  37887. // Worker thread?
  37888. if (typeof window === 'undefined') {
  37889. if (!('console' in globalScope)) {
  37890. globalScope.console = workerConsole;
  37891. }
  37892. // Listen for unsupported features so we can pass them on to the main thread.
  37893. PDFJS.UnsupportedManager.listen(function (msg) {
  37894. globalScope.postMessage({
  37895. action: '_unsupported_feature',
  37896. data: msg
  37897. });
  37898. });
  37899. var handler = new MessageHandler('worker_processor', this);
  37900. WorkerMessageHandler.setup(handler);
  37901. }
  37902. /* This class implements the QM Coder decoding as defined in
  37903. * JPEG 2000 Part I Final Committee Draft Version 1.0
  37904. * Annex C.3 Arithmetic decoding procedure
  37905. * available at http://www.jpeg.org/public/fcd15444-1.pdf
  37906. *
  37907. * The arithmetic decoder is used in conjunction with context models to decode
  37908. * JPEG2000 and JBIG2 streams.
  37909. */
  37910. var ArithmeticDecoder = (function ArithmeticDecoderClosure() {
  37911. // Table C-2
  37912. var QeTable = [
  37913. {qe: 0x5601, nmps: 1, nlps: 1, switchFlag: 1},
  37914. {qe: 0x3401, nmps: 2, nlps: 6, switchFlag: 0},
  37915. {qe: 0x1801, nmps: 3, nlps: 9, switchFlag: 0},
  37916. {qe: 0x0AC1, nmps: 4, nlps: 12, switchFlag: 0},
  37917. {qe: 0x0521, nmps: 5, nlps: 29, switchFlag: 0},
  37918. {qe: 0x0221, nmps: 38, nlps: 33, switchFlag: 0},
  37919. {qe: 0x5601, nmps: 7, nlps: 6, switchFlag: 1},
  37920. {qe: 0x5401, nmps: 8, nlps: 14, switchFlag: 0},
  37921. {qe: 0x4801, nmps: 9, nlps: 14, switchFlag: 0},
  37922. {qe: 0x3801, nmps: 10, nlps: 14, switchFlag: 0},
  37923. {qe: 0x3001, nmps: 11, nlps: 17, switchFlag: 0},
  37924. {qe: 0x2401, nmps: 12, nlps: 18, switchFlag: 0},
  37925. {qe: 0x1C01, nmps: 13, nlps: 20, switchFlag: 0},
  37926. {qe: 0x1601, nmps: 29, nlps: 21, switchFlag: 0},
  37927. {qe: 0x5601, nmps: 15, nlps: 14, switchFlag: 1},
  37928. {qe: 0x5401, nmps: 16, nlps: 14, switchFlag: 0},
  37929. {qe: 0x5101, nmps: 17, nlps: 15, switchFlag: 0},
  37930. {qe: 0x4801, nmps: 18, nlps: 16, switchFlag: 0},
  37931. {qe: 0x3801, nmps: 19, nlps: 17, switchFlag: 0},
  37932. {qe: 0x3401, nmps: 20, nlps: 18, switchFlag: 0},
  37933. {qe: 0x3001, nmps: 21, nlps: 19, switchFlag: 0},
  37934. {qe: 0x2801, nmps: 22, nlps: 19, switchFlag: 0},
  37935. {qe: 0x2401, nmps: 23, nlps: 20, switchFlag: 0},
  37936. {qe: 0x2201, nmps: 24, nlps: 21, switchFlag: 0},
  37937. {qe: 0x1C01, nmps: 25, nlps: 22, switchFlag: 0},
  37938. {qe: 0x1801, nmps: 26, nlps: 23, switchFlag: 0},
  37939. {qe: 0x1601, nmps: 27, nlps: 24, switchFlag: 0},
  37940. {qe: 0x1401, nmps: 28, nlps: 25, switchFlag: 0},
  37941. {qe: 0x1201, nmps: 29, nlps: 26, switchFlag: 0},
  37942. {qe: 0x1101, nmps: 30, nlps: 27, switchFlag: 0},
  37943. {qe: 0x0AC1, nmps: 31, nlps: 28, switchFlag: 0},
  37944. {qe: 0x09C1, nmps: 32, nlps: 29, switchFlag: 0},
  37945. {qe: 0x08A1, nmps: 33, nlps: 30, switchFlag: 0},
  37946. {qe: 0x0521, nmps: 34, nlps: 31, switchFlag: 0},
  37947. {qe: 0x0441, nmps: 35, nlps: 32, switchFlag: 0},
  37948. {qe: 0x02A1, nmps: 36, nlps: 33, switchFlag: 0},
  37949. {qe: 0x0221, nmps: 37, nlps: 34, switchFlag: 0},
  37950. {qe: 0x0141, nmps: 38, nlps: 35, switchFlag: 0},
  37951. {qe: 0x0111, nmps: 39, nlps: 36, switchFlag: 0},
  37952. {qe: 0x0085, nmps: 40, nlps: 37, switchFlag: 0},
  37953. {qe: 0x0049, nmps: 41, nlps: 38, switchFlag: 0},
  37954. {qe: 0x0025, nmps: 42, nlps: 39, switchFlag: 0},
  37955. {qe: 0x0015, nmps: 43, nlps: 40, switchFlag: 0},
  37956. {qe: 0x0009, nmps: 44, nlps: 41, switchFlag: 0},
  37957. {qe: 0x0005, nmps: 45, nlps: 42, switchFlag: 0},
  37958. {qe: 0x0001, nmps: 45, nlps: 43, switchFlag: 0},
  37959. {qe: 0x5601, nmps: 46, nlps: 46, switchFlag: 0}
  37960. ];
  37961. // C.3.5 Initialisation of the decoder (INITDEC)
  37962. function ArithmeticDecoder(data, start, end) {
  37963. this.data = data;
  37964. this.bp = start;
  37965. this.dataEnd = end;
  37966. this.chigh = data[start];
  37967. this.clow = 0;
  37968. this.byteIn();
  37969. this.chigh = ((this.chigh << 7) & 0xFFFF) | ((this.clow >> 9) & 0x7F);
  37970. this.clow = (this.clow << 7) & 0xFFFF;
  37971. this.ct -= 7;
  37972. this.a = 0x8000;
  37973. }
  37974. ArithmeticDecoder.prototype = {
  37975. // C.3.4 Compressed data input (BYTEIN)
  37976. byteIn: function ArithmeticDecoder_byteIn() {
  37977. var data = this.data;
  37978. var bp = this.bp;
  37979. if (data[bp] === 0xFF) {
  37980. var b1 = data[bp + 1];
  37981. if (b1 > 0x8F) {
  37982. this.clow += 0xFF00;
  37983. this.ct = 8;
  37984. } else {
  37985. bp++;
  37986. this.clow += (data[bp] << 9);
  37987. this.ct = 7;
  37988. this.bp = bp;
  37989. }
  37990. } else {
  37991. bp++;
  37992. this.clow += bp < this.dataEnd ? (data[bp] << 8) : 0xFF00;
  37993. this.ct = 8;
  37994. this.bp = bp;
  37995. }
  37996. if (this.clow > 0xFFFF) {
  37997. this.chigh += (this.clow >> 16);
  37998. this.clow &= 0xFFFF;
  37999. }
  38000. },
  38001. // C.3.2 Decoding a decision (DECODE)
  38002. readBit: function ArithmeticDecoder_readBit(contexts, pos) {
  38003. // contexts are packed into 1 byte:
  38004. // highest 7 bits carry cx.index, lowest bit carries cx.mps
  38005. var cx_index = contexts[pos] >> 1, cx_mps = contexts[pos] & 1;
  38006. var qeTableIcx = QeTable[cx_index];
  38007. var qeIcx = qeTableIcx.qe;
  38008. var d;
  38009. var a = this.a - qeIcx;
  38010. if (this.chigh < qeIcx) {
  38011. // exchangeLps
  38012. if (a < qeIcx) {
  38013. a = qeIcx;
  38014. d = cx_mps;
  38015. cx_index = qeTableIcx.nmps;
  38016. } else {
  38017. a = qeIcx;
  38018. d = 1 ^ cx_mps;
  38019. if (qeTableIcx.switchFlag === 1) {
  38020. cx_mps = d;
  38021. }
  38022. cx_index = qeTableIcx.nlps;
  38023. }
  38024. } else {
  38025. this.chigh -= qeIcx;
  38026. if ((a & 0x8000) !== 0) {
  38027. this.a = a;
  38028. return cx_mps;
  38029. }
  38030. // exchangeMps
  38031. if (a < qeIcx) {
  38032. d = 1 ^ cx_mps;
  38033. if (qeTableIcx.switchFlag === 1) {
  38034. cx_mps = d;
  38035. }
  38036. cx_index = qeTableIcx.nlps;
  38037. } else {
  38038. d = cx_mps;
  38039. cx_index = qeTableIcx.nmps;
  38040. }
  38041. }
  38042. // C.3.3 renormD;
  38043. do {
  38044. if (this.ct === 0) {
  38045. this.byteIn();
  38046. }
  38047. a <<= 1;
  38048. this.chigh = ((this.chigh << 1) & 0xFFFF) | ((this.clow >> 15) & 1);
  38049. this.clow = (this.clow << 1) & 0xFFFF;
  38050. this.ct--;
  38051. } while ((a & 0x8000) === 0);
  38052. this.a = a;
  38053. contexts[pos] = cx_index << 1 | cx_mps;
  38054. return d;
  38055. }
  38056. };
  38057. return ArithmeticDecoder;
  38058. })();
  38059. var JpegImage = (function jpegImage() {
  38060. var dctZigZag = new Uint8Array([
  38061. 0,
  38062. 1, 8,
  38063. 16, 9, 2,
  38064. 3, 10, 17, 24,
  38065. 32, 25, 18, 11, 4,
  38066. 5, 12, 19, 26, 33, 40,
  38067. 48, 41, 34, 27, 20, 13, 6,
  38068. 7, 14, 21, 28, 35, 42, 49, 56,
  38069. 57, 50, 43, 36, 29, 22, 15,
  38070. 23, 30, 37, 44, 51, 58,
  38071. 59, 52, 45, 38, 31,
  38072. 39, 46, 53, 60,
  38073. 61, 54, 47,
  38074. 55, 62,
  38075. 63
  38076. ]);
  38077. var dctCos1 = 4017; // cos(pi/16)
  38078. var dctSin1 = 799; // sin(pi/16)
  38079. var dctCos3 = 3406; // cos(3*pi/16)
  38080. var dctSin3 = 2276; // sin(3*pi/16)
  38081. var dctCos6 = 1567; // cos(6*pi/16)
  38082. var dctSin6 = 3784; // sin(6*pi/16)
  38083. var dctSqrt2 = 5793; // sqrt(2)
  38084. var dctSqrt1d2 = 2896; // sqrt(2) / 2
  38085. function constructor() {
  38086. }
  38087. function buildHuffmanTable(codeLengths, values) {
  38088. var k = 0, code = [], i, j, length = 16;
  38089. while (length > 0 && !codeLengths[length - 1]) {
  38090. length--;
  38091. }
  38092. code.push({children: [], index: 0});
  38093. var p = code[0], q;
  38094. for (i = 0; i < length; i++) {
  38095. for (j = 0; j < codeLengths[i]; j++) {
  38096. p = code.pop();
  38097. p.children[p.index] = values[k];
  38098. while (p.index > 0) {
  38099. p = code.pop();
  38100. }
  38101. p.index++;
  38102. code.push(p);
  38103. while (code.length <= i) {
  38104. code.push(q = {children: [], index: 0});
  38105. p.children[p.index] = q.children;
  38106. p = q;
  38107. }
  38108. k++;
  38109. }
  38110. if (i + 1 < length) {
  38111. // p here points to last code
  38112. code.push(q = {children: [], index: 0});
  38113. p.children[p.index] = q.children;
  38114. p = q;
  38115. }
  38116. }
  38117. return code[0].children;
  38118. }
  38119. function getBlockBufferOffset(component, row, col) {
  38120. return 64 * ((component.blocksPerLine + 1) * row + col);
  38121. }
  38122. function decodeScan(data, offset, frame, components, resetInterval,
  38123. spectralStart, spectralEnd, successivePrev, successive) {
  38124. var precision = frame.precision;
  38125. var samplesPerLine = frame.samplesPerLine;
  38126. var scanLines = frame.scanLines;
  38127. var mcusPerLine = frame.mcusPerLine;
  38128. var progressive = frame.progressive;
  38129. var maxH = frame.maxH, maxV = frame.maxV;
  38130. var startOffset = offset, bitsData = 0, bitsCount = 0;
  38131. function readBit() {
  38132. if (bitsCount > 0) {
  38133. bitsCount--;
  38134. return (bitsData >> bitsCount) & 1;
  38135. }
  38136. bitsData = data[offset++];
  38137. if (bitsData === 0xFF) {
  38138. var nextByte = data[offset++];
  38139. if (nextByte) {
  38140. throw 'unexpected marker: ' +
  38141. ((bitsData << 8) | nextByte).toString(16);
  38142. }
  38143. // unstuff 0
  38144. }
  38145. bitsCount = 7;
  38146. return bitsData >>> 7;
  38147. }
  38148. function decodeHuffman(tree) {
  38149. var node = tree;
  38150. while (true) {
  38151. node = node[readBit()];
  38152. if (typeof node === 'number') {
  38153. return node;
  38154. }
  38155. if (typeof node !== 'object') {
  38156. throw 'invalid huffman sequence';
  38157. }
  38158. }
  38159. }
  38160. function receive(length) {
  38161. var n = 0;
  38162. while (length > 0) {
  38163. n = (n << 1) | readBit();
  38164. length--;
  38165. }
  38166. return n;
  38167. }
  38168. function receiveAndExtend(length) {
  38169. if (length === 1) {
  38170. return readBit() === 1 ? 1 : -1;
  38171. }
  38172. var n = receive(length);
  38173. if (n >= 1 << (length - 1)) {
  38174. return n;
  38175. }
  38176. return n + (-1 << length) + 1;
  38177. }
  38178. function decodeBaseline(component, offset) {
  38179. var t = decodeHuffman(component.huffmanTableDC);
  38180. var diff = t === 0 ? 0 : receiveAndExtend(t);
  38181. component.blockData[offset] = (component.pred += diff);
  38182. var k = 1;
  38183. while (k < 64) {
  38184. var rs = decodeHuffman(component.huffmanTableAC);
  38185. var s = rs & 15, r = rs >> 4;
  38186. if (s === 0) {
  38187. if (r < 15) {
  38188. break;
  38189. }
  38190. k += 16;
  38191. continue;
  38192. }
  38193. k += r;
  38194. var z = dctZigZag[k];
  38195. component.blockData[offset + z] = receiveAndExtend(s);
  38196. k++;
  38197. }
  38198. }
  38199. function decodeDCFirst(component, offset) {
  38200. var t = decodeHuffman(component.huffmanTableDC);
  38201. var diff = t === 0 ? 0 : (receiveAndExtend(t) << successive);
  38202. component.blockData[offset] = (component.pred += diff);
  38203. }
  38204. function decodeDCSuccessive(component, offset) {
  38205. component.blockData[offset] |= readBit() << successive;
  38206. }
  38207. var eobrun = 0;
  38208. function decodeACFirst(component, offset) {
  38209. if (eobrun > 0) {
  38210. eobrun--;
  38211. return;
  38212. }
  38213. var k = spectralStart, e = spectralEnd;
  38214. while (k <= e) {
  38215. var rs = decodeHuffman(component.huffmanTableAC);
  38216. var s = rs & 15, r = rs >> 4;
  38217. if (s === 0) {
  38218. if (r < 15) {
  38219. eobrun = receive(r) + (1 << r) - 1;
  38220. break;
  38221. }
  38222. k += 16;
  38223. continue;
  38224. }
  38225. k += r;
  38226. var z = dctZigZag[k];
  38227. component.blockData[offset + z] =
  38228. receiveAndExtend(s) * (1 << successive);
  38229. k++;
  38230. }
  38231. }
  38232. var successiveACState = 0, successiveACNextValue;
  38233. function decodeACSuccessive(component, offset) {
  38234. var k = spectralStart;
  38235. var e = spectralEnd;
  38236. var r = 0;
  38237. var s;
  38238. var rs;
  38239. while (k <= e) {
  38240. var z = dctZigZag[k];
  38241. switch (successiveACState) {
  38242. case 0: // initial state
  38243. rs = decodeHuffman(component.huffmanTableAC);
  38244. s = rs & 15;
  38245. r = rs >> 4;
  38246. if (s === 0) {
  38247. if (r < 15) {
  38248. eobrun = receive(r) + (1 << r);
  38249. successiveACState = 4;
  38250. } else {
  38251. r = 16;
  38252. successiveACState = 1;
  38253. }
  38254. } else {
  38255. if (s !== 1) {
  38256. throw 'invalid ACn encoding';
  38257. }
  38258. successiveACNextValue = receiveAndExtend(s);
  38259. successiveACState = r ? 2 : 3;
  38260. }
  38261. continue;
  38262. case 1: // skipping r zero items
  38263. case 2:
  38264. if (component.blockData[offset + z]) {
  38265. component.blockData[offset + z] += (readBit() << successive);
  38266. } else {
  38267. r--;
  38268. if (r === 0) {
  38269. successiveACState = successiveACState === 2 ? 3 : 0;
  38270. }
  38271. }
  38272. break;
  38273. case 3: // set value for a zero item
  38274. if (component.blockData[offset + z]) {
  38275. component.blockData[offset + z] += (readBit() << successive);
  38276. } else {
  38277. component.blockData[offset + z] =
  38278. successiveACNextValue << successive;
  38279. successiveACState = 0;
  38280. }
  38281. break;
  38282. case 4: // eob
  38283. if (component.blockData[offset + z]) {
  38284. component.blockData[offset + z] += (readBit() << successive);
  38285. }
  38286. break;
  38287. }
  38288. k++;
  38289. }
  38290. if (successiveACState === 4) {
  38291. eobrun--;
  38292. if (eobrun === 0) {
  38293. successiveACState = 0;
  38294. }
  38295. }
  38296. }
  38297. function decodeMcu(component, decode, mcu, row, col) {
  38298. var mcuRow = (mcu / mcusPerLine) | 0;
  38299. var mcuCol = mcu % mcusPerLine;
  38300. var blockRow = mcuRow * component.v + row;
  38301. var blockCol = mcuCol * component.h + col;
  38302. var offset = getBlockBufferOffset(component, blockRow, blockCol);
  38303. decode(component, offset);
  38304. }
  38305. function decodeBlock(component, decode, mcu) {
  38306. var blockRow = (mcu / component.blocksPerLine) | 0;
  38307. var blockCol = mcu % component.blocksPerLine;
  38308. var offset = getBlockBufferOffset(component, blockRow, blockCol);
  38309. decode(component, offset);
  38310. }
  38311. var componentsLength = components.length;
  38312. var component, i, j, k, n;
  38313. var decodeFn;
  38314. if (progressive) {
  38315. if (spectralStart === 0) {
  38316. decodeFn = successivePrev === 0 ? decodeDCFirst : decodeDCSuccessive;
  38317. } else {
  38318. decodeFn = successivePrev === 0 ? decodeACFirst : decodeACSuccessive;
  38319. }
  38320. } else {
  38321. decodeFn = decodeBaseline;
  38322. }
  38323. var mcu = 0, marker;
  38324. var mcuExpected;
  38325. if (componentsLength === 1) {
  38326. mcuExpected = components[0].blocksPerLine * components[0].blocksPerColumn;
  38327. } else {
  38328. mcuExpected = mcusPerLine * frame.mcusPerColumn;
  38329. }
  38330. if (!resetInterval) {
  38331. resetInterval = mcuExpected;
  38332. }
  38333. var h, v;
  38334. while (mcu < mcuExpected) {
  38335. // reset interval stuff
  38336. for (i = 0; i < componentsLength; i++) {
  38337. components[i].pred = 0;
  38338. }
  38339. eobrun = 0;
  38340. if (componentsLength === 1) {
  38341. component = components[0];
  38342. for (n = 0; n < resetInterval; n++) {
  38343. decodeBlock(component, decodeFn, mcu);
  38344. mcu++;
  38345. }
  38346. } else {
  38347. for (n = 0; n < resetInterval; n++) {
  38348. for (i = 0; i < componentsLength; i++) {
  38349. component = components[i];
  38350. h = component.h;
  38351. v = component.v;
  38352. for (j = 0; j < v; j++) {
  38353. for (k = 0; k < h; k++) {
  38354. decodeMcu(component, decodeFn, mcu, j, k);
  38355. }
  38356. }
  38357. }
  38358. mcu++;
  38359. }
  38360. }
  38361. // find marker
  38362. bitsCount = 0;
  38363. marker = (data[offset] << 8) | data[offset + 1];
  38364. if (marker <= 0xFF00) {
  38365. throw 'marker was not found';
  38366. }
  38367. if (marker >= 0xFFD0 && marker <= 0xFFD7) { // RSTx
  38368. offset += 2;
  38369. } else {
  38370. break;
  38371. }
  38372. }
  38373. return offset - startOffset;
  38374. }
  38375. // A port of poppler's IDCT method which in turn is taken from:
  38376. // Christoph Loeffler, Adriaan Ligtenberg, George S. Moschytz,
  38377. // 'Practical Fast 1-D DCT Algorithms with 11 Multiplications',
  38378. // IEEE Intl. Conf. on Acoustics, Speech & Signal Processing, 1989,
  38379. // 988-991.
  38380. function quantizeAndInverse(component, blockBufferOffset, p) {
  38381. var qt = component.quantizationTable, blockData = component.blockData;
  38382. var v0, v1, v2, v3, v4, v5, v6, v7;
  38383. var p0, p1, p2, p3, p4, p5, p6, p7;
  38384. var t;
  38385. // inverse DCT on rows
  38386. for (var row = 0; row < 64; row += 8) {
  38387. // gather block data
  38388. p0 = blockData[blockBufferOffset + row];
  38389. p1 = blockData[blockBufferOffset + row + 1];
  38390. p2 = blockData[blockBufferOffset + row + 2];
  38391. p3 = blockData[blockBufferOffset + row + 3];
  38392. p4 = blockData[blockBufferOffset + row + 4];
  38393. p5 = blockData[blockBufferOffset + row + 5];
  38394. p6 = blockData[blockBufferOffset + row + 6];
  38395. p7 = blockData[blockBufferOffset + row + 7];
  38396. // dequant p0
  38397. p0 *= qt[row];
  38398. // check for all-zero AC coefficients
  38399. if ((p1 | p2 | p3 | p4 | p5 | p6 | p7) === 0) {
  38400. t = (dctSqrt2 * p0 + 512) >> 10;
  38401. p[row] = t;
  38402. p[row + 1] = t;
  38403. p[row + 2] = t;
  38404. p[row + 3] = t;
  38405. p[row + 4] = t;
  38406. p[row + 5] = t;
  38407. p[row + 6] = t;
  38408. p[row + 7] = t;
  38409. continue;
  38410. }
  38411. // dequant p1 ... p7
  38412. p1 *= qt[row + 1];
  38413. p2 *= qt[row + 2];
  38414. p3 *= qt[row + 3];
  38415. p4 *= qt[row + 4];
  38416. p5 *= qt[row + 5];
  38417. p6 *= qt[row + 6];
  38418. p7 *= qt[row + 7];
  38419. // stage 4
  38420. v0 = (dctSqrt2 * p0 + 128) >> 8;
  38421. v1 = (dctSqrt2 * p4 + 128) >> 8;
  38422. v2 = p2;
  38423. v3 = p6;
  38424. v4 = (dctSqrt1d2 * (p1 - p7) + 128) >> 8;
  38425. v7 = (dctSqrt1d2 * (p1 + p7) + 128) >> 8;
  38426. v5 = p3 << 4;
  38427. v6 = p5 << 4;
  38428. // stage 3
  38429. v0 = (v0 + v1 + 1) >> 1;
  38430. v1 = v0 - v1;
  38431. t = (v2 * dctSin6 + v3 * dctCos6 + 128) >> 8;
  38432. v2 = (v2 * dctCos6 - v3 * dctSin6 + 128) >> 8;
  38433. v3 = t;
  38434. v4 = (v4 + v6 + 1) >> 1;
  38435. v6 = v4 - v6;
  38436. v7 = (v7 + v5 + 1) >> 1;
  38437. v5 = v7 - v5;
  38438. // stage 2
  38439. v0 = (v0 + v3 + 1) >> 1;
  38440. v3 = v0 - v3;
  38441. v1 = (v1 + v2 + 1) >> 1;
  38442. v2 = v1 - v2;
  38443. t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;
  38444. v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;
  38445. v7 = t;
  38446. t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;
  38447. v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;
  38448. v6 = t;
  38449. // stage 1
  38450. p[row] = v0 + v7;
  38451. p[row + 7] = v0 - v7;
  38452. p[row + 1] = v1 + v6;
  38453. p[row + 6] = v1 - v6;
  38454. p[row + 2] = v2 + v5;
  38455. p[row + 5] = v2 - v5;
  38456. p[row + 3] = v3 + v4;
  38457. p[row + 4] = v3 - v4;
  38458. }
  38459. // inverse DCT on columns
  38460. for (var col = 0; col < 8; ++col) {
  38461. p0 = p[col];
  38462. p1 = p[col + 8];
  38463. p2 = p[col + 16];
  38464. p3 = p[col + 24];
  38465. p4 = p[col + 32];
  38466. p5 = p[col + 40];
  38467. p6 = p[col + 48];
  38468. p7 = p[col + 56];
  38469. // check for all-zero AC coefficients
  38470. if ((p1 | p2 | p3 | p4 | p5 | p6 | p7) === 0) {
  38471. t = (dctSqrt2 * p0 + 8192) >> 14;
  38472. // convert to 8 bit
  38473. t = (t < -2040) ? 0 : (t >= 2024) ? 255 : (t + 2056) >> 4;
  38474. blockData[blockBufferOffset + col] = t;
  38475. blockData[blockBufferOffset + col + 8] = t;
  38476. blockData[blockBufferOffset + col + 16] = t;
  38477. blockData[blockBufferOffset + col + 24] = t;
  38478. blockData[blockBufferOffset + col + 32] = t;
  38479. blockData[blockBufferOffset + col + 40] = t;
  38480. blockData[blockBufferOffset + col + 48] = t;
  38481. blockData[blockBufferOffset + col + 56] = t;
  38482. continue;
  38483. }
  38484. // stage 4
  38485. v0 = (dctSqrt2 * p0 + 2048) >> 12;
  38486. v1 = (dctSqrt2 * p4 + 2048) >> 12;
  38487. v2 = p2;
  38488. v3 = p6;
  38489. v4 = (dctSqrt1d2 * (p1 - p7) + 2048) >> 12;
  38490. v7 = (dctSqrt1d2 * (p1 + p7) + 2048) >> 12;
  38491. v5 = p3;
  38492. v6 = p5;
  38493. // stage 3
  38494. // Shift v0 by 128.5 << 5 here, so we don't need to shift p0...p7 when
  38495. // converting to UInt8 range later.
  38496. v0 = ((v0 + v1 + 1) >> 1) + 4112;
  38497. v1 = v0 - v1;
  38498. t = (v2 * dctSin6 + v3 * dctCos6 + 2048) >> 12;
  38499. v2 = (v2 * dctCos6 - v3 * dctSin6 + 2048) >> 12;
  38500. v3 = t;
  38501. v4 = (v4 + v6 + 1) >> 1;
  38502. v6 = v4 - v6;
  38503. v7 = (v7 + v5 + 1) >> 1;
  38504. v5 = v7 - v5;
  38505. // stage 2
  38506. v0 = (v0 + v3 + 1) >> 1;
  38507. v3 = v0 - v3;
  38508. v1 = (v1 + v2 + 1) >> 1;
  38509. v2 = v1 - v2;
  38510. t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;
  38511. v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;
  38512. v7 = t;
  38513. t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;
  38514. v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;
  38515. v6 = t;
  38516. // stage 1
  38517. p0 = v0 + v7;
  38518. p7 = v0 - v7;
  38519. p1 = v1 + v6;
  38520. p6 = v1 - v6;
  38521. p2 = v2 + v5;
  38522. p5 = v2 - v5;
  38523. p3 = v3 + v4;
  38524. p4 = v3 - v4;
  38525. // convert to 8-bit integers
  38526. p0 = (p0 < 16) ? 0 : (p0 >= 4080) ? 255 : p0 >> 4;
  38527. p1 = (p1 < 16) ? 0 : (p1 >= 4080) ? 255 : p1 >> 4;
  38528. p2 = (p2 < 16) ? 0 : (p2 >= 4080) ? 255 : p2 >> 4;
  38529. p3 = (p3 < 16) ? 0 : (p3 >= 4080) ? 255 : p3 >> 4;
  38530. p4 = (p4 < 16) ? 0 : (p4 >= 4080) ? 255 : p4 >> 4;
  38531. p5 = (p5 < 16) ? 0 : (p5 >= 4080) ? 255 : p5 >> 4;
  38532. p6 = (p6 < 16) ? 0 : (p6 >= 4080) ? 255 : p6 >> 4;
  38533. p7 = (p7 < 16) ? 0 : (p7 >= 4080) ? 255 : p7 >> 4;
  38534. // store block data
  38535. blockData[blockBufferOffset + col] = p0;
  38536. blockData[blockBufferOffset + col + 8] = p1;
  38537. blockData[blockBufferOffset + col + 16] = p2;
  38538. blockData[blockBufferOffset + col + 24] = p3;
  38539. blockData[blockBufferOffset + col + 32] = p4;
  38540. blockData[blockBufferOffset + col + 40] = p5;
  38541. blockData[blockBufferOffset + col + 48] = p6;
  38542. blockData[blockBufferOffset + col + 56] = p7;
  38543. }
  38544. }
  38545. function buildComponentData(frame, component) {
  38546. var blocksPerLine = component.blocksPerLine;
  38547. var blocksPerColumn = component.blocksPerColumn;
  38548. var computationBuffer = new Int16Array(64);
  38549. for (var blockRow = 0; blockRow < blocksPerColumn; blockRow++) {
  38550. for (var blockCol = 0; blockCol < blocksPerLine; blockCol++) {
  38551. var offset = getBlockBufferOffset(component, blockRow, blockCol);
  38552. quantizeAndInverse(component, offset, computationBuffer);
  38553. }
  38554. }
  38555. return component.blockData;
  38556. }
  38557. function clamp0to255(a) {
  38558. return a <= 0 ? 0 : a >= 255 ? 255 : a;
  38559. }
  38560. constructor.prototype = {
  38561. parse: function parse(data) {
  38562. function readUint16() {
  38563. var value = (data[offset] << 8) | data[offset + 1];
  38564. offset += 2;
  38565. return value;
  38566. }
  38567. function readDataBlock() {
  38568. var length = readUint16();
  38569. var array = data.subarray(offset, offset + length - 2);
  38570. offset += array.length;
  38571. return array;
  38572. }
  38573. function prepareComponents(frame) {
  38574. var mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / frame.maxH);
  38575. var mcusPerColumn = Math.ceil(frame.scanLines / 8 / frame.maxV);
  38576. for (var i = 0; i < frame.components.length; i++) {
  38577. component = frame.components[i];
  38578. var blocksPerLine = Math.ceil(Math.ceil(frame.samplesPerLine / 8) *
  38579. component.h / frame.maxH);
  38580. var blocksPerColumn = Math.ceil(Math.ceil(frame.scanLines / 8) *
  38581. component.v / frame.maxV);
  38582. var blocksPerLineForMcu = mcusPerLine * component.h;
  38583. var blocksPerColumnForMcu = mcusPerColumn * component.v;
  38584. var blocksBufferSize = 64 * blocksPerColumnForMcu *
  38585. (blocksPerLineForMcu + 1);
  38586. component.blockData = new Int16Array(blocksBufferSize);
  38587. component.blocksPerLine = blocksPerLine;
  38588. component.blocksPerColumn = blocksPerColumn;
  38589. }
  38590. frame.mcusPerLine = mcusPerLine;
  38591. frame.mcusPerColumn = mcusPerColumn;
  38592. }
  38593. var offset = 0, length = data.length;
  38594. var jfif = null;
  38595. var adobe = null;
  38596. var pixels = null;
  38597. var frame, resetInterval;
  38598. var quantizationTables = [];
  38599. var huffmanTablesAC = [], huffmanTablesDC = [];
  38600. var fileMarker = readUint16();
  38601. if (fileMarker !== 0xFFD8) { // SOI (Start of Image)
  38602. throw 'SOI not found';
  38603. }
  38604. fileMarker = readUint16();
  38605. while (fileMarker !== 0xFFD9) { // EOI (End of image)
  38606. var i, j, l;
  38607. switch(fileMarker) {
  38608. case 0xFFE0: // APP0 (Application Specific)
  38609. case 0xFFE1: // APP1
  38610. case 0xFFE2: // APP2
  38611. case 0xFFE3: // APP3
  38612. case 0xFFE4: // APP4
  38613. case 0xFFE5: // APP5
  38614. case 0xFFE6: // APP6
  38615. case 0xFFE7: // APP7
  38616. case 0xFFE8: // APP8
  38617. case 0xFFE9: // APP9
  38618. case 0xFFEA: // APP10
  38619. case 0xFFEB: // APP11
  38620. case 0xFFEC: // APP12
  38621. case 0xFFED: // APP13
  38622. case 0xFFEE: // APP14
  38623. case 0xFFEF: // APP15
  38624. case 0xFFFE: // COM (Comment)
  38625. var appData = readDataBlock();
  38626. if (fileMarker === 0xFFE0) {
  38627. if (appData[0] === 0x4A && appData[1] === 0x46 &&
  38628. appData[2] === 0x49 && appData[3] === 0x46 &&
  38629. appData[4] === 0) { // 'JFIF\x00'
  38630. jfif = {
  38631. version: { major: appData[5], minor: appData[6] },
  38632. densityUnits: appData[7],
  38633. xDensity: (appData[8] << 8) | appData[9],
  38634. yDensity: (appData[10] << 8) | appData[11],
  38635. thumbWidth: appData[12],
  38636. thumbHeight: appData[13],
  38637. thumbData: appData.subarray(14, 14 +
  38638. 3 * appData[12] * appData[13])
  38639. };
  38640. }
  38641. }
  38642. // TODO APP1 - Exif
  38643. if (fileMarker === 0xFFEE) {
  38644. if (appData[0] === 0x41 && appData[1] === 0x64 &&
  38645. appData[2] === 0x6F && appData[3] === 0x62 &&
  38646. appData[4] === 0x65) { // 'Adobe'
  38647. adobe = {
  38648. version: (appData[5] << 8) | appData[6],
  38649. flags0: (appData[7] << 8) | appData[8],
  38650. flags1: (appData[9] << 8) | appData[10],
  38651. transformCode: appData[11]
  38652. };
  38653. }
  38654. }
  38655. break;
  38656. case 0xFFDB: // DQT (Define Quantization Tables)
  38657. var quantizationTablesLength = readUint16();
  38658. var quantizationTablesEnd = quantizationTablesLength + offset - 2;
  38659. var z;
  38660. while (offset < quantizationTablesEnd) {
  38661. var quantizationTableSpec = data[offset++];
  38662. var tableData = new Uint16Array(64);
  38663. if ((quantizationTableSpec >> 4) === 0) { // 8 bit values
  38664. for (j = 0; j < 64; j++) {
  38665. z = dctZigZag[j];
  38666. tableData[z] = data[offset++];
  38667. }
  38668. } else if ((quantizationTableSpec >> 4) === 1) { //16 bit
  38669. for (j = 0; j < 64; j++) {
  38670. z = dctZigZag[j];
  38671. tableData[z] = readUint16();
  38672. }
  38673. } else {
  38674. throw 'DQT: invalid table spec';
  38675. }
  38676. quantizationTables[quantizationTableSpec & 15] = tableData;
  38677. }
  38678. break;
  38679. case 0xFFC0: // SOF0 (Start of Frame, Baseline DCT)
  38680. case 0xFFC1: // SOF1 (Start of Frame, Extended DCT)
  38681. case 0xFFC2: // SOF2 (Start of Frame, Progressive DCT)
  38682. if (frame) {
  38683. throw 'Only single frame JPEGs supported';
  38684. }
  38685. readUint16(); // skip data length
  38686. frame = {};
  38687. frame.extended = (fileMarker === 0xFFC1);
  38688. frame.progressive = (fileMarker === 0xFFC2);
  38689. frame.precision = data[offset++];
  38690. frame.scanLines = readUint16();
  38691. frame.samplesPerLine = readUint16();
  38692. frame.components = [];
  38693. frame.componentIds = {};
  38694. var componentsCount = data[offset++], componentId;
  38695. var maxH = 0, maxV = 0;
  38696. for (i = 0; i < componentsCount; i++) {
  38697. componentId = data[offset];
  38698. var h = data[offset + 1] >> 4;
  38699. var v = data[offset + 1] & 15;
  38700. if (maxH < h) {
  38701. maxH = h;
  38702. }
  38703. if (maxV < v) {
  38704. maxV = v;
  38705. }
  38706. var qId = data[offset + 2];
  38707. l = frame.components.push({
  38708. h: h,
  38709. v: v,
  38710. quantizationTable: quantizationTables[qId]
  38711. });
  38712. frame.componentIds[componentId] = l - 1;
  38713. offset += 3;
  38714. }
  38715. frame.maxH = maxH;
  38716. frame.maxV = maxV;
  38717. prepareComponents(frame);
  38718. break;
  38719. case 0xFFC4: // DHT (Define Huffman Tables)
  38720. var huffmanLength = readUint16();
  38721. for (i = 2; i < huffmanLength;) {
  38722. var huffmanTableSpec = data[offset++];
  38723. var codeLengths = new Uint8Array(16);
  38724. var codeLengthSum = 0;
  38725. for (j = 0; j < 16; j++, offset++) {
  38726. codeLengthSum += (codeLengths[j] = data[offset]);
  38727. }
  38728. var huffmanValues = new Uint8Array(codeLengthSum);
  38729. for (j = 0; j < codeLengthSum; j++, offset++) {
  38730. huffmanValues[j] = data[offset];
  38731. }
  38732. i += 17 + codeLengthSum;
  38733. ((huffmanTableSpec >> 4) === 0 ?
  38734. huffmanTablesDC : huffmanTablesAC)[huffmanTableSpec & 15] =
  38735. buildHuffmanTable(codeLengths, huffmanValues);
  38736. }
  38737. break;
  38738. case 0xFFDD: // DRI (Define Restart Interval)
  38739. readUint16(); // skip data length
  38740. resetInterval = readUint16();
  38741. break;
  38742. case 0xFFDA: // SOS (Start of Scan)
  38743. var scanLength = readUint16();
  38744. var selectorsCount = data[offset++];
  38745. var components = [], component;
  38746. for (i = 0; i < selectorsCount; i++) {
  38747. var componentIndex = frame.componentIds[data[offset++]];
  38748. component = frame.components[componentIndex];
  38749. var tableSpec = data[offset++];
  38750. component.huffmanTableDC = huffmanTablesDC[tableSpec >> 4];
  38751. component.huffmanTableAC = huffmanTablesAC[tableSpec & 15];
  38752. components.push(component);
  38753. }
  38754. var spectralStart = data[offset++];
  38755. var spectralEnd = data[offset++];
  38756. var successiveApproximation = data[offset++];
  38757. var processed = decodeScan(data, offset,
  38758. frame, components, resetInterval,
  38759. spectralStart, spectralEnd,
  38760. successiveApproximation >> 4, successiveApproximation & 15);
  38761. offset += processed;
  38762. break;
  38763. case 0xFFFF: // Fill bytes
  38764. if (data[offset] !== 0xFF) { // Avoid skipping a valid marker.
  38765. offset--;
  38766. }
  38767. break;
  38768. default:
  38769. if (data[offset - 3] === 0xFF &&
  38770. data[offset - 2] >= 0xC0 && data[offset - 2] <= 0xFE) {
  38771. // could be incorrect encoding -- last 0xFF byte of the previous
  38772. // block was eaten by the encoder
  38773. offset -= 3;
  38774. break;
  38775. }
  38776. throw 'unknown JPEG marker ' + fileMarker.toString(16);
  38777. }
  38778. fileMarker = readUint16();
  38779. }
  38780. this.width = frame.samplesPerLine;
  38781. this.height = frame.scanLines;
  38782. this.jfif = jfif;
  38783. this.adobe = adobe;
  38784. this.components = [];
  38785. for (i = 0; i < frame.components.length; i++) {
  38786. component = frame.components[i];
  38787. this.components.push({
  38788. output: buildComponentData(frame, component),
  38789. scaleX: component.h / frame.maxH,
  38790. scaleY: component.v / frame.maxV,
  38791. blocksPerLine: component.blocksPerLine,
  38792. blocksPerColumn: component.blocksPerColumn
  38793. });
  38794. }
  38795. this.numComponents = this.components.length;
  38796. },
  38797. _getLinearizedBlockData: function getLinearizedBlockData(width, height) {
  38798. var scaleX = this.width / width, scaleY = this.height / height;
  38799. var component, componentScaleX, componentScaleY, blocksPerScanline;
  38800. var x, y, i, j, k;
  38801. var index;
  38802. var offset = 0;
  38803. var output;
  38804. var numComponents = this.components.length;
  38805. var dataLength = width * height * numComponents;
  38806. var data = new Uint8Array(dataLength);
  38807. var xScaleBlockOffset = new Uint32Array(width);
  38808. var mask3LSB = 0xfffffff8; // used to clear the 3 LSBs
  38809. for (i = 0; i < numComponents; i++) {
  38810. component = this.components[i];
  38811. componentScaleX = component.scaleX * scaleX;
  38812. componentScaleY = component.scaleY * scaleY;
  38813. offset = i;
  38814. output = component.output;
  38815. blocksPerScanline = (component.blocksPerLine + 1) << 3;
  38816. // precalculate the xScaleBlockOffset
  38817. for (x = 0; x < width; x++) {
  38818. j = 0 | (x * componentScaleX);
  38819. xScaleBlockOffset[x] = ((j & mask3LSB) << 3) | (j & 7);
  38820. }
  38821. // linearize the blocks of the component
  38822. for (y = 0; y < height; y++) {
  38823. j = 0 | (y * componentScaleY);
  38824. index = blocksPerScanline * (j & mask3LSB) | ((j & 7) << 3);
  38825. for (x = 0; x < width; x++) {
  38826. data[offset] = output[index + xScaleBlockOffset[x]];
  38827. offset += numComponents;
  38828. }
  38829. }
  38830. }
  38831. // decodeTransform contains pairs of multiplier (-256..256) and additive
  38832. var transform = this.decodeTransform;
  38833. if (transform) {
  38834. for (i = 0; i < dataLength;) {
  38835. for (j = 0, k = 0; j < numComponents; j++, i++, k += 2) {
  38836. data[i] = ((data[i] * transform[k]) >> 8) + transform[k + 1];
  38837. }
  38838. }
  38839. }
  38840. return data;
  38841. },
  38842. _isColorConversionNeeded: function isColorConversionNeeded() {
  38843. if (this.adobe && this.adobe.transformCode) {
  38844. // The adobe transform marker overrides any previous setting
  38845. return true;
  38846. } else if (this.numComponents === 3) {
  38847. return true;
  38848. } else {
  38849. return false;
  38850. }
  38851. },
  38852. _convertYccToRgb: function convertYccToRgb(data) {
  38853. var Y, Cb, Cr;
  38854. for (var i = 0, length = data.length; i < length; i += 3) {
  38855. Y = data[i ];
  38856. Cb = data[i + 1];
  38857. Cr = data[i + 2];
  38858. data[i ] = clamp0to255(Y - 179.456 + 1.402 * Cr);
  38859. data[i + 1] = clamp0to255(Y + 135.459 - 0.344 * Cb - 0.714 * Cr);
  38860. data[i + 2] = clamp0to255(Y - 226.816 + 1.772 * Cb);
  38861. }
  38862. return data;
  38863. },
  38864. _convertYcckToRgb: function convertYcckToRgb(data) {
  38865. var Y, Cb, Cr, k;
  38866. var offset = 0;
  38867. for (var i = 0, length = data.length; i < length; i += 4) {
  38868. Y = data[i];
  38869. Cb = data[i + 1];
  38870. Cr = data[i + 2];
  38871. k = data[i + 3];
  38872. var r = -122.67195406894 +
  38873. Cb * (-6.60635669420364e-5 * Cb + 0.000437130475926232 * Cr -
  38874. 5.4080610064599e-5 * Y + 0.00048449797120281 * k -
  38875. 0.154362151871126) +
  38876. Cr * (-0.000957964378445773 * Cr + 0.000817076911346625 * Y -
  38877. 0.00477271405408747 * k + 1.53380253221734) +
  38878. Y * (0.000961250184130688 * Y - 0.00266257332283933 * k +
  38879. 0.48357088451265) +
  38880. k * (-0.000336197177618394 * k + 0.484791561490776);
  38881. var g = 107.268039397724 +
  38882. Cb * (2.19927104525741e-5 * Cb - 0.000640992018297945 * Cr +
  38883. 0.000659397001245577 * Y + 0.000426105652938837 * k -
  38884. 0.176491792462875) +
  38885. Cr * (-0.000778269941513683 * Cr + 0.00130872261408275 * Y +
  38886. 0.000770482631801132 * k - 0.151051492775562) +
  38887. Y * (0.00126935368114843 * Y - 0.00265090189010898 * k +
  38888. 0.25802910206845) +
  38889. k * (-0.000318913117588328 * k - 0.213742400323665);
  38890. var b = -20.810012546947 +
  38891. Cb * (-0.000570115196973677 * Cb - 2.63409051004589e-5 * Cr +
  38892. 0.0020741088115012 * Y - 0.00288260236853442 * k +
  38893. 0.814272968359295) +
  38894. Cr * (-1.53496057440975e-5 * Cr - 0.000132689043961446 * Y +
  38895. 0.000560833691242812 * k - 0.195152027534049) +
  38896. Y * (0.00174418132927582 * Y - 0.00255243321439347 * k +
  38897. 0.116935020465145) +
  38898. k * (-0.000343531996510555 * k + 0.24165260232407);
  38899. data[offset++] = clamp0to255(r);
  38900. data[offset++] = clamp0to255(g);
  38901. data[offset++] = clamp0to255(b);
  38902. }
  38903. return data;
  38904. },
  38905. _convertYcckToCmyk: function convertYcckToCmyk(data) {
  38906. var Y, Cb, Cr;
  38907. for (var i = 0, length = data.length; i < length; i += 4) {
  38908. Y = data[i];
  38909. Cb = data[i + 1];
  38910. Cr = data[i + 2];
  38911. data[i ] = clamp0to255(434.456 - Y - 1.402 * Cr);
  38912. data[i + 1] = clamp0to255(119.541 - Y + 0.344 * Cb + 0.714 * Cr);
  38913. data[i + 2] = clamp0to255(481.816 - Y - 1.772 * Cb);
  38914. // K in data[i + 3] is unchanged
  38915. }
  38916. return data;
  38917. },
  38918. _convertCmykToRgb: function convertCmykToRgb(data) {
  38919. var c, m, y, k;
  38920. var offset = 0;
  38921. var min = -255 * 255 * 255;
  38922. var scale = 1 / 255 / 255;
  38923. for (var i = 0, length = data.length; i < length; i += 4) {
  38924. c = data[i];
  38925. m = data[i + 1];
  38926. y = data[i + 2];
  38927. k = data[i + 3];
  38928. var r =
  38929. c * (-4.387332384609988 * c + 54.48615194189176 * m +
  38930. 18.82290502165302 * y + 212.25662451639585 * k -
  38931. 72734.4411664936) +
  38932. m * (1.7149763477362134 * m - 5.6096736904047315 * y -
  38933. 17.873870861415444 * k - 1401.7366389350734) +
  38934. y * (-2.5217340131683033 * y - 21.248923337353073 * k +
  38935. 4465.541406466231) -
  38936. k * (21.86122147463605 * k + 48317.86113160301);
  38937. var g =
  38938. c * (8.841041422036149 * c + 60.118027045597366 * m +
  38939. 6.871425592049007 * y + 31.159100130055922 * k -
  38940. 20220.756542821975) +
  38941. m * (-15.310361306967817 * m + 17.575251261109482 * y +
  38942. 131.35250912493976 * k - 48691.05921601825) +
  38943. y * (4.444339102852739 * y + 9.8632861493405 * k -
  38944. 6341.191035517494) -
  38945. k * (20.737325471181034 * k + 47890.15695978492);
  38946. var b =
  38947. c * (0.8842522430003296 * c + 8.078677503112928 * m +
  38948. 30.89978309703729 * y - 0.23883238689178934 * k -
  38949. 3616.812083916688) +
  38950. m * (10.49593273432072 * m + 63.02378494754052 * y +
  38951. 50.606957656360734 * k - 28620.90484698408) +
  38952. y * (0.03296041114873217 * y + 115.60384449646641 * k -
  38953. 49363.43385999684) -
  38954. k * (22.33816807309886 * k + 45932.16563550634);
  38955. data[offset++] = r >= 0 ? 255 : r <= min ? 0 : 255 + r * scale | 0;
  38956. data[offset++] = g >= 0 ? 255 : g <= min ? 0 : 255 + g * scale | 0;
  38957. data[offset++] = b >= 0 ? 255 : b <= min ? 0 : 255 + b * scale | 0;
  38958. }
  38959. return data;
  38960. },
  38961. getData: function getData(width, height, forceRGBoutput) {
  38962. if (this.numComponents > 4) {
  38963. throw 'Unsupported color mode';
  38964. }
  38965. // type of data: Uint8Array(width * height * numComponents)
  38966. var data = this._getLinearizedBlockData(width, height);
  38967. if (this.numComponents === 3) {
  38968. return this._convertYccToRgb(data);
  38969. } else if (this.numComponents === 4) {
  38970. if (this._isColorConversionNeeded()) {
  38971. if (forceRGBoutput) {
  38972. return this._convertYcckToRgb(data);
  38973. } else {
  38974. return this._convertYcckToCmyk(data);
  38975. }
  38976. } else if (forceRGBoutput) {
  38977. return this._convertCmykToRgb(data);
  38978. }
  38979. }
  38980. return data;
  38981. }
  38982. };
  38983. return constructor;
  38984. })();
  38985. var JpxImage = (function JpxImageClosure() {
  38986. // Table E.1
  38987. var SubbandsGainLog2 = {
  38988. 'LL': 0,
  38989. 'LH': 1,
  38990. 'HL': 1,
  38991. 'HH': 2
  38992. };
  38993. function JpxImage() {
  38994. this.failOnCorruptedImage = false;
  38995. }
  38996. JpxImage.prototype = {
  38997. parse: function JpxImage_parse(data) {
  38998. var head = readUint16(data, 0);
  38999. // No box header, immediate start of codestream (SOC)
  39000. if (head === 0xFF4F) {
  39001. this.parseCodestream(data, 0, data.length);
  39002. return;
  39003. }
  39004. var position = 0, length = data.length;
  39005. while (position < length) {
  39006. var headerSize = 8;
  39007. var lbox = readUint32(data, position);
  39008. var tbox = readUint32(data, position + 4);
  39009. position += headerSize;
  39010. if (lbox === 1) {
  39011. // XLBox: read UInt64 according to spec.
  39012. // JavaScript's int precision of 53 bit should be sufficient here.
  39013. lbox = readUint32(data, position) * 4294967296 +
  39014. readUint32(data, position + 4);
  39015. position += 8;
  39016. headerSize += 8;
  39017. }
  39018. if (lbox === 0) {
  39019. lbox = length - position + headerSize;
  39020. }
  39021. if (lbox < headerSize) {
  39022. throw new Error('JPX Error: Invalid box field size');
  39023. }
  39024. var dataLength = lbox - headerSize;
  39025. var jumpDataLength = true;
  39026. switch (tbox) {
  39027. case 0x6A703268: // 'jp2h'
  39028. jumpDataLength = false; // parsing child boxes
  39029. break;
  39030. case 0x636F6C72: // 'colr'
  39031. // Colorspaces are not used, the CS from the PDF is used.
  39032. var method = data[position];
  39033. var precedence = data[position + 1];
  39034. var approximation = data[position + 2];
  39035. if (method === 1) {
  39036. // enumerated colorspace
  39037. var colorspace = readUint32(data, position + 3);
  39038. switch (colorspace) {
  39039. case 16: // this indicates a sRGB colorspace
  39040. case 17: // this indicates a grayscale colorspace
  39041. case 18: // this indicates a YUV colorspace
  39042. break;
  39043. default:
  39044. warn('Unknown colorspace ' + colorspace);
  39045. break;
  39046. }
  39047. } else if (method === 2) {
  39048. info('ICC profile not supported');
  39049. }
  39050. break;
  39051. case 0x6A703263: // 'jp2c'
  39052. this.parseCodestream(data, position, position + dataLength);
  39053. break;
  39054. case 0x6A502020: // 'jP\024\024'
  39055. if (0x0d0a870a !== readUint32(data, position)) {
  39056. warn('Invalid JP2 signature');
  39057. }
  39058. break;
  39059. // The following header types are valid but currently not used:
  39060. case 0x6A501A1A: // 'jP\032\032'
  39061. case 0x66747970: // 'ftyp'
  39062. case 0x72726571: // 'rreq'
  39063. case 0x72657320: // 'res '
  39064. case 0x69686472: // 'ihdr'
  39065. break;
  39066. default:
  39067. var headerType = String.fromCharCode((tbox >> 24) & 0xFF,
  39068. (tbox >> 16) & 0xFF,
  39069. (tbox >> 8) & 0xFF,
  39070. tbox & 0xFF);
  39071. warn('Unsupported header type ' + tbox + ' (' + headerType + ')');
  39072. break;
  39073. }
  39074. if (jumpDataLength) {
  39075. position += dataLength;
  39076. }
  39077. }
  39078. },
  39079. parseImageProperties: function JpxImage_parseImageProperties(stream) {
  39080. var newByte = stream.getByte();
  39081. while (newByte >= 0) {
  39082. var oldByte = newByte;
  39083. newByte = stream.getByte();
  39084. var code = (oldByte << 8) | newByte;
  39085. // Image and tile size (SIZ)
  39086. if (code === 0xFF51) {
  39087. stream.skip(4);
  39088. var Xsiz = stream.getInt32() >>> 0; // Byte 4
  39089. var Ysiz = stream.getInt32() >>> 0; // Byte 8
  39090. var XOsiz = stream.getInt32() >>> 0; // Byte 12
  39091. var YOsiz = stream.getInt32() >>> 0; // Byte 16
  39092. stream.skip(16);
  39093. var Csiz = stream.getUint16(); // Byte 36
  39094. this.width = Xsiz - XOsiz;
  39095. this.height = Ysiz - YOsiz;
  39096. this.componentsCount = Csiz;
  39097. // Results are always returned as Uint8Arrays
  39098. this.bitsPerComponent = 8;
  39099. return;
  39100. }
  39101. }
  39102. throw new Error('JPX Error: No size marker found in JPX stream');
  39103. },
  39104. parseCodestream: function JpxImage_parseCodestream(data, start, end) {
  39105. var context = {};
  39106. try {
  39107. var doNotRecover = false;
  39108. var position = start;
  39109. while (position + 1 < end) {
  39110. var code = readUint16(data, position);
  39111. position += 2;
  39112. var length = 0, j, sqcd, spqcds, spqcdSize, scalarExpounded, tile;
  39113. switch (code) {
  39114. case 0xFF4F: // Start of codestream (SOC)
  39115. context.mainHeader = true;
  39116. break;
  39117. case 0xFFD9: // End of codestream (EOC)
  39118. break;
  39119. case 0xFF51: // Image and tile size (SIZ)
  39120. length = readUint16(data, position);
  39121. var siz = {};
  39122. siz.Xsiz = readUint32(data, position + 4);
  39123. siz.Ysiz = readUint32(data, position + 8);
  39124. siz.XOsiz = readUint32(data, position + 12);
  39125. siz.YOsiz = readUint32(data, position + 16);
  39126. siz.XTsiz = readUint32(data, position + 20);
  39127. siz.YTsiz = readUint32(data, position + 24);
  39128. siz.XTOsiz = readUint32(data, position + 28);
  39129. siz.YTOsiz = readUint32(data, position + 32);
  39130. var componentsCount = readUint16(data, position + 36);
  39131. siz.Csiz = componentsCount;
  39132. var components = [];
  39133. j = position + 38;
  39134. for (var i = 0; i < componentsCount; i++) {
  39135. var component = {
  39136. precision: (data[j] & 0x7F) + 1,
  39137. isSigned: !!(data[j] & 0x80),
  39138. XRsiz: data[j + 1],
  39139. YRsiz: data[j + 1]
  39140. };
  39141. calculateComponentDimensions(component, siz);
  39142. components.push(component);
  39143. }
  39144. context.SIZ = siz;
  39145. context.components = components;
  39146. calculateTileGrids(context, components);
  39147. context.QCC = [];
  39148. context.COC = [];
  39149. break;
  39150. case 0xFF5C: // Quantization default (QCD)
  39151. length = readUint16(data, position);
  39152. var qcd = {};
  39153. j = position + 2;
  39154. sqcd = data[j++];
  39155. switch (sqcd & 0x1F) {
  39156. case 0:
  39157. spqcdSize = 8;
  39158. scalarExpounded = true;
  39159. break;
  39160. case 1:
  39161. spqcdSize = 16;
  39162. scalarExpounded = false;
  39163. break;
  39164. case 2:
  39165. spqcdSize = 16;
  39166. scalarExpounded = true;
  39167. break;
  39168. default:
  39169. throw new Error('JPX Error: Invalid SQcd value ' + sqcd);
  39170. }
  39171. qcd.noQuantization = (spqcdSize === 8);
  39172. qcd.scalarExpounded = scalarExpounded;
  39173. qcd.guardBits = sqcd >> 5;
  39174. spqcds = [];
  39175. while (j < length + position) {
  39176. var spqcd = {};
  39177. if (spqcdSize === 8) {
  39178. spqcd.epsilon = data[j++] >> 3;
  39179. spqcd.mu = 0;
  39180. } else {
  39181. spqcd.epsilon = data[j] >> 3;
  39182. spqcd.mu = ((data[j] & 0x7) << 8) | data[j + 1];
  39183. j += 2;
  39184. }
  39185. spqcds.push(spqcd);
  39186. }
  39187. qcd.SPqcds = spqcds;
  39188. if (context.mainHeader) {
  39189. context.QCD = qcd;
  39190. } else {
  39191. context.currentTile.QCD = qcd;
  39192. context.currentTile.QCC = [];
  39193. }
  39194. break;
  39195. case 0xFF5D: // Quantization component (QCC)
  39196. length = readUint16(data, position);
  39197. var qcc = {};
  39198. j = position + 2;
  39199. var cqcc;
  39200. if (context.SIZ.Csiz < 257) {
  39201. cqcc = data[j++];
  39202. } else {
  39203. cqcc = readUint16(data, j);
  39204. j += 2;
  39205. }
  39206. sqcd = data[j++];
  39207. switch (sqcd & 0x1F) {
  39208. case 0:
  39209. spqcdSize = 8;
  39210. scalarExpounded = true;
  39211. break;
  39212. case 1:
  39213. spqcdSize = 16;
  39214. scalarExpounded = false;
  39215. break;
  39216. case 2:
  39217. spqcdSize = 16;
  39218. scalarExpounded = true;
  39219. break;
  39220. default:
  39221. throw new Error('JPX Error: Invalid SQcd value ' + sqcd);
  39222. }
  39223. qcc.noQuantization = (spqcdSize === 8);
  39224. qcc.scalarExpounded = scalarExpounded;
  39225. qcc.guardBits = sqcd >> 5;
  39226. spqcds = [];
  39227. while (j < (length + position)) {
  39228. spqcd = {};
  39229. if (spqcdSize === 8) {
  39230. spqcd.epsilon = data[j++] >> 3;
  39231. spqcd.mu = 0;
  39232. } else {
  39233. spqcd.epsilon = data[j] >> 3;
  39234. spqcd.mu = ((data[j] & 0x7) << 8) | data[j + 1];
  39235. j += 2;
  39236. }
  39237. spqcds.push(spqcd);
  39238. }
  39239. qcc.SPqcds = spqcds;
  39240. if (context.mainHeader) {
  39241. context.QCC[cqcc] = qcc;
  39242. } else {
  39243. context.currentTile.QCC[cqcc] = qcc;
  39244. }
  39245. break;
  39246. case 0xFF52: // Coding style default (COD)
  39247. length = readUint16(data, position);
  39248. var cod = {};
  39249. j = position + 2;
  39250. var scod = data[j++];
  39251. cod.entropyCoderWithCustomPrecincts = !!(scod & 1);
  39252. cod.sopMarkerUsed = !!(scod & 2);
  39253. cod.ephMarkerUsed = !!(scod & 4);
  39254. cod.progressionOrder = data[j++];
  39255. cod.layersCount = readUint16(data, j);
  39256. j += 2;
  39257. cod.multipleComponentTransform = data[j++];
  39258. cod.decompositionLevelsCount = data[j++];
  39259. cod.xcb = (data[j++] & 0xF) + 2;
  39260. cod.ycb = (data[j++] & 0xF) + 2;
  39261. var blockStyle = data[j++];
  39262. cod.selectiveArithmeticCodingBypass = !!(blockStyle & 1);
  39263. cod.resetContextProbabilities = !!(blockStyle & 2);
  39264. cod.terminationOnEachCodingPass = !!(blockStyle & 4);
  39265. cod.verticalyStripe = !!(blockStyle & 8);
  39266. cod.predictableTermination = !!(blockStyle & 16);
  39267. cod.segmentationSymbolUsed = !!(blockStyle & 32);
  39268. cod.reversibleTransformation = data[j++];
  39269. if (cod.entropyCoderWithCustomPrecincts) {
  39270. var precinctsSizes = [];
  39271. while (j < length + position) {
  39272. var precinctsSize = data[j++];
  39273. precinctsSizes.push({
  39274. PPx: precinctsSize & 0xF,
  39275. PPy: precinctsSize >> 4
  39276. });
  39277. }
  39278. cod.precinctsSizes = precinctsSizes;
  39279. }
  39280. var unsupported = [];
  39281. if (cod.selectiveArithmeticCodingBypass) {
  39282. unsupported.push('selectiveArithmeticCodingBypass');
  39283. }
  39284. if (cod.resetContextProbabilities) {
  39285. unsupported.push('resetContextProbabilities');
  39286. }
  39287. if (cod.terminationOnEachCodingPass) {
  39288. unsupported.push('terminationOnEachCodingPass');
  39289. }
  39290. if (cod.verticalyStripe) {
  39291. unsupported.push('verticalyStripe');
  39292. }
  39293. if (cod.predictableTermination) {
  39294. unsupported.push('predictableTermination');
  39295. }
  39296. if (unsupported.length > 0) {
  39297. doNotRecover = true;
  39298. throw new Error('JPX Error: Unsupported COD options (' +
  39299. unsupported.join(', ') + ')');
  39300. }
  39301. if (context.mainHeader) {
  39302. context.COD = cod;
  39303. } else {
  39304. context.currentTile.COD = cod;
  39305. context.currentTile.COC = [];
  39306. }
  39307. break;
  39308. case 0xFF90: // Start of tile-part (SOT)
  39309. length = readUint16(data, position);
  39310. tile = {};
  39311. tile.index = readUint16(data, position + 2);
  39312. tile.length = readUint32(data, position + 4);
  39313. tile.dataEnd = tile.length + position - 2;
  39314. tile.partIndex = data[position + 8];
  39315. tile.partsCount = data[position + 9];
  39316. context.mainHeader = false;
  39317. if (tile.partIndex === 0) {
  39318. // reset component specific settings
  39319. tile.COD = context.COD;
  39320. tile.COC = context.COC.slice(0); // clone of the global COC
  39321. tile.QCD = context.QCD;
  39322. tile.QCC = context.QCC.slice(0); // clone of the global COC
  39323. }
  39324. context.currentTile = tile;
  39325. break;
  39326. case 0xFF93: // Start of data (SOD)
  39327. tile = context.currentTile;
  39328. if (tile.partIndex === 0) {
  39329. initializeTile(context, tile.index);
  39330. buildPackets(context);
  39331. }
  39332. // moving to the end of the data
  39333. length = tile.dataEnd - position;
  39334. parseTilePackets(context, data, position, length);
  39335. break;
  39336. case 0xFF55: // Tile-part lengths, main header (TLM)
  39337. case 0xFF57: // Packet length, main header (PLM)
  39338. case 0xFF58: // Packet length, tile-part header (PLT)
  39339. case 0xFF64: // Comment (COM)
  39340. length = readUint16(data, position);
  39341. // skipping content
  39342. break;
  39343. case 0xFF53: // Coding style component (COC)
  39344. throw new Error('JPX Error: Codestream code 0xFF53 (COC) is ' +
  39345. 'not implemented');
  39346. default:
  39347. throw new Error('JPX Error: Unknown codestream code: ' +
  39348. code.toString(16));
  39349. }
  39350. position += length;
  39351. }
  39352. } catch (e) {
  39353. if (doNotRecover || this.failOnCorruptedImage) {
  39354. throw e;
  39355. } else {
  39356. warn('Trying to recover from ' + e.message);
  39357. }
  39358. }
  39359. this.tiles = transformComponents(context);
  39360. this.width = context.SIZ.Xsiz - context.SIZ.XOsiz;
  39361. this.height = context.SIZ.Ysiz - context.SIZ.YOsiz;
  39362. this.componentsCount = context.SIZ.Csiz;
  39363. }
  39364. };
  39365. function calculateComponentDimensions(component, siz) {
  39366. // Section B.2 Component mapping
  39367. component.x0 = Math.ceil(siz.XOsiz / component.XRsiz);
  39368. component.x1 = Math.ceil(siz.Xsiz / component.XRsiz);
  39369. component.y0 = Math.ceil(siz.YOsiz / component.YRsiz);
  39370. component.y1 = Math.ceil(siz.Ysiz / component.YRsiz);
  39371. component.width = component.x1 - component.x0;
  39372. component.height = component.y1 - component.y0;
  39373. }
  39374. function calculateTileGrids(context, components) {
  39375. var siz = context.SIZ;
  39376. // Section B.3 Division into tile and tile-components
  39377. var tile, tiles = [];
  39378. var numXtiles = Math.ceil((siz.Xsiz - siz.XTOsiz) / siz.XTsiz);
  39379. var numYtiles = Math.ceil((siz.Ysiz - siz.YTOsiz) / siz.YTsiz);
  39380. for (var q = 0; q < numYtiles; q++) {
  39381. for (var p = 0; p < numXtiles; p++) {
  39382. tile = {};
  39383. tile.tx0 = Math.max(siz.XTOsiz + p * siz.XTsiz, siz.XOsiz);
  39384. tile.ty0 = Math.max(siz.YTOsiz + q * siz.YTsiz, siz.YOsiz);
  39385. tile.tx1 = Math.min(siz.XTOsiz + (p + 1) * siz.XTsiz, siz.Xsiz);
  39386. tile.ty1 = Math.min(siz.YTOsiz + (q + 1) * siz.YTsiz, siz.Ysiz);
  39387. tile.width = tile.tx1 - tile.tx0;
  39388. tile.height = tile.ty1 - tile.ty0;
  39389. tile.components = [];
  39390. tiles.push(tile);
  39391. }
  39392. }
  39393. context.tiles = tiles;
  39394. var componentsCount = siz.Csiz;
  39395. for (var i = 0, ii = componentsCount; i < ii; i++) {
  39396. var component = components[i];
  39397. for (var j = 0, jj = tiles.length; j < jj; j++) {
  39398. var tileComponent = {};
  39399. tile = tiles[j];
  39400. tileComponent.tcx0 = Math.ceil(tile.tx0 / component.XRsiz);
  39401. tileComponent.tcy0 = Math.ceil(tile.ty0 / component.YRsiz);
  39402. tileComponent.tcx1 = Math.ceil(tile.tx1 / component.XRsiz);
  39403. tileComponent.tcy1 = Math.ceil(tile.ty1 / component.YRsiz);
  39404. tileComponent.width = tileComponent.tcx1 - tileComponent.tcx0;
  39405. tileComponent.height = tileComponent.tcy1 - tileComponent.tcy0;
  39406. tile.components[i] = tileComponent;
  39407. }
  39408. }
  39409. }
  39410. function getBlocksDimensions(context, component, r) {
  39411. var codOrCoc = component.codingStyleParameters;
  39412. var result = {};
  39413. if (!codOrCoc.entropyCoderWithCustomPrecincts) {
  39414. result.PPx = 15;
  39415. result.PPy = 15;
  39416. } else {
  39417. result.PPx = codOrCoc.precinctsSizes[r].PPx;
  39418. result.PPy = codOrCoc.precinctsSizes[r].PPy;
  39419. }
  39420. // calculate codeblock size as described in section B.7
  39421. result.xcb_ = (r > 0 ? Math.min(codOrCoc.xcb, result.PPx - 1) :
  39422. Math.min(codOrCoc.xcb, result.PPx));
  39423. result.ycb_ = (r > 0 ? Math.min(codOrCoc.ycb, result.PPy - 1) :
  39424. Math.min(codOrCoc.ycb, result.PPy));
  39425. return result;
  39426. }
  39427. function buildPrecincts(context, resolution, dimensions) {
  39428. // Section B.6 Division resolution to precincts
  39429. var precinctWidth = 1 << dimensions.PPx;
  39430. var precinctHeight = 1 << dimensions.PPy;
  39431. // Jasper introduces codeblock groups for mapping each subband codeblocks
  39432. // to precincts. Precinct partition divides a resolution according to width
  39433. // and height parameters. The subband that belongs to the resolution level
  39434. // has a different size than the level, unless it is the zero resolution.
  39435. // From Jasper documentation: jpeg2000.pdf, section K: Tier-2 coding:
  39436. // The precinct partitioning for a particular subband is derived from a
  39437. // partitioning of its parent LL band (i.e., the LL band at the next higher
  39438. // resolution level)... The LL band associated with each resolution level is
  39439. // divided into precincts... Each of the resulting precinct regions is then
  39440. // mapped into its child subbands (if any) at the next lower resolution
  39441. // level. This is accomplished by using the coordinate transformation
  39442. // (u, v) = (ceil(x/2), ceil(y/2)) where (x, y) and (u, v) are the
  39443. // coordinates of a point in the LL band and child subband, respectively.
  39444. var isZeroRes = resolution.resLevel === 0;
  39445. var precinctWidthInSubband = 1 << (dimensions.PPx + (isZeroRes ? 0 : -1));
  39446. var precinctHeightInSubband = 1 << (dimensions.PPy + (isZeroRes ? 0 : -1));
  39447. var numprecinctswide = (resolution.trx1 > resolution.trx0 ?
  39448. Math.ceil(resolution.trx1 / precinctWidth) -
  39449. Math.floor(resolution.trx0 / precinctWidth) : 0);
  39450. var numprecinctshigh = (resolution.try1 > resolution.try0 ?
  39451. Math.ceil(resolution.try1 / precinctHeight) -
  39452. Math.floor(resolution.try0 / precinctHeight) : 0);
  39453. var numprecincts = numprecinctswide * numprecinctshigh;
  39454. resolution.precinctParameters = {
  39455. precinctWidth: precinctWidth,
  39456. precinctHeight: precinctHeight,
  39457. numprecinctswide: numprecinctswide,
  39458. numprecinctshigh: numprecinctshigh,
  39459. numprecincts: numprecincts,
  39460. precinctWidthInSubband: precinctWidthInSubband,
  39461. precinctHeightInSubband: precinctHeightInSubband
  39462. };
  39463. }
  39464. function buildCodeblocks(context, subband, dimensions) {
  39465. // Section B.7 Division sub-band into code-blocks
  39466. var xcb_ = dimensions.xcb_;
  39467. var ycb_ = dimensions.ycb_;
  39468. var codeblockWidth = 1 << xcb_;
  39469. var codeblockHeight = 1 << ycb_;
  39470. var cbx0 = subband.tbx0 >> xcb_;
  39471. var cby0 = subband.tby0 >> ycb_;
  39472. var cbx1 = (subband.tbx1 + codeblockWidth - 1) >> xcb_;
  39473. var cby1 = (subband.tby1 + codeblockHeight - 1) >> ycb_;
  39474. var precinctParameters = subband.resolution.precinctParameters;
  39475. var codeblocks = [];
  39476. var precincts = [];
  39477. var i, j, codeblock, precinctNumber;
  39478. for (j = cby0; j < cby1; j++) {
  39479. for (i = cbx0; i < cbx1; i++) {
  39480. codeblock = {
  39481. cbx: i,
  39482. cby: j,
  39483. tbx0: codeblockWidth * i,
  39484. tby0: codeblockHeight * j,
  39485. tbx1: codeblockWidth * (i + 1),
  39486. tby1: codeblockHeight * (j + 1)
  39487. };
  39488. codeblock.tbx0_ = Math.max(subband.tbx0, codeblock.tbx0);
  39489. codeblock.tby0_ = Math.max(subband.tby0, codeblock.tby0);
  39490. codeblock.tbx1_ = Math.min(subband.tbx1, codeblock.tbx1);
  39491. codeblock.tby1_ = Math.min(subband.tby1, codeblock.tby1);
  39492. // Calculate precinct number for this codeblock, codeblock position
  39493. // should be relative to its subband, use actual dimension and position
  39494. // See comment about codeblock group width and height
  39495. var pi = Math.floor((codeblock.tbx0_ - subband.tbx0) /
  39496. precinctParameters.precinctWidthInSubband);
  39497. var pj = Math.floor((codeblock.tby0_ - subband.tby0) /
  39498. precinctParameters.precinctHeightInSubband);
  39499. precinctNumber = pi + (pj * precinctParameters.numprecinctswide);
  39500. codeblock.precinctNumber = precinctNumber;
  39501. codeblock.subbandType = subband.type;
  39502. codeblock.Lblock = 3;
  39503. if (codeblock.tbx1_ <= codeblock.tbx0_ ||
  39504. codeblock.tby1_ <= codeblock.tby0_) {
  39505. continue;
  39506. }
  39507. codeblocks.push(codeblock);
  39508. // building precinct for the sub-band
  39509. var precinct = precincts[precinctNumber];
  39510. if (precinct !== undefined) {
  39511. if (i < precinct.cbxMin) {
  39512. precinct.cbxMin = i;
  39513. } else if (i > precinct.cbxMax) {
  39514. precinct.cbxMax = i;
  39515. }
  39516. if (j < precinct.cbyMin) {
  39517. precinct.cbxMin = j;
  39518. } else if (j > precinct.cbyMax) {
  39519. precinct.cbyMax = j;
  39520. }
  39521. } else {
  39522. precincts[precinctNumber] = precinct = {
  39523. cbxMin: i,
  39524. cbyMin: j,
  39525. cbxMax: i,
  39526. cbyMax: j
  39527. };
  39528. }
  39529. codeblock.precinct = precinct;
  39530. }
  39531. }
  39532. subband.codeblockParameters = {
  39533. codeblockWidth: xcb_,
  39534. codeblockHeight: ycb_,
  39535. numcodeblockwide: cbx1 - cbx0 + 1,
  39536. numcodeblockhigh: cby1 - cby0 + 1
  39537. };
  39538. subband.codeblocks = codeblocks;
  39539. subband.precincts = precincts;
  39540. }
  39541. function createPacket(resolution, precinctNumber, layerNumber) {
  39542. var precinctCodeblocks = [];
  39543. // Section B.10.8 Order of info in packet
  39544. var subbands = resolution.subbands;
  39545. // sub-bands already ordered in 'LL', 'HL', 'LH', and 'HH' sequence
  39546. for (var i = 0, ii = subbands.length; i < ii; i++) {
  39547. var subband = subbands[i];
  39548. var codeblocks = subband.codeblocks;
  39549. for (var j = 0, jj = codeblocks.length; j < jj; j++) {
  39550. var codeblock = codeblocks[j];
  39551. if (codeblock.precinctNumber !== precinctNumber) {
  39552. continue;
  39553. }
  39554. precinctCodeblocks.push(codeblock);
  39555. }
  39556. }
  39557. return {
  39558. layerNumber: layerNumber,
  39559. codeblocks: precinctCodeblocks
  39560. };
  39561. }
  39562. function LayerResolutionComponentPositionIterator(context) {
  39563. var siz = context.SIZ;
  39564. var tileIndex = context.currentTile.index;
  39565. var tile = context.tiles[tileIndex];
  39566. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  39567. var componentsCount = siz.Csiz;
  39568. var maxDecompositionLevelsCount = 0;
  39569. for (var q = 0; q < componentsCount; q++) {
  39570. maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount,
  39571. tile.components[q].codingStyleParameters.decompositionLevelsCount);
  39572. }
  39573. var l = 0, r = 0, i = 0, k = 0;
  39574. this.nextPacket = function JpxImage_nextPacket() {
  39575. // Section B.12.1.1 Layer-resolution-component-position
  39576. for (; l < layersCount; l++) {
  39577. for (; r <= maxDecompositionLevelsCount; r++) {
  39578. for (; i < componentsCount; i++) {
  39579. var component = tile.components[i];
  39580. if (r > component.codingStyleParameters.decompositionLevelsCount) {
  39581. continue;
  39582. }
  39583. var resolution = component.resolutions[r];
  39584. var numprecincts = resolution.precinctParameters.numprecincts;
  39585. for (; k < numprecincts;) {
  39586. var packet = createPacket(resolution, k, l);
  39587. k++;
  39588. return packet;
  39589. }
  39590. k = 0;
  39591. }
  39592. i = 0;
  39593. }
  39594. r = 0;
  39595. }
  39596. throw new Error('JPX Error: Out of packets');
  39597. };
  39598. }
  39599. function ResolutionLayerComponentPositionIterator(context) {
  39600. var siz = context.SIZ;
  39601. var tileIndex = context.currentTile.index;
  39602. var tile = context.tiles[tileIndex];
  39603. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  39604. var componentsCount = siz.Csiz;
  39605. var maxDecompositionLevelsCount = 0;
  39606. for (var q = 0; q < componentsCount; q++) {
  39607. maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount,
  39608. tile.components[q].codingStyleParameters.decompositionLevelsCount);
  39609. }
  39610. var r = 0, l = 0, i = 0, k = 0;
  39611. this.nextPacket = function JpxImage_nextPacket() {
  39612. // Section B.12.1.2 Resolution-layer-component-position
  39613. for (; r <= maxDecompositionLevelsCount; r++) {
  39614. for (; l < layersCount; l++) {
  39615. for (; i < componentsCount; i++) {
  39616. var component = tile.components[i];
  39617. if (r > component.codingStyleParameters.decompositionLevelsCount) {
  39618. continue;
  39619. }
  39620. var resolution = component.resolutions[r];
  39621. var numprecincts = resolution.precinctParameters.numprecincts;
  39622. for (; k < numprecincts;) {
  39623. var packet = createPacket(resolution, k, l);
  39624. k++;
  39625. return packet;
  39626. }
  39627. k = 0;
  39628. }
  39629. i = 0;
  39630. }
  39631. l = 0;
  39632. }
  39633. throw new Error('JPX Error: Out of packets');
  39634. };
  39635. }
  39636. function ResolutionPositionComponentLayerIterator(context) {
  39637. var siz = context.SIZ;
  39638. var tileIndex = context.currentTile.index;
  39639. var tile = context.tiles[tileIndex];
  39640. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  39641. var componentsCount = siz.Csiz;
  39642. var l, r, c, p;
  39643. var maxDecompositionLevelsCount = 0;
  39644. for (c = 0; c < componentsCount; c++) {
  39645. var component = tile.components[c];
  39646. maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount,
  39647. component.codingStyleParameters.decompositionLevelsCount);
  39648. }
  39649. var maxNumPrecinctsInLevel = new Int32Array(
  39650. maxDecompositionLevelsCount + 1);
  39651. for (r = 0; r <= maxDecompositionLevelsCount; ++r) {
  39652. var maxNumPrecincts = 0;
  39653. for (c = 0; c < componentsCount; ++c) {
  39654. var resolutions = tile.components[c].resolutions;
  39655. if (r < resolutions.length) {
  39656. maxNumPrecincts = Math.max(maxNumPrecincts,
  39657. resolutions[r].precinctParameters.numprecincts);
  39658. }
  39659. }
  39660. maxNumPrecinctsInLevel[r] = maxNumPrecincts;
  39661. }
  39662. l = 0;
  39663. r = 0;
  39664. c = 0;
  39665. p = 0;
  39666. this.nextPacket = function JpxImage_nextPacket() {
  39667. // Section B.12.1.3 Resolution-position-component-layer
  39668. for (; r <= maxDecompositionLevelsCount; r++) {
  39669. for (; p < maxNumPrecinctsInLevel[r]; p++) {
  39670. for (; c < componentsCount; c++) {
  39671. var component = tile.components[c];
  39672. if (r > component.codingStyleParameters.decompositionLevelsCount) {
  39673. continue;
  39674. }
  39675. var resolution = component.resolutions[r];
  39676. var numprecincts = resolution.precinctParameters.numprecincts;
  39677. if (p >= numprecincts) {
  39678. continue;
  39679. }
  39680. for (; l < layersCount;) {
  39681. var packet = createPacket(resolution, p, l);
  39682. l++;
  39683. return packet;
  39684. }
  39685. l = 0;
  39686. }
  39687. c = 0;
  39688. }
  39689. p = 0;
  39690. }
  39691. throw new Error('JPX Error: Out of packets');
  39692. };
  39693. }
  39694. function PositionComponentResolutionLayerIterator(context) {
  39695. var siz = context.SIZ;
  39696. var tileIndex = context.currentTile.index;
  39697. var tile = context.tiles[tileIndex];
  39698. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  39699. var componentsCount = siz.Csiz;
  39700. var precinctsSizes = getPrecinctSizesInImageScale(tile);
  39701. var precinctsIterationSizes = precinctsSizes;
  39702. var l = 0, r = 0, c = 0, px = 0, py = 0;
  39703. this.nextPacket = function JpxImage_nextPacket() {
  39704. // Section B.12.1.4 Position-component-resolution-layer
  39705. for (; py < precinctsIterationSizes.maxNumHigh; py++) {
  39706. for (; px < precinctsIterationSizes.maxNumWide; px++) {
  39707. for (; c < componentsCount; c++) {
  39708. var component = tile.components[c];
  39709. var decompositionLevelsCount =
  39710. component.codingStyleParameters.decompositionLevelsCount;
  39711. for (; r <= decompositionLevelsCount; r++) {
  39712. var resolution = component.resolutions[r];
  39713. var sizeInImageScale =
  39714. precinctsSizes.components[c].resolutions[r];
  39715. var k = getPrecinctIndexIfExist(
  39716. px,
  39717. py,
  39718. sizeInImageScale,
  39719. precinctsIterationSizes,
  39720. resolution);
  39721. if (k === null) {
  39722. continue;
  39723. }
  39724. for (; l < layersCount;) {
  39725. var packet = createPacket(resolution, k, l);
  39726. l++;
  39727. return packet;
  39728. }
  39729. l = 0;
  39730. }
  39731. r = 0;
  39732. }
  39733. c = 0;
  39734. }
  39735. px = 0;
  39736. }
  39737. throw new Error('JPX Error: Out of packets');
  39738. };
  39739. }
  39740. function ComponentPositionResolutionLayerIterator(context) {
  39741. var siz = context.SIZ;
  39742. var tileIndex = context.currentTile.index;
  39743. var tile = context.tiles[tileIndex];
  39744. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  39745. var componentsCount = siz.Csiz;
  39746. var precinctsSizes = getPrecinctSizesInImageScale(tile);
  39747. var l = 0, r = 0, c = 0, px = 0, py = 0;
  39748. this.nextPacket = function JpxImage_nextPacket() {
  39749. // Section B.12.1.5 Component-position-resolution-layer
  39750. for (; c < componentsCount; ++c) {
  39751. var component = tile.components[c];
  39752. var precinctsIterationSizes = precinctsSizes.components[c];
  39753. var decompositionLevelsCount =
  39754. component.codingStyleParameters.decompositionLevelsCount;
  39755. for (; py < precinctsIterationSizes.maxNumHigh; py++) {
  39756. for (; px < precinctsIterationSizes.maxNumWide; px++) {
  39757. for (; r <= decompositionLevelsCount; r++) {
  39758. var resolution = component.resolutions[r];
  39759. var sizeInImageScale = precinctsIterationSizes.resolutions[r];
  39760. var k = getPrecinctIndexIfExist(
  39761. px,
  39762. py,
  39763. sizeInImageScale,
  39764. precinctsIterationSizes,
  39765. resolution);
  39766. if (k === null) {
  39767. continue;
  39768. }
  39769. for (; l < layersCount;) {
  39770. var packet = createPacket(resolution, k, l);
  39771. l++;
  39772. return packet;
  39773. }
  39774. l = 0;
  39775. }
  39776. r = 0;
  39777. }
  39778. px = 0;
  39779. }
  39780. py = 0;
  39781. }
  39782. throw new Error('JPX Error: Out of packets');
  39783. };
  39784. }
  39785. function getPrecinctIndexIfExist(
  39786. pxIndex, pyIndex, sizeInImageScale, precinctIterationSizes, resolution) {
  39787. var posX = pxIndex * precinctIterationSizes.minWidth;
  39788. var posY = pyIndex * precinctIterationSizes.minHeight;
  39789. if (posX % sizeInImageScale.width !== 0 ||
  39790. posY % sizeInImageScale.height !== 0) {
  39791. return null;
  39792. }
  39793. var startPrecinctRowIndex =
  39794. (posY / sizeInImageScale.width) *
  39795. resolution.precinctParameters.numprecinctswide;
  39796. return (posX / sizeInImageScale.height) + startPrecinctRowIndex;
  39797. }
  39798. function getPrecinctSizesInImageScale(tile) {
  39799. var componentsCount = tile.components.length;
  39800. var minWidth = Number.MAX_VALUE;
  39801. var minHeight = Number.MAX_VALUE;
  39802. var maxNumWide = 0;
  39803. var maxNumHigh = 0;
  39804. var sizePerComponent = new Array(componentsCount);
  39805. for (var c = 0; c < componentsCount; c++) {
  39806. var component = tile.components[c];
  39807. var decompositionLevelsCount =
  39808. component.codingStyleParameters.decompositionLevelsCount;
  39809. var sizePerResolution = new Array(decompositionLevelsCount + 1);
  39810. var minWidthCurrentComponent = Number.MAX_VALUE;
  39811. var minHeightCurrentComponent = Number.MAX_VALUE;
  39812. var maxNumWideCurrentComponent = 0;
  39813. var maxNumHighCurrentComponent = 0;
  39814. var scale = 1;
  39815. for (var r = decompositionLevelsCount; r >= 0; --r) {
  39816. var resolution = component.resolutions[r];
  39817. var widthCurrentResolution =
  39818. scale * resolution.precinctParameters.precinctWidth;
  39819. var heightCurrentResolution =
  39820. scale * resolution.precinctParameters.precinctHeight;
  39821. minWidthCurrentComponent = Math.min(
  39822. minWidthCurrentComponent,
  39823. widthCurrentResolution);
  39824. minHeightCurrentComponent = Math.min(
  39825. minHeightCurrentComponent,
  39826. heightCurrentResolution);
  39827. maxNumWideCurrentComponent = Math.max(maxNumWideCurrentComponent,
  39828. resolution.precinctParameters.numprecinctswide);
  39829. maxNumHighCurrentComponent = Math.max(maxNumHighCurrentComponent,
  39830. resolution.precinctParameters.numprecinctshigh);
  39831. sizePerResolution[r] = {
  39832. width: widthCurrentResolution,
  39833. height: heightCurrentResolution
  39834. };
  39835. scale <<= 1;
  39836. }
  39837. minWidth = Math.min(minWidth, minWidthCurrentComponent);
  39838. minHeight = Math.min(minHeight, minHeightCurrentComponent);
  39839. maxNumWide = Math.max(maxNumWide, maxNumWideCurrentComponent);
  39840. maxNumHigh = Math.max(maxNumHigh, maxNumHighCurrentComponent);
  39841. sizePerComponent[c] = {
  39842. resolutions: sizePerResolution,
  39843. minWidth: minWidthCurrentComponent,
  39844. minHeight: minHeightCurrentComponent,
  39845. maxNumWide: maxNumWideCurrentComponent,
  39846. maxNumHigh: maxNumHighCurrentComponent
  39847. };
  39848. }
  39849. return {
  39850. components: sizePerComponent,
  39851. minWidth: minWidth,
  39852. minHeight: minHeight,
  39853. maxNumWide: maxNumWide,
  39854. maxNumHigh: maxNumHigh
  39855. };
  39856. }
  39857. function buildPackets(context) {
  39858. var siz = context.SIZ;
  39859. var tileIndex = context.currentTile.index;
  39860. var tile = context.tiles[tileIndex];
  39861. var componentsCount = siz.Csiz;
  39862. // Creating resolutions and sub-bands for each component
  39863. for (var c = 0; c < componentsCount; c++) {
  39864. var component = tile.components[c];
  39865. var decompositionLevelsCount =
  39866. component.codingStyleParameters.decompositionLevelsCount;
  39867. // Section B.5 Resolution levels and sub-bands
  39868. var resolutions = [];
  39869. var subbands = [];
  39870. for (var r = 0; r <= decompositionLevelsCount; r++) {
  39871. var blocksDimensions = getBlocksDimensions(context, component, r);
  39872. var resolution = {};
  39873. var scale = 1 << (decompositionLevelsCount - r);
  39874. resolution.trx0 = Math.ceil(component.tcx0 / scale);
  39875. resolution.try0 = Math.ceil(component.tcy0 / scale);
  39876. resolution.trx1 = Math.ceil(component.tcx1 / scale);
  39877. resolution.try1 = Math.ceil(component.tcy1 / scale);
  39878. resolution.resLevel = r;
  39879. buildPrecincts(context, resolution, blocksDimensions);
  39880. resolutions.push(resolution);
  39881. var subband;
  39882. if (r === 0) {
  39883. // one sub-band (LL) with last decomposition
  39884. subband = {};
  39885. subband.type = 'LL';
  39886. subband.tbx0 = Math.ceil(component.tcx0 / scale);
  39887. subband.tby0 = Math.ceil(component.tcy0 / scale);
  39888. subband.tbx1 = Math.ceil(component.tcx1 / scale);
  39889. subband.tby1 = Math.ceil(component.tcy1 / scale);
  39890. subband.resolution = resolution;
  39891. buildCodeblocks(context, subband, blocksDimensions);
  39892. subbands.push(subband);
  39893. resolution.subbands = [subband];
  39894. } else {
  39895. var bscale = 1 << (decompositionLevelsCount - r + 1);
  39896. var resolutionSubbands = [];
  39897. // three sub-bands (HL, LH and HH) with rest of decompositions
  39898. subband = {};
  39899. subband.type = 'HL';
  39900. subband.tbx0 = Math.ceil(component.tcx0 / bscale - 0.5);
  39901. subband.tby0 = Math.ceil(component.tcy0 / bscale);
  39902. subband.tbx1 = Math.ceil(component.tcx1 / bscale - 0.5);
  39903. subband.tby1 = Math.ceil(component.tcy1 / bscale);
  39904. subband.resolution = resolution;
  39905. buildCodeblocks(context, subband, blocksDimensions);
  39906. subbands.push(subband);
  39907. resolutionSubbands.push(subband);
  39908. subband = {};
  39909. subband.type = 'LH';
  39910. subband.tbx0 = Math.ceil(component.tcx0 / bscale);
  39911. subband.tby0 = Math.ceil(component.tcy0 / bscale - 0.5);
  39912. subband.tbx1 = Math.ceil(component.tcx1 / bscale);
  39913. subband.tby1 = Math.ceil(component.tcy1 / bscale - 0.5);
  39914. subband.resolution = resolution;
  39915. buildCodeblocks(context, subband, blocksDimensions);
  39916. subbands.push(subband);
  39917. resolutionSubbands.push(subband);
  39918. subband = {};
  39919. subband.type = 'HH';
  39920. subband.tbx0 = Math.ceil(component.tcx0 / bscale - 0.5);
  39921. subband.tby0 = Math.ceil(component.tcy0 / bscale - 0.5);
  39922. subband.tbx1 = Math.ceil(component.tcx1 / bscale - 0.5);
  39923. subband.tby1 = Math.ceil(component.tcy1 / bscale - 0.5);
  39924. subband.resolution = resolution;
  39925. buildCodeblocks(context, subband, blocksDimensions);
  39926. subbands.push(subband);
  39927. resolutionSubbands.push(subband);
  39928. resolution.subbands = resolutionSubbands;
  39929. }
  39930. }
  39931. component.resolutions = resolutions;
  39932. component.subbands = subbands;
  39933. }
  39934. // Generate the packets sequence
  39935. var progressionOrder = tile.codingStyleDefaultParameters.progressionOrder;
  39936. switch (progressionOrder) {
  39937. case 0:
  39938. tile.packetsIterator =
  39939. new LayerResolutionComponentPositionIterator(context);
  39940. break;
  39941. case 1:
  39942. tile.packetsIterator =
  39943. new ResolutionLayerComponentPositionIterator(context);
  39944. break;
  39945. case 2:
  39946. tile.packetsIterator =
  39947. new ResolutionPositionComponentLayerIterator(context);
  39948. break;
  39949. case 3:
  39950. tile.packetsIterator =
  39951. new PositionComponentResolutionLayerIterator(context);
  39952. break;
  39953. case 4:
  39954. tile.packetsIterator =
  39955. new ComponentPositionResolutionLayerIterator(context);
  39956. break;
  39957. default:
  39958. throw new Error('JPX Error: Unsupported progression order ' +
  39959. progressionOrder);
  39960. }
  39961. }
  39962. function parseTilePackets(context, data, offset, dataLength) {
  39963. var position = 0;
  39964. var buffer, bufferSize = 0, skipNextBit = false;
  39965. function readBits(count) {
  39966. while (bufferSize < count) {
  39967. var b = data[offset + position];
  39968. position++;
  39969. if (skipNextBit) {
  39970. buffer = (buffer << 7) | b;
  39971. bufferSize += 7;
  39972. skipNextBit = false;
  39973. } else {
  39974. buffer = (buffer << 8) | b;
  39975. bufferSize += 8;
  39976. }
  39977. if (b === 0xFF) {
  39978. skipNextBit = true;
  39979. }
  39980. }
  39981. bufferSize -= count;
  39982. return (buffer >>> bufferSize) & ((1 << count) - 1);
  39983. }
  39984. function skipMarkerIfEqual(value) {
  39985. if (data[offset + position - 1] === 0xFF &&
  39986. data[offset + position] === value) {
  39987. skipBytes(1);
  39988. return true;
  39989. } else if (data[offset + position] === 0xFF &&
  39990. data[offset + position + 1] === value) {
  39991. skipBytes(2);
  39992. return true;
  39993. }
  39994. return false;
  39995. }
  39996. function skipBytes(count) {
  39997. position += count;
  39998. }
  39999. function alignToByte() {
  40000. bufferSize = 0;
  40001. if (skipNextBit) {
  40002. position++;
  40003. skipNextBit = false;
  40004. }
  40005. }
  40006. function readCodingpasses() {
  40007. if (readBits(1) === 0) {
  40008. return 1;
  40009. }
  40010. if (readBits(1) === 0) {
  40011. return 2;
  40012. }
  40013. var value = readBits(2);
  40014. if (value < 3) {
  40015. return value + 3;
  40016. }
  40017. value = readBits(5);
  40018. if (value < 31) {
  40019. return value + 6;
  40020. }
  40021. value = readBits(7);
  40022. return value + 37;
  40023. }
  40024. var tileIndex = context.currentTile.index;
  40025. var tile = context.tiles[tileIndex];
  40026. var sopMarkerUsed = context.COD.sopMarkerUsed;
  40027. var ephMarkerUsed = context.COD.ephMarkerUsed;
  40028. var packetsIterator = tile.packetsIterator;
  40029. while (position < dataLength) {
  40030. alignToByte();
  40031. if (sopMarkerUsed && skipMarkerIfEqual(0x91)) {
  40032. // Skip also marker segment length and packet sequence ID
  40033. skipBytes(4);
  40034. }
  40035. var packet = packetsIterator.nextPacket();
  40036. if (!readBits(1)) {
  40037. continue;
  40038. }
  40039. var layerNumber = packet.layerNumber;
  40040. var queue = [], codeblock;
  40041. for (var i = 0, ii = packet.codeblocks.length; i < ii; i++) {
  40042. codeblock = packet.codeblocks[i];
  40043. var precinct = codeblock.precinct;
  40044. var codeblockColumn = codeblock.cbx - precinct.cbxMin;
  40045. var codeblockRow = codeblock.cby - precinct.cbyMin;
  40046. var codeblockIncluded = false;
  40047. var firstTimeInclusion = false;
  40048. var valueReady;
  40049. if (codeblock['included'] !== undefined) {
  40050. codeblockIncluded = !!readBits(1);
  40051. } else {
  40052. // reading inclusion tree
  40053. precinct = codeblock.precinct;
  40054. var inclusionTree, zeroBitPlanesTree;
  40055. if (precinct['inclusionTree'] !== undefined) {
  40056. inclusionTree = precinct.inclusionTree;
  40057. } else {
  40058. // building inclusion and zero bit-planes trees
  40059. var width = precinct.cbxMax - precinct.cbxMin + 1;
  40060. var height = precinct.cbyMax - precinct.cbyMin + 1;
  40061. inclusionTree = new InclusionTree(width, height, layerNumber);
  40062. zeroBitPlanesTree = new TagTree(width, height);
  40063. precinct.inclusionTree = inclusionTree;
  40064. precinct.zeroBitPlanesTree = zeroBitPlanesTree;
  40065. }
  40066. if (inclusionTree.reset(codeblockColumn, codeblockRow, layerNumber)) {
  40067. while (true) {
  40068. if (readBits(1)) {
  40069. valueReady = !inclusionTree.nextLevel();
  40070. if (valueReady) {
  40071. codeblock.included = true;
  40072. codeblockIncluded = firstTimeInclusion = true;
  40073. break;
  40074. }
  40075. } else {
  40076. inclusionTree.incrementValue(layerNumber);
  40077. break;
  40078. }
  40079. }
  40080. }
  40081. }
  40082. if (!codeblockIncluded) {
  40083. continue;
  40084. }
  40085. if (firstTimeInclusion) {
  40086. zeroBitPlanesTree = precinct.zeroBitPlanesTree;
  40087. zeroBitPlanesTree.reset(codeblockColumn, codeblockRow);
  40088. while (true) {
  40089. if (readBits(1)) {
  40090. valueReady = !zeroBitPlanesTree.nextLevel();
  40091. if (valueReady) {
  40092. break;
  40093. }
  40094. } else {
  40095. zeroBitPlanesTree.incrementValue();
  40096. }
  40097. }
  40098. codeblock.zeroBitPlanes = zeroBitPlanesTree.value;
  40099. }
  40100. var codingpasses = readCodingpasses();
  40101. while (readBits(1)) {
  40102. codeblock.Lblock++;
  40103. }
  40104. var codingpassesLog2 = log2(codingpasses);
  40105. // rounding down log2
  40106. var bits = ((codingpasses < (1 << codingpassesLog2)) ?
  40107. codingpassesLog2 - 1 : codingpassesLog2) + codeblock.Lblock;
  40108. var codedDataLength = readBits(bits);
  40109. queue.push({
  40110. codeblock: codeblock,
  40111. codingpasses: codingpasses,
  40112. dataLength: codedDataLength
  40113. });
  40114. }
  40115. alignToByte();
  40116. if (ephMarkerUsed) {
  40117. skipMarkerIfEqual(0x92);
  40118. }
  40119. while (queue.length > 0) {
  40120. var packetItem = queue.shift();
  40121. codeblock = packetItem.codeblock;
  40122. if (codeblock['data'] === undefined) {
  40123. codeblock.data = [];
  40124. }
  40125. codeblock.data.push({
  40126. data: data,
  40127. start: offset + position,
  40128. end: offset + position + packetItem.dataLength,
  40129. codingpasses: packetItem.codingpasses
  40130. });
  40131. position += packetItem.dataLength;
  40132. }
  40133. }
  40134. return position;
  40135. }
  40136. function copyCoefficients(coefficients, levelWidth, levelHeight, subband,
  40137. delta, mb, reversible, segmentationSymbolUsed) {
  40138. var x0 = subband.tbx0;
  40139. var y0 = subband.tby0;
  40140. var width = subband.tbx1 - subband.tbx0;
  40141. var codeblocks = subband.codeblocks;
  40142. var right = subband.type.charAt(0) === 'H' ? 1 : 0;
  40143. var bottom = subband.type.charAt(1) === 'H' ? levelWidth : 0;
  40144. for (var i = 0, ii = codeblocks.length; i < ii; ++i) {
  40145. var codeblock = codeblocks[i];
  40146. var blockWidth = codeblock.tbx1_ - codeblock.tbx0_;
  40147. var blockHeight = codeblock.tby1_ - codeblock.tby0_;
  40148. if (blockWidth === 0 || blockHeight === 0) {
  40149. continue;
  40150. }
  40151. if (codeblock['data'] === undefined) {
  40152. continue;
  40153. }
  40154. var bitModel, currentCodingpassType;
  40155. bitModel = new BitModel(blockWidth, blockHeight, codeblock.subbandType,
  40156. codeblock.zeroBitPlanes, mb);
  40157. currentCodingpassType = 2; // first bit plane starts from cleanup
  40158. // collect data
  40159. var data = codeblock.data, totalLength = 0, codingpasses = 0;
  40160. var j, jj, dataItem;
  40161. for (j = 0, jj = data.length; j < jj; j++) {
  40162. dataItem = data[j];
  40163. totalLength += dataItem.end - dataItem.start;
  40164. codingpasses += dataItem.codingpasses;
  40165. }
  40166. var encodedData = new Uint8Array(totalLength);
  40167. var position = 0;
  40168. for (j = 0, jj = data.length; j < jj; j++) {
  40169. dataItem = data[j];
  40170. var chunk = dataItem.data.subarray(dataItem.start, dataItem.end);
  40171. encodedData.set(chunk, position);
  40172. position += chunk.length;
  40173. }
  40174. // decoding the item
  40175. var decoder = new ArithmeticDecoder(encodedData, 0, totalLength);
  40176. bitModel.setDecoder(decoder);
  40177. for (j = 0; j < codingpasses; j++) {
  40178. switch (currentCodingpassType) {
  40179. case 0:
  40180. bitModel.runSignificancePropogationPass();
  40181. break;
  40182. case 1:
  40183. bitModel.runMagnitudeRefinementPass();
  40184. break;
  40185. case 2:
  40186. bitModel.runCleanupPass();
  40187. if (segmentationSymbolUsed) {
  40188. bitModel.checkSegmentationSymbol();
  40189. }
  40190. break;
  40191. }
  40192. currentCodingpassType = (currentCodingpassType + 1) % 3;
  40193. }
  40194. var offset = (codeblock.tbx0_ - x0) + (codeblock.tby0_ - y0) * width;
  40195. var sign = bitModel.coefficentsSign;
  40196. var magnitude = bitModel.coefficentsMagnitude;
  40197. var bitsDecoded = bitModel.bitsDecoded;
  40198. var magnitudeCorrection = reversible ? 0 : 0.5;
  40199. var k, n, nb;
  40200. position = 0;
  40201. // Do the interleaving of Section F.3.3 here, so we do not need
  40202. // to copy later. LL level is not interleaved, just copied.
  40203. var interleave = (subband.type !== 'LL');
  40204. for (j = 0; j < blockHeight; j++) {
  40205. var row = (offset / width) | 0; // row in the non-interleaved subband
  40206. var levelOffset = 2 * row * (levelWidth - width) + right + bottom;
  40207. for (k = 0; k < blockWidth; k++) {
  40208. n = magnitude[position];
  40209. if (n !== 0) {
  40210. n = (n + magnitudeCorrection) * delta;
  40211. if (sign[position] !== 0) {
  40212. n = -n;
  40213. }
  40214. nb = bitsDecoded[position];
  40215. var pos = interleave ? (levelOffset + (offset << 1)) : offset;
  40216. if (reversible && (nb >= mb)) {
  40217. coefficients[pos] = n;
  40218. } else {
  40219. coefficients[pos] = n * (1 << (mb - nb));
  40220. }
  40221. }
  40222. offset++;
  40223. position++;
  40224. }
  40225. offset += width - blockWidth;
  40226. }
  40227. }
  40228. }
  40229. function transformTile(context, tile, c) {
  40230. var component = tile.components[c];
  40231. var codingStyleParameters = component.codingStyleParameters;
  40232. var quantizationParameters = component.quantizationParameters;
  40233. var decompositionLevelsCount =
  40234. codingStyleParameters.decompositionLevelsCount;
  40235. var spqcds = quantizationParameters.SPqcds;
  40236. var scalarExpounded = quantizationParameters.scalarExpounded;
  40237. var guardBits = quantizationParameters.guardBits;
  40238. var segmentationSymbolUsed = codingStyleParameters.segmentationSymbolUsed;
  40239. var precision = context.components[c].precision;
  40240. var reversible = codingStyleParameters.reversibleTransformation;
  40241. var transform = (reversible ? new ReversibleTransform() :
  40242. new IrreversibleTransform());
  40243. var subbandCoefficients = [];
  40244. var b = 0;
  40245. for (var i = 0; i <= decompositionLevelsCount; i++) {
  40246. var resolution = component.resolutions[i];
  40247. var width = resolution.trx1 - resolution.trx0;
  40248. var height = resolution.try1 - resolution.try0;
  40249. // Allocate space for the whole sublevel.
  40250. var coefficients = new Float32Array(width * height);
  40251. for (var j = 0, jj = resolution.subbands.length; j < jj; j++) {
  40252. var mu, epsilon;
  40253. if (!scalarExpounded) {
  40254. // formula E-5
  40255. mu = spqcds[0].mu;
  40256. epsilon = spqcds[0].epsilon + (i > 0 ? 1 - i : 0);
  40257. } else {
  40258. mu = spqcds[b].mu;
  40259. epsilon = spqcds[b].epsilon;
  40260. b++;
  40261. }
  40262. var subband = resolution.subbands[j];
  40263. var gainLog2 = SubbandsGainLog2[subband.type];
  40264. // calulate quantization coefficient (Section E.1.1.1)
  40265. var delta = (reversible ? 1 :
  40266. Math.pow(2, precision + gainLog2 - epsilon) * (1 + mu / 2048));
  40267. var mb = (guardBits + epsilon - 1);
  40268. // In the first resolution level, copyCoefficients will fill the
  40269. // whole array with coefficients. In the succeding passes,
  40270. // copyCoefficients will consecutively fill in the values that belong
  40271. // to the interleaved positions of the HL, LH, and HH coefficients.
  40272. // The LL coefficients will then be interleaved in Transform.iterate().
  40273. copyCoefficients(coefficients, width, height, subband, delta, mb,
  40274. reversible, segmentationSymbolUsed);
  40275. }
  40276. subbandCoefficients.push({
  40277. width: width,
  40278. height: height,
  40279. items: coefficients
  40280. });
  40281. }
  40282. var result = transform.calculate(subbandCoefficients,
  40283. component.tcx0, component.tcy0);
  40284. return {
  40285. left: component.tcx0,
  40286. top: component.tcy0,
  40287. width: result.width,
  40288. height: result.height,
  40289. items: result.items
  40290. };
  40291. }
  40292. function transformComponents(context) {
  40293. var siz = context.SIZ;
  40294. var components = context.components;
  40295. var componentsCount = siz.Csiz;
  40296. var resultImages = [];
  40297. for (var i = 0, ii = context.tiles.length; i < ii; i++) {
  40298. var tile = context.tiles[i];
  40299. var transformedTiles = [];
  40300. var c;
  40301. for (c = 0; c < componentsCount; c++) {
  40302. transformedTiles[c] = transformTile(context, tile, c);
  40303. }
  40304. var tile0 = transformedTiles[0];
  40305. var out = new Uint8Array(tile0.items.length * componentsCount);
  40306. var result = {
  40307. left: tile0.left,
  40308. top: tile0.top,
  40309. width: tile0.width,
  40310. height: tile0.height,
  40311. items: out
  40312. };
  40313. // Section G.2.2 Inverse multi component transform
  40314. var shift, offset, max, min, maxK;
  40315. var pos = 0, j, jj, y0, y1, y2, r, g, b, k, val;
  40316. if (tile.codingStyleDefaultParameters.multipleComponentTransform) {
  40317. var fourComponents = componentsCount === 4;
  40318. var y0items = transformedTiles[0].items;
  40319. var y1items = transformedTiles[1].items;
  40320. var y2items = transformedTiles[2].items;
  40321. var y3items = fourComponents ? transformedTiles[3].items : null;
  40322. // HACK: The multiple component transform formulas below assume that
  40323. // all components have the same precision. With this in mind, we
  40324. // compute shift and offset only once.
  40325. shift = components[0].precision - 8;
  40326. offset = (128 << shift) + 0.5;
  40327. max = 255 * (1 << shift);
  40328. maxK = max * 0.5;
  40329. min = -maxK;
  40330. var component0 = tile.components[0];
  40331. var alpha01 = componentsCount - 3;
  40332. jj = y0items.length;
  40333. if (!component0.codingStyleParameters.reversibleTransformation) {
  40334. // inverse irreversible multiple component transform
  40335. for (j = 0; j < jj; j++, pos += alpha01) {
  40336. y0 = y0items[j] + offset;
  40337. y1 = y1items[j];
  40338. y2 = y2items[j];
  40339. r = y0 + 1.402 * y2;
  40340. g = y0 - 0.34413 * y1 - 0.71414 * y2;
  40341. b = y0 + 1.772 * y1;
  40342. out[pos++] = r <= 0 ? 0 : r >= max ? 255 : r >> shift;
  40343. out[pos++] = g <= 0 ? 0 : g >= max ? 255 : g >> shift;
  40344. out[pos++] = b <= 0 ? 0 : b >= max ? 255 : b >> shift;
  40345. }
  40346. } else {
  40347. // inverse reversible multiple component transform
  40348. for (j = 0; j < jj; j++, pos += alpha01) {
  40349. y0 = y0items[j] + offset;
  40350. y1 = y1items[j];
  40351. y2 = y2items[j];
  40352. g = y0 - ((y2 + y1) >> 2);
  40353. r = g + y2;
  40354. b = g + y1;
  40355. out[pos++] = r <= 0 ? 0 : r >= max ? 255 : r >> shift;
  40356. out[pos++] = g <= 0 ? 0 : g >= max ? 255 : g >> shift;
  40357. out[pos++] = b <= 0 ? 0 : b >= max ? 255 : b >> shift;
  40358. }
  40359. }
  40360. if (fourComponents) {
  40361. for (j = 0, pos = 3; j < jj; j++, pos += 4) {
  40362. k = y3items[j];
  40363. out[pos] = k <= min ? 0 : k >= maxK ? 255 : (k + offset) >> shift;
  40364. }
  40365. }
  40366. } else { // no multi-component transform
  40367. for (c = 0; c < componentsCount; c++) {
  40368. var items = transformedTiles[c].items;
  40369. shift = components[c].precision - 8;
  40370. offset = (128 << shift) + 0.5;
  40371. max = (127.5 * (1 << shift));
  40372. min = -max;
  40373. for (pos = c, j = 0, jj = items.length; j < jj; j++) {
  40374. val = items[j];
  40375. out[pos] = val <= min ? 0 :
  40376. val >= max ? 255 : (val + offset) >> shift;
  40377. pos += componentsCount;
  40378. }
  40379. }
  40380. }
  40381. resultImages.push(result);
  40382. }
  40383. return resultImages;
  40384. }
  40385. function initializeTile(context, tileIndex) {
  40386. var siz = context.SIZ;
  40387. var componentsCount = siz.Csiz;
  40388. var tile = context.tiles[tileIndex];
  40389. for (var c = 0; c < componentsCount; c++) {
  40390. var component = tile.components[c];
  40391. var qcdOrQcc = (context.currentTile.QCC[c] !== undefined ?
  40392. context.currentTile.QCC[c] : context.currentTile.QCD);
  40393. component.quantizationParameters = qcdOrQcc;
  40394. var codOrCoc = (context.currentTile.COC[c] !== undefined ?
  40395. context.currentTile.COC[c] : context.currentTile.COD);
  40396. component.codingStyleParameters = codOrCoc;
  40397. }
  40398. tile.codingStyleDefaultParameters = context.currentTile.COD;
  40399. }
  40400. // Section B.10.2 Tag trees
  40401. var TagTree = (function TagTreeClosure() {
  40402. function TagTree(width, height) {
  40403. var levelsLength = log2(Math.max(width, height)) + 1;
  40404. this.levels = [];
  40405. for (var i = 0; i < levelsLength; i++) {
  40406. var level = {
  40407. width: width,
  40408. height: height,
  40409. items: []
  40410. };
  40411. this.levels.push(level);
  40412. width = Math.ceil(width / 2);
  40413. height = Math.ceil(height / 2);
  40414. }
  40415. }
  40416. TagTree.prototype = {
  40417. reset: function TagTree_reset(i, j) {
  40418. var currentLevel = 0, value = 0, level;
  40419. while (currentLevel < this.levels.length) {
  40420. level = this.levels[currentLevel];
  40421. var index = i + j * level.width;
  40422. if (level.items[index] !== undefined) {
  40423. value = level.items[index];
  40424. break;
  40425. }
  40426. level.index = index;
  40427. i >>= 1;
  40428. j >>= 1;
  40429. currentLevel++;
  40430. }
  40431. currentLevel--;
  40432. level = this.levels[currentLevel];
  40433. level.items[level.index] = value;
  40434. this.currentLevel = currentLevel;
  40435. delete this.value;
  40436. },
  40437. incrementValue: function TagTree_incrementValue() {
  40438. var level = this.levels[this.currentLevel];
  40439. level.items[level.index]++;
  40440. },
  40441. nextLevel: function TagTree_nextLevel() {
  40442. var currentLevel = this.currentLevel;
  40443. var level = this.levels[currentLevel];
  40444. var value = level.items[level.index];
  40445. currentLevel--;
  40446. if (currentLevel < 0) {
  40447. this.value = value;
  40448. return false;
  40449. }
  40450. this.currentLevel = currentLevel;
  40451. level = this.levels[currentLevel];
  40452. level.items[level.index] = value;
  40453. return true;
  40454. }
  40455. };
  40456. return TagTree;
  40457. })();
  40458. var InclusionTree = (function InclusionTreeClosure() {
  40459. function InclusionTree(width, height, defaultValue) {
  40460. var levelsLength = log2(Math.max(width, height)) + 1;
  40461. this.levels = [];
  40462. for (var i = 0; i < levelsLength; i++) {
  40463. var items = new Uint8Array(width * height);
  40464. for (var j = 0, jj = items.length; j < jj; j++) {
  40465. items[j] = defaultValue;
  40466. }
  40467. var level = {
  40468. width: width,
  40469. height: height,
  40470. items: items
  40471. };
  40472. this.levels.push(level);
  40473. width = Math.ceil(width / 2);
  40474. height = Math.ceil(height / 2);
  40475. }
  40476. }
  40477. InclusionTree.prototype = {
  40478. reset: function InclusionTree_reset(i, j, stopValue) {
  40479. var currentLevel = 0;
  40480. while (currentLevel < this.levels.length) {
  40481. var level = this.levels[currentLevel];
  40482. var index = i + j * level.width;
  40483. level.index = index;
  40484. var value = level.items[index];
  40485. if (value === 0xFF) {
  40486. break;
  40487. }
  40488. if (value > stopValue) {
  40489. this.currentLevel = currentLevel;
  40490. // already know about this one, propagating the value to top levels
  40491. this.propagateValues();
  40492. return false;
  40493. }
  40494. i >>= 1;
  40495. j >>= 1;
  40496. currentLevel++;
  40497. }
  40498. this.currentLevel = currentLevel - 1;
  40499. return true;
  40500. },
  40501. incrementValue: function InclusionTree_incrementValue(stopValue) {
  40502. var level = this.levels[this.currentLevel];
  40503. level.items[level.index] = stopValue + 1;
  40504. this.propagateValues();
  40505. },
  40506. propagateValues: function InclusionTree_propagateValues() {
  40507. var levelIndex = this.currentLevel;
  40508. var level = this.levels[levelIndex];
  40509. var currentValue = level.items[level.index];
  40510. while (--levelIndex >= 0) {
  40511. level = this.levels[levelIndex];
  40512. level.items[level.index] = currentValue;
  40513. }
  40514. },
  40515. nextLevel: function InclusionTree_nextLevel() {
  40516. var currentLevel = this.currentLevel;
  40517. var level = this.levels[currentLevel];
  40518. var value = level.items[level.index];
  40519. level.items[level.index] = 0xFF;
  40520. currentLevel--;
  40521. if (currentLevel < 0) {
  40522. return false;
  40523. }
  40524. this.currentLevel = currentLevel;
  40525. level = this.levels[currentLevel];
  40526. level.items[level.index] = value;
  40527. return true;
  40528. }
  40529. };
  40530. return InclusionTree;
  40531. })();
  40532. // Section D. Coefficient bit modeling
  40533. var BitModel = (function BitModelClosure() {
  40534. var UNIFORM_CONTEXT = 17;
  40535. var RUNLENGTH_CONTEXT = 18;
  40536. // Table D-1
  40537. // The index is binary presentation: 0dddvvhh, ddd - sum of Di (0..4),
  40538. // vv - sum of Vi (0..2), and hh - sum of Hi (0..2)
  40539. var LLAndLHContextsLabel = new Uint8Array([
  40540. 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,
  40541. 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,
  40542. 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
  40543. ]);
  40544. var HLContextLabel = new Uint8Array([
  40545. 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,
  40546. 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,
  40547. 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
  40548. ]);
  40549. var HHContextLabel = new Uint8Array([
  40550. 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,
  40551. 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,
  40552. 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
  40553. ]);
  40554. function BitModel(width, height, subband, zeroBitPlanes, mb) {
  40555. this.width = width;
  40556. this.height = height;
  40557. this.contextLabelTable = (subband === 'HH' ? HHContextLabel :
  40558. (subband === 'HL' ? HLContextLabel : LLAndLHContextsLabel));
  40559. var coefficientCount = width * height;
  40560. // coefficients outside the encoding region treated as insignificant
  40561. // add border state cells for significanceState
  40562. this.neighborsSignificance = new Uint8Array(coefficientCount);
  40563. this.coefficentsSign = new Uint8Array(coefficientCount);
  40564. this.coefficentsMagnitude = mb > 14 ? new Uint32Array(coefficientCount) :
  40565. mb > 6 ? new Uint16Array(coefficientCount) :
  40566. new Uint8Array(coefficientCount);
  40567. this.processingFlags = new Uint8Array(coefficientCount);
  40568. var bitsDecoded = new Uint8Array(coefficientCount);
  40569. if (zeroBitPlanes !== 0) {
  40570. for (var i = 0; i < coefficientCount; i++) {
  40571. bitsDecoded[i] = zeroBitPlanes;
  40572. }
  40573. }
  40574. this.bitsDecoded = bitsDecoded;
  40575. this.reset();
  40576. }
  40577. BitModel.prototype = {
  40578. setDecoder: function BitModel_setDecoder(decoder) {
  40579. this.decoder = decoder;
  40580. },
  40581. reset: function BitModel_reset() {
  40582. // We have 17 contexts that are accessed via context labels,
  40583. // plus the uniform and runlength context.
  40584. this.contexts = new Int8Array(19);
  40585. // Contexts are packed into 1 byte:
  40586. // highest 7 bits carry the index, lowest bit carries mps
  40587. this.contexts[0] = (4 << 1) | 0;
  40588. this.contexts[UNIFORM_CONTEXT] = (46 << 1) | 0;
  40589. this.contexts[RUNLENGTH_CONTEXT] = (3 << 1) | 0;
  40590. },
  40591. setNeighborsSignificance:
  40592. function BitModel_setNeighborsSignificance(row, column, index) {
  40593. var neighborsSignificance = this.neighborsSignificance;
  40594. var width = this.width, height = this.height;
  40595. var left = (column > 0);
  40596. var right = (column + 1 < width);
  40597. var i;
  40598. if (row > 0) {
  40599. i = index - width;
  40600. if (left) {
  40601. neighborsSignificance[i - 1] += 0x10;
  40602. }
  40603. if (right) {
  40604. neighborsSignificance[i + 1] += 0x10;
  40605. }
  40606. neighborsSignificance[i] += 0x04;
  40607. }
  40608. if (row + 1 < height) {
  40609. i = index + width;
  40610. if (left) {
  40611. neighborsSignificance[i - 1] += 0x10;
  40612. }
  40613. if (right) {
  40614. neighborsSignificance[i + 1] += 0x10;
  40615. }
  40616. neighborsSignificance[i] += 0x04;
  40617. }
  40618. if (left) {
  40619. neighborsSignificance[index - 1] += 0x01;
  40620. }
  40621. if (right) {
  40622. neighborsSignificance[index + 1] += 0x01;
  40623. }
  40624. neighborsSignificance[index] |= 0x80;
  40625. },
  40626. runSignificancePropogationPass:
  40627. function BitModel_runSignificancePropogationPass() {
  40628. var decoder = this.decoder;
  40629. var width = this.width, height = this.height;
  40630. var coefficentsMagnitude = this.coefficentsMagnitude;
  40631. var coefficentsSign = this.coefficentsSign;
  40632. var neighborsSignificance = this.neighborsSignificance;
  40633. var processingFlags = this.processingFlags;
  40634. var contexts = this.contexts;
  40635. var labels = this.contextLabelTable;
  40636. var bitsDecoded = this.bitsDecoded;
  40637. var processedInverseMask = ~1;
  40638. var processedMask = 1;
  40639. var firstMagnitudeBitMask = 2;
  40640. for (var i0 = 0; i0 < height; i0 += 4) {
  40641. for (var j = 0; j < width; j++) {
  40642. var index = i0 * width + j;
  40643. for (var i1 = 0; i1 < 4; i1++, index += width) {
  40644. var i = i0 + i1;
  40645. if (i >= height) {
  40646. break;
  40647. }
  40648. // clear processed flag first
  40649. processingFlags[index] &= processedInverseMask;
  40650. if (coefficentsMagnitude[index] ||
  40651. !neighborsSignificance[index]) {
  40652. continue;
  40653. }
  40654. var contextLabel = labels[neighborsSignificance[index]];
  40655. var decision = decoder.readBit(contexts, contextLabel);
  40656. if (decision) {
  40657. var sign = this.decodeSignBit(i, j, index);
  40658. coefficentsSign[index] = sign;
  40659. coefficentsMagnitude[index] = 1;
  40660. this.setNeighborsSignificance(i, j, index);
  40661. processingFlags[index] |= firstMagnitudeBitMask;
  40662. }
  40663. bitsDecoded[index]++;
  40664. processingFlags[index] |= processedMask;
  40665. }
  40666. }
  40667. }
  40668. },
  40669. decodeSignBit: function BitModel_decodeSignBit(row, column, index) {
  40670. var width = this.width, height = this.height;
  40671. var coefficentsMagnitude = this.coefficentsMagnitude;
  40672. var coefficentsSign = this.coefficentsSign;
  40673. var contribution, sign0, sign1, significance1;
  40674. var contextLabel, decoded;
  40675. // calculate horizontal contribution
  40676. significance1 = (column > 0 && coefficentsMagnitude[index - 1] !== 0);
  40677. if (column + 1 < width && coefficentsMagnitude[index + 1] !== 0) {
  40678. sign1 = coefficentsSign[index + 1];
  40679. if (significance1) {
  40680. sign0 = coefficentsSign[index - 1];
  40681. contribution = 1 - sign1 - sign0;
  40682. } else {
  40683. contribution = 1 - sign1 - sign1;
  40684. }
  40685. } else if (significance1) {
  40686. sign0 = coefficentsSign[index - 1];
  40687. contribution = 1 - sign0 - sign0;
  40688. } else {
  40689. contribution = 0;
  40690. }
  40691. var horizontalContribution = 3 * contribution;
  40692. // calculate vertical contribution and combine with the horizontal
  40693. significance1 = (row > 0 && coefficentsMagnitude[index - width] !== 0);
  40694. if (row + 1 < height && coefficentsMagnitude[index + width] !== 0) {
  40695. sign1 = coefficentsSign[index + width];
  40696. if (significance1) {
  40697. sign0 = coefficentsSign[index - width];
  40698. contribution = 1 - sign1 - sign0 + horizontalContribution;
  40699. } else {
  40700. contribution = 1 - sign1 - sign1 + horizontalContribution;
  40701. }
  40702. } else if (significance1) {
  40703. sign0 = coefficentsSign[index - width];
  40704. contribution = 1 - sign0 - sign0 + horizontalContribution;
  40705. } else {
  40706. contribution = horizontalContribution;
  40707. }
  40708. if (contribution >= 0) {
  40709. contextLabel = 9 + contribution;
  40710. decoded = this.decoder.readBit(this.contexts, contextLabel);
  40711. } else {
  40712. contextLabel = 9 - contribution;
  40713. decoded = this.decoder.readBit(this.contexts, contextLabel) ^ 1;
  40714. }
  40715. return decoded;
  40716. },
  40717. runMagnitudeRefinementPass:
  40718. function BitModel_runMagnitudeRefinementPass() {
  40719. var decoder = this.decoder;
  40720. var width = this.width, height = this.height;
  40721. var coefficentsMagnitude = this.coefficentsMagnitude;
  40722. var neighborsSignificance = this.neighborsSignificance;
  40723. var contexts = this.contexts;
  40724. var bitsDecoded = this.bitsDecoded;
  40725. var processingFlags = this.processingFlags;
  40726. var processedMask = 1;
  40727. var firstMagnitudeBitMask = 2;
  40728. var length = width * height;
  40729. var width4 = width * 4;
  40730. for (var index0 = 0, indexNext; index0 < length; index0 = indexNext) {
  40731. indexNext = Math.min(length, index0 + width4);
  40732. for (var j = 0; j < width; j++) {
  40733. for (var index = index0 + j; index < indexNext; index += width) {
  40734. // significant but not those that have just become
  40735. if (!coefficentsMagnitude[index] ||
  40736. (processingFlags[index] & processedMask) !== 0) {
  40737. continue;
  40738. }
  40739. var contextLabel = 16;
  40740. if ((processingFlags[index] & firstMagnitudeBitMask) !== 0) {
  40741. processingFlags[index] ^= firstMagnitudeBitMask;
  40742. // first refinement
  40743. var significance = neighborsSignificance[index] & 127;
  40744. contextLabel = significance === 0 ? 15 : 14;
  40745. }
  40746. var bit = decoder.readBit(contexts, contextLabel);
  40747. coefficentsMagnitude[index] =
  40748. (coefficentsMagnitude[index] << 1) | bit;
  40749. bitsDecoded[index]++;
  40750. processingFlags[index] |= processedMask;
  40751. }
  40752. }
  40753. }
  40754. },
  40755. runCleanupPass: function BitModel_runCleanupPass() {
  40756. var decoder = this.decoder;
  40757. var width = this.width, height = this.height;
  40758. var neighborsSignificance = this.neighborsSignificance;
  40759. var coefficentsMagnitude = this.coefficentsMagnitude;
  40760. var coefficentsSign = this.coefficentsSign;
  40761. var contexts = this.contexts;
  40762. var labels = this.contextLabelTable;
  40763. var bitsDecoded = this.bitsDecoded;
  40764. var processingFlags = this.processingFlags;
  40765. var processedMask = 1;
  40766. var firstMagnitudeBitMask = 2;
  40767. var oneRowDown = width;
  40768. var twoRowsDown = width * 2;
  40769. var threeRowsDown = width * 3;
  40770. var iNext;
  40771. for (var i0 = 0; i0 < height; i0 = iNext) {
  40772. iNext = Math.min(i0 + 4, height);
  40773. var indexBase = i0 * width;
  40774. var checkAllEmpty = i0 + 3 < height;
  40775. for (var j = 0; j < width; j++) {
  40776. var index0 = indexBase + j;
  40777. // using the property: labels[neighborsSignificance[index]] === 0
  40778. // when neighborsSignificance[index] === 0
  40779. var allEmpty = (checkAllEmpty &&
  40780. processingFlags[index0] === 0 &&
  40781. processingFlags[index0 + oneRowDown] === 0 &&
  40782. processingFlags[index0 + twoRowsDown] === 0 &&
  40783. processingFlags[index0 + threeRowsDown] === 0 &&
  40784. neighborsSignificance[index0] === 0 &&
  40785. neighborsSignificance[index0 + oneRowDown] === 0 &&
  40786. neighborsSignificance[index0 + twoRowsDown] === 0 &&
  40787. neighborsSignificance[index0 + threeRowsDown] === 0);
  40788. var i1 = 0, index = index0;
  40789. var i = i0, sign;
  40790. if (allEmpty) {
  40791. var hasSignificantCoefficent =
  40792. decoder.readBit(contexts, RUNLENGTH_CONTEXT);
  40793. if (!hasSignificantCoefficent) {
  40794. bitsDecoded[index0]++;
  40795. bitsDecoded[index0 + oneRowDown]++;
  40796. bitsDecoded[index0 + twoRowsDown]++;
  40797. bitsDecoded[index0 + threeRowsDown]++;
  40798. continue; // next column
  40799. }
  40800. i1 = (decoder.readBit(contexts, UNIFORM_CONTEXT) << 1) |
  40801. decoder.readBit(contexts, UNIFORM_CONTEXT);
  40802. if (i1 !== 0) {
  40803. i = i0 + i1;
  40804. index += i1 * width;
  40805. }
  40806. sign = this.decodeSignBit(i, j, index);
  40807. coefficentsSign[index] = sign;
  40808. coefficentsMagnitude[index] = 1;
  40809. this.setNeighborsSignificance(i, j, index);
  40810. processingFlags[index] |= firstMagnitudeBitMask;
  40811. index = index0;
  40812. for (var i2 = i0; i2 <= i; i2++, index += width) {
  40813. bitsDecoded[index]++;
  40814. }
  40815. i1++;
  40816. }
  40817. for (i = i0 + i1; i < iNext; i++, index += width) {
  40818. if (coefficentsMagnitude[index] ||
  40819. (processingFlags[index] & processedMask) !== 0) {
  40820. continue;
  40821. }
  40822. var contextLabel = labels[neighborsSignificance[index]];
  40823. var decision = decoder.readBit(contexts, contextLabel);
  40824. if (decision === 1) {
  40825. sign = this.decodeSignBit(i, j, index);
  40826. coefficentsSign[index] = sign;
  40827. coefficentsMagnitude[index] = 1;
  40828. this.setNeighborsSignificance(i, j, index);
  40829. processingFlags[index] |= firstMagnitudeBitMask;
  40830. }
  40831. bitsDecoded[index]++;
  40832. }
  40833. }
  40834. }
  40835. },
  40836. checkSegmentationSymbol: function BitModel_checkSegmentationSymbol() {
  40837. var decoder = this.decoder;
  40838. var contexts = this.contexts;
  40839. var symbol = (decoder.readBit(contexts, UNIFORM_CONTEXT) << 3) |
  40840. (decoder.readBit(contexts, UNIFORM_CONTEXT) << 2) |
  40841. (decoder.readBit(contexts, UNIFORM_CONTEXT) << 1) |
  40842. decoder.readBit(contexts, UNIFORM_CONTEXT);
  40843. if (symbol !== 0xA) {
  40844. throw new Error('JPX Error: Invalid segmentation symbol');
  40845. }
  40846. }
  40847. };
  40848. return BitModel;
  40849. })();
  40850. // Section F, Discrete wavelet transformation
  40851. var Transform = (function TransformClosure() {
  40852. function Transform() {}
  40853. Transform.prototype.calculate =
  40854. function transformCalculate(subbands, u0, v0) {
  40855. var ll = subbands[0];
  40856. for (var i = 1, ii = subbands.length; i < ii; i++) {
  40857. ll = this.iterate(ll, subbands[i], u0, v0);
  40858. }
  40859. return ll;
  40860. };
  40861. Transform.prototype.extend = function extend(buffer, offset, size) {
  40862. // Section F.3.7 extending... using max extension of 4
  40863. var i1 = offset - 1, j1 = offset + 1;
  40864. var i2 = offset + size - 2, j2 = offset + size;
  40865. buffer[i1--] = buffer[j1++];
  40866. buffer[j2++] = buffer[i2--];
  40867. buffer[i1--] = buffer[j1++];
  40868. buffer[j2++] = buffer[i2--];
  40869. buffer[i1--] = buffer[j1++];
  40870. buffer[j2++] = buffer[i2--];
  40871. buffer[i1] = buffer[j1];
  40872. buffer[j2] = buffer[i2];
  40873. };
  40874. Transform.prototype.iterate = function Transform_iterate(ll, hl_lh_hh,
  40875. u0, v0) {
  40876. var llWidth = ll.width, llHeight = ll.height, llItems = ll.items;
  40877. var width = hl_lh_hh.width;
  40878. var height = hl_lh_hh.height;
  40879. var items = hl_lh_hh.items;
  40880. var i, j, k, l, u, v;
  40881. // Interleave LL according to Section F.3.3
  40882. for (k = 0, i = 0; i < llHeight; i++) {
  40883. l = i * 2 * width;
  40884. for (j = 0; j < llWidth; j++, k++, l += 2) {
  40885. items[l] = llItems[k];
  40886. }
  40887. }
  40888. // The LL band is not needed anymore.
  40889. llItems = ll.items = null;
  40890. var bufferPadding = 4;
  40891. var rowBuffer = new Float32Array(width + 2 * bufferPadding);
  40892. // Section F.3.4 HOR_SR
  40893. if (width === 1) {
  40894. // if width = 1, when u0 even keep items as is, when odd divide by 2
  40895. if ((u0 & 1) !== 0) {
  40896. for (v = 0, k = 0; v < height; v++, k += width) {
  40897. items[k] *= 0.5;
  40898. }
  40899. }
  40900. } else {
  40901. for (v = 0, k = 0; v < height; v++, k += width) {
  40902. rowBuffer.set(items.subarray(k, k + width), bufferPadding);
  40903. this.extend(rowBuffer, bufferPadding, width);
  40904. this.filter(rowBuffer, bufferPadding, width);
  40905. items.set(
  40906. rowBuffer.subarray(bufferPadding, bufferPadding + width),
  40907. k);
  40908. }
  40909. }
  40910. // Accesses to the items array can take long, because it may not fit into
  40911. // CPU cache and has to be fetched from main memory. Since subsequent
  40912. // accesses to the items array are not local when reading columns, we
  40913. // have a cache miss every time. To reduce cache misses, get up to
  40914. // 'numBuffers' items at a time and store them into the individual
  40915. // buffers. The colBuffers should be small enough to fit into CPU cache.
  40916. var numBuffers = 16;
  40917. var colBuffers = [];
  40918. for (i = 0; i < numBuffers; i++) {
  40919. colBuffers.push(new Float32Array(height + 2 * bufferPadding));
  40920. }
  40921. var b, currentBuffer = 0;
  40922. ll = bufferPadding + height;
  40923. // Section F.3.5 VER_SR
  40924. if (height === 1) {
  40925. // if height = 1, when v0 even keep items as is, when odd divide by 2
  40926. if ((v0 & 1) !== 0) {
  40927. for (u = 0; u < width; u++) {
  40928. items[u] *= 0.5;
  40929. }
  40930. }
  40931. } else {
  40932. for (u = 0; u < width; u++) {
  40933. // if we ran out of buffers, copy several image columns at once
  40934. if (currentBuffer === 0) {
  40935. numBuffers = Math.min(width - u, numBuffers);
  40936. for (k = u, l = bufferPadding; l < ll; k += width, l++) {
  40937. for (b = 0; b < numBuffers; b++) {
  40938. colBuffers[b][l] = items[k + b];
  40939. }
  40940. }
  40941. currentBuffer = numBuffers;
  40942. }
  40943. currentBuffer--;
  40944. var buffer = colBuffers[currentBuffer];
  40945. this.extend(buffer, bufferPadding, height);
  40946. this.filter(buffer, bufferPadding, height);
  40947. // If this is last buffer in this group of buffers, flush all buffers.
  40948. if (currentBuffer === 0) {
  40949. k = u - numBuffers + 1;
  40950. for (l = bufferPadding; l < ll; k += width, l++) {
  40951. for (b = 0; b < numBuffers; b++) {
  40952. items[k + b] = colBuffers[b][l];
  40953. }
  40954. }
  40955. }
  40956. }
  40957. }
  40958. return {
  40959. width: width,
  40960. height: height,
  40961. items: items
  40962. };
  40963. };
  40964. return Transform;
  40965. })();
  40966. // Section 3.8.2 Irreversible 9-7 filter
  40967. var IrreversibleTransform = (function IrreversibleTransformClosure() {
  40968. function IrreversibleTransform() {
  40969. Transform.call(this);
  40970. }
  40971. IrreversibleTransform.prototype = Object.create(Transform.prototype);
  40972. IrreversibleTransform.prototype.filter =
  40973. function irreversibleTransformFilter(x, offset, length) {
  40974. var len = length >> 1;
  40975. offset = offset | 0;
  40976. var j, n, current, next;
  40977. var alpha = -1.586134342059924;
  40978. var beta = -0.052980118572961;
  40979. var gamma = 0.882911075530934;
  40980. var delta = 0.443506852043971;
  40981. var K = 1.230174104914001;
  40982. var K_ = 1 / K;
  40983. // step 1 is combined with step 3
  40984. // step 2
  40985. j = offset - 3;
  40986. for (n = len + 4; n--; j += 2) {
  40987. x[j] *= K_;
  40988. }
  40989. // step 1 & 3
  40990. j = offset - 2;
  40991. current = delta * x[j -1];
  40992. for (n = len + 3; n--; j += 2) {
  40993. next = delta * x[j + 1];
  40994. x[j] = K * x[j] - current - next;
  40995. if (n--) {
  40996. j += 2;
  40997. current = delta * x[j + 1];
  40998. x[j] = K * x[j] - current - next;
  40999. } else {
  41000. break;
  41001. }
  41002. }
  41003. // step 4
  41004. j = offset - 1;
  41005. current = gamma * x[j - 1];
  41006. for (n = len + 2; n--; j += 2) {
  41007. next = gamma * x[j + 1];
  41008. x[j] -= current + next;
  41009. if (n--) {
  41010. j += 2;
  41011. current = gamma * x[j + 1];
  41012. x[j] -= current + next;
  41013. } else {
  41014. break;
  41015. }
  41016. }
  41017. // step 5
  41018. j = offset;
  41019. current = beta * x[j - 1];
  41020. for (n = len + 1; n--; j += 2) {
  41021. next = beta * x[j + 1];
  41022. x[j] -= current + next;
  41023. if (n--) {
  41024. j += 2;
  41025. current = beta * x[j + 1];
  41026. x[j] -= current + next;
  41027. } else {
  41028. break;
  41029. }
  41030. }
  41031. // step 6
  41032. if (len !== 0) {
  41033. j = offset + 1;
  41034. current = alpha * x[j - 1];
  41035. for (n = len; n--; j += 2) {
  41036. next = alpha * x[j + 1];
  41037. x[j] -= current + next;
  41038. if (n--) {
  41039. j += 2;
  41040. current = alpha * x[j + 1];
  41041. x[j] -= current + next;
  41042. } else {
  41043. break;
  41044. }
  41045. }
  41046. }
  41047. };
  41048. return IrreversibleTransform;
  41049. })();
  41050. // Section 3.8.1 Reversible 5-3 filter
  41051. var ReversibleTransform = (function ReversibleTransformClosure() {
  41052. function ReversibleTransform() {
  41053. Transform.call(this);
  41054. }
  41055. ReversibleTransform.prototype = Object.create(Transform.prototype);
  41056. ReversibleTransform.prototype.filter =
  41057. function reversibleTransformFilter(x, offset, length) {
  41058. var len = length >> 1;
  41059. offset = offset | 0;
  41060. var j, n;
  41061. for (j = offset, n = len + 1; n--; j += 2) {
  41062. x[j] -= (x[j - 1] + x[j + 1] + 2) >> 2;
  41063. }
  41064. for (j = offset + 1, n = len; n--; j += 2) {
  41065. x[j] += (x[j - 1] + x[j + 1]) >> 1;
  41066. }
  41067. };
  41068. return ReversibleTransform;
  41069. })();
  41070. return JpxImage;
  41071. })();
  41072. var Jbig2Image = (function Jbig2ImageClosure() {
  41073. // Utility data structures
  41074. function ContextCache() {}
  41075. ContextCache.prototype = {
  41076. getContexts: function(id) {
  41077. if (id in this) {
  41078. return this[id];
  41079. }
  41080. return (this[id] = new Int8Array(1 << 16));
  41081. }
  41082. };
  41083. function DecodingContext(data, start, end) {
  41084. this.data = data;
  41085. this.start = start;
  41086. this.end = end;
  41087. }
  41088. DecodingContext.prototype = {
  41089. get decoder() {
  41090. var decoder = new ArithmeticDecoder(this.data, this.start, this.end);
  41091. return shadow(this, 'decoder', decoder);
  41092. },
  41093. get contextCache() {
  41094. var cache = new ContextCache();
  41095. return shadow(this, 'contextCache', cache);
  41096. }
  41097. };
  41098. // Annex A. Arithmetic Integer Decoding Procedure
  41099. // A.2 Procedure for decoding values
  41100. function decodeInteger(contextCache, procedure, decoder) {
  41101. var contexts = contextCache.getContexts(procedure);
  41102. var prev = 1;
  41103. function readBits(length) {
  41104. var v = 0;
  41105. for (var i = 0; i < length; i++) {
  41106. var bit = decoder.readBit(contexts, prev);
  41107. prev = (prev < 256 ? (prev << 1) | bit :
  41108. (((prev << 1) | bit) & 511) | 256);
  41109. v = (v << 1) | bit;
  41110. }
  41111. return v >>> 0;
  41112. }
  41113. var sign = readBits(1);
  41114. var value = readBits(1) ?
  41115. (readBits(1) ?
  41116. (readBits(1) ?
  41117. (readBits(1) ?
  41118. (readBits(1) ?
  41119. (readBits(32) + 4436) :
  41120. readBits(12) + 340) :
  41121. readBits(8) + 84) :
  41122. readBits(6) + 20) :
  41123. readBits(4) + 4) :
  41124. readBits(2);
  41125. return (sign === 0 ? value : (value > 0 ? -value : null));
  41126. }
  41127. // A.3 The IAID decoding procedure
  41128. function decodeIAID(contextCache, decoder, codeLength) {
  41129. var contexts = contextCache.getContexts('IAID');
  41130. var prev = 1;
  41131. for (var i = 0; i < codeLength; i++) {
  41132. var bit = decoder.readBit(contexts, prev);
  41133. prev = (prev << 1) | bit;
  41134. }
  41135. if (codeLength < 31) {
  41136. return prev & ((1 << codeLength) - 1);
  41137. }
  41138. return prev & 0x7FFFFFFF;
  41139. }
  41140. // 7.3 Segment types
  41141. var SegmentTypes = [
  41142. 'SymbolDictionary', null, null, null, 'IntermediateTextRegion', null,
  41143. 'ImmediateTextRegion', 'ImmediateLosslessTextRegion', null, null, null,
  41144. null, null, null, null, null, 'patternDictionary', null, null, null,
  41145. 'IntermediateHalftoneRegion', null, 'ImmediateHalftoneRegion',
  41146. 'ImmediateLosslessHalftoneRegion', null, null, null, null, null, null, null,
  41147. null, null, null, null, null, 'IntermediateGenericRegion', null,
  41148. 'ImmediateGenericRegion', 'ImmediateLosslessGenericRegion',
  41149. 'IntermediateGenericRefinementRegion', null,
  41150. 'ImmediateGenericRefinementRegion',
  41151. 'ImmediateLosslessGenericRefinementRegion', null, null, null, null,
  41152. 'PageInformation', 'EndOfPage', 'EndOfStripe', 'EndOfFile', 'Profiles',
  41153. 'Tables', null, null, null, null, null, null, null, null,
  41154. 'Extension'
  41155. ];
  41156. var CodingTemplates = [
  41157. [{x: -1, y: -2}, {x: 0, y: -2}, {x: 1, y: -2}, {x: -2, y: -1},
  41158. {x: -1, y: -1}, {x: 0, y: -1}, {x: 1, y: -1}, {x: 2, y: -1},
  41159. {x: -4, y: 0}, {x: -3, y: 0}, {x: -2, y: 0}, {x: -1, y: 0}],
  41160. [{x: -1, y: -2}, {x: 0, y: -2}, {x: 1, y: -2}, {x: 2, y: -2},
  41161. {x: -2, y: -1}, {x: -1, y: -1}, {x: 0, y: -1}, {x: 1, y: -1},
  41162. {x: 2, y: -1}, {x: -3, y: 0}, {x: -2, y: 0}, {x: -1, y: 0}],
  41163. [{x: -1, y: -2}, {x: 0, y: -2}, {x: 1, y: -2}, {x: -2, y: -1},
  41164. {x: -1, y: -1}, {x: 0, y: -1}, {x: 1, y: -1}, {x: -2, y: 0},
  41165. {x: -1, y: 0}],
  41166. [{x: -3, y: -1}, {x: -2, y: -1}, {x: -1, y: -1}, {x: 0, y: -1},
  41167. {x: 1, y: -1}, {x: -4, y: 0}, {x: -3, y: 0}, {x: -2, y: 0}, {x: -1, y: 0}]
  41168. ];
  41169. var RefinementTemplates = [
  41170. {
  41171. coding: [{x: 0, y: -1}, {x: 1, y: -1}, {x: -1, y: 0}],
  41172. reference: [{x: 0, y: -1}, {x: 1, y: -1}, {x: -1, y: 0}, {x: 0, y: 0},
  41173. {x: 1, y: 0}, {x: -1, y: 1}, {x: 0, y: 1}, {x: 1, y: 1}]
  41174. },
  41175. {
  41176. coding: [{x: -1, y: -1}, {x: 0, y: -1}, {x: 1, y: -1}, {x: -1, y: 0}],
  41177. reference: [{x: 0, y: -1}, {x: -1, y: 0}, {x: 0, y: 0}, {x: 1, y: 0},
  41178. {x: 0, y: 1}, {x: 1, y: 1}]
  41179. }
  41180. ];
  41181. // See 6.2.5.7 Decoding the bitmap.
  41182. var ReusedContexts = [
  41183. 0x9B25, // 10011 0110010 0101
  41184. 0x0795, // 0011 110010 101
  41185. 0x00E5, // 001 11001 01
  41186. 0x0195 // 011001 0101
  41187. ];
  41188. var RefinementReusedContexts = [
  41189. 0x0020, // '000' + '0' (coding) + '00010000' + '0' (reference)
  41190. 0x0008 // '0000' + '001000'
  41191. ];
  41192. function decodeBitmapTemplate0(width, height, decodingContext) {
  41193. var decoder = decodingContext.decoder;
  41194. var contexts = decodingContext.contextCache.getContexts('GB');
  41195. var contextLabel, i, j, pixel, row, row1, row2, bitmap = [];
  41196. // ...ooooo....
  41197. // ..ooooooo... Context template for current pixel (X)
  41198. // .ooooX...... (concatenate values of 'o'-pixels to get contextLabel)
  41199. var OLD_PIXEL_MASK = 0x7BF7; // 01111 0111111 0111
  41200. for (i = 0; i < height; i++) {
  41201. row = bitmap[i] = new Uint8Array(width);
  41202. row1 = (i < 1) ? row : bitmap[i - 1];
  41203. row2 = (i < 2) ? row : bitmap[i - 2];
  41204. // At the beginning of each row:
  41205. // Fill contextLabel with pixels that are above/right of (X)
  41206. contextLabel = (row2[0] << 13) | (row2[1] << 12) | (row2[2] << 11) |
  41207. (row1[0] << 7) | (row1[1] << 6) | (row1[2] << 5) |
  41208. (row1[3] << 4);
  41209. for (j = 0; j < width; j++) {
  41210. row[j] = pixel = decoder.readBit(contexts, contextLabel);
  41211. // At each pixel: Clear contextLabel pixels that are shifted
  41212. // out of the context, then add new ones.
  41213. contextLabel = ((contextLabel & OLD_PIXEL_MASK) << 1) |
  41214. (j + 3 < width ? row2[j + 3] << 11 : 0) |
  41215. (j + 4 < width ? row1[j + 4] << 4 : 0) | pixel;
  41216. }
  41217. }
  41218. return bitmap;
  41219. }
  41220. // 6.2 Generic Region Decoding Procedure
  41221. function decodeBitmap(mmr, width, height, templateIndex, prediction, skip, at,
  41222. decodingContext) {
  41223. if (mmr) {
  41224. error('JBIG2 error: MMR encoding is not supported');
  41225. }
  41226. // Use optimized version for the most common case
  41227. if (templateIndex === 0 && !skip && !prediction && at.length === 4 &&
  41228. at[0].x === 3 && at[0].y === -1 && at[1].x === -3 && at[1].y === -1 &&
  41229. at[2].x === 2 && at[2].y === -2 && at[3].x === -2 && at[3].y === -2) {
  41230. return decodeBitmapTemplate0(width, height, decodingContext);
  41231. }
  41232. var useskip = !!skip;
  41233. var template = CodingTemplates[templateIndex].concat(at);
  41234. // Sorting is non-standard, and it is not required. But sorting increases
  41235. // the number of template bits that can be reused from the previous
  41236. // contextLabel in the main loop.
  41237. template.sort(function (a, b) {
  41238. return (a.y - b.y) || (a.x - b.x);
  41239. });
  41240. var templateLength = template.length;
  41241. var templateX = new Int8Array(templateLength);
  41242. var templateY = new Int8Array(templateLength);
  41243. var changingTemplateEntries = [];
  41244. var reuseMask = 0, minX = 0, maxX = 0, minY = 0;
  41245. var c, k;
  41246. for (k = 0; k < templateLength; k++) {
  41247. templateX[k] = template[k].x;
  41248. templateY[k] = template[k].y;
  41249. minX = Math.min(minX, template[k].x);
  41250. maxX = Math.max(maxX, template[k].x);
  41251. minY = Math.min(minY, template[k].y);
  41252. // Check if the template pixel appears in two consecutive context labels,
  41253. // so it can be reused. Otherwise, we add it to the list of changing
  41254. // template entries.
  41255. if (k < templateLength - 1 &&
  41256. template[k].y === template[k + 1].y &&
  41257. template[k].x === template[k + 1].x - 1) {
  41258. reuseMask |= 1 << (templateLength - 1 - k);
  41259. } else {
  41260. changingTemplateEntries.push(k);
  41261. }
  41262. }
  41263. var changingEntriesLength = changingTemplateEntries.length;
  41264. var changingTemplateX = new Int8Array(changingEntriesLength);
  41265. var changingTemplateY = new Int8Array(changingEntriesLength);
  41266. var changingTemplateBit = new Uint16Array(changingEntriesLength);
  41267. for (c = 0; c < changingEntriesLength; c++) {
  41268. k = changingTemplateEntries[c];
  41269. changingTemplateX[c] = template[k].x;
  41270. changingTemplateY[c] = template[k].y;
  41271. changingTemplateBit[c] = 1 << (templateLength - 1 - k);
  41272. }
  41273. // Get the safe bounding box edges from the width, height, minX, maxX, minY
  41274. var sbb_left = -minX;
  41275. var sbb_top = -minY;
  41276. var sbb_right = width - maxX;
  41277. var pseudoPixelContext = ReusedContexts[templateIndex];
  41278. var row = new Uint8Array(width);
  41279. var bitmap = [];
  41280. var decoder = decodingContext.decoder;
  41281. var contexts = decodingContext.contextCache.getContexts('GB');
  41282. var ltp = 0, j, i0, j0, contextLabel = 0, bit, shift;
  41283. for (var i = 0; i < height; i++) {
  41284. if (prediction) {
  41285. var sltp = decoder.readBit(contexts, pseudoPixelContext);
  41286. ltp ^= sltp;
  41287. if (ltp) {
  41288. bitmap.push(row); // duplicate previous row
  41289. continue;
  41290. }
  41291. }
  41292. row = new Uint8Array(row);
  41293. bitmap.push(row);
  41294. for (j = 0; j < width; j++) {
  41295. if (useskip && skip[i][j]) {
  41296. row[j] = 0;
  41297. continue;
  41298. }
  41299. // Are we in the middle of a scanline, so we can reuse contextLabel
  41300. // bits?
  41301. if (j >= sbb_left && j < sbb_right && i >= sbb_top) {
  41302. // If yes, we can just shift the bits that are reusable and only
  41303. // fetch the remaining ones.
  41304. contextLabel = (contextLabel << 1) & reuseMask;
  41305. for (k = 0; k < changingEntriesLength; k++) {
  41306. i0 = i + changingTemplateY[k];
  41307. j0 = j + changingTemplateX[k];
  41308. bit = bitmap[i0][j0];
  41309. if (bit) {
  41310. bit = changingTemplateBit[k];
  41311. contextLabel |= bit;
  41312. }
  41313. }
  41314. } else {
  41315. // compute the contextLabel from scratch
  41316. contextLabel = 0;
  41317. shift = templateLength - 1;
  41318. for (k = 0; k < templateLength; k++, shift--) {
  41319. j0 = j + templateX[k];
  41320. if (j0 >= 0 && j0 < width) {
  41321. i0 = i + templateY[k];
  41322. if (i0 >= 0) {
  41323. bit = bitmap[i0][j0];
  41324. if (bit) {
  41325. contextLabel |= bit << shift;
  41326. }
  41327. }
  41328. }
  41329. }
  41330. }
  41331. var pixel = decoder.readBit(contexts, contextLabel);
  41332. row[j] = pixel;
  41333. }
  41334. }
  41335. return bitmap;
  41336. }
  41337. // 6.3.2 Generic Refinement Region Decoding Procedure
  41338. function decodeRefinement(width, height, templateIndex, referenceBitmap,
  41339. offsetX, offsetY, prediction, at,
  41340. decodingContext) {
  41341. var codingTemplate = RefinementTemplates[templateIndex].coding;
  41342. if (templateIndex === 0) {
  41343. codingTemplate = codingTemplate.concat([at[0]]);
  41344. }
  41345. var codingTemplateLength = codingTemplate.length;
  41346. var codingTemplateX = new Int32Array(codingTemplateLength);
  41347. var codingTemplateY = new Int32Array(codingTemplateLength);
  41348. var k;
  41349. for (k = 0; k < codingTemplateLength; k++) {
  41350. codingTemplateX[k] = codingTemplate[k].x;
  41351. codingTemplateY[k] = codingTemplate[k].y;
  41352. }
  41353. var referenceTemplate = RefinementTemplates[templateIndex].reference;
  41354. if (templateIndex === 0) {
  41355. referenceTemplate = referenceTemplate.concat([at[1]]);
  41356. }
  41357. var referenceTemplateLength = referenceTemplate.length;
  41358. var referenceTemplateX = new Int32Array(referenceTemplateLength);
  41359. var referenceTemplateY = new Int32Array(referenceTemplateLength);
  41360. for (k = 0; k < referenceTemplateLength; k++) {
  41361. referenceTemplateX[k] = referenceTemplate[k].x;
  41362. referenceTemplateY[k] = referenceTemplate[k].y;
  41363. }
  41364. var referenceWidth = referenceBitmap[0].length;
  41365. var referenceHeight = referenceBitmap.length;
  41366. var pseudoPixelContext = RefinementReusedContexts[templateIndex];
  41367. var bitmap = [];
  41368. var decoder = decodingContext.decoder;
  41369. var contexts = decodingContext.contextCache.getContexts('GR');
  41370. var ltp = 0;
  41371. for (var i = 0; i < height; i++) {
  41372. if (prediction) {
  41373. var sltp = decoder.readBit(contexts, pseudoPixelContext);
  41374. ltp ^= sltp;
  41375. if (ltp) {
  41376. error('JBIG2 error: prediction is not supported');
  41377. }
  41378. }
  41379. var row = new Uint8Array(width);
  41380. bitmap.push(row);
  41381. for (var j = 0; j < width; j++) {
  41382. var i0, j0;
  41383. var contextLabel = 0;
  41384. for (k = 0; k < codingTemplateLength; k++) {
  41385. i0 = i + codingTemplateY[k];
  41386. j0 = j + codingTemplateX[k];
  41387. if (i0 < 0 || j0 < 0 || j0 >= width) {
  41388. contextLabel <<= 1; // out of bound pixel
  41389. } else {
  41390. contextLabel = (contextLabel << 1) | bitmap[i0][j0];
  41391. }
  41392. }
  41393. for (k = 0; k < referenceTemplateLength; k++) {
  41394. i0 = i + referenceTemplateY[k] + offsetY;
  41395. j0 = j + referenceTemplateX[k] + offsetX;
  41396. if (i0 < 0 || i0 >= referenceHeight || j0 < 0 ||
  41397. j0 >= referenceWidth) {
  41398. contextLabel <<= 1; // out of bound pixel
  41399. } else {
  41400. contextLabel = (contextLabel << 1) | referenceBitmap[i0][j0];
  41401. }
  41402. }
  41403. var pixel = decoder.readBit(contexts, contextLabel);
  41404. row[j] = pixel;
  41405. }
  41406. }
  41407. return bitmap;
  41408. }
  41409. // 6.5.5 Decoding the symbol dictionary
  41410. function decodeSymbolDictionary(huffman, refinement, symbols,
  41411. numberOfNewSymbols, numberOfExportedSymbols,
  41412. huffmanTables, templateIndex, at,
  41413. refinementTemplateIndex, refinementAt,
  41414. decodingContext) {
  41415. if (huffman) {
  41416. error('JBIG2 error: huffman is not supported');
  41417. }
  41418. var newSymbols = [];
  41419. var currentHeight = 0;
  41420. var symbolCodeLength = log2(symbols.length + numberOfNewSymbols);
  41421. var decoder = decodingContext.decoder;
  41422. var contextCache = decodingContext.contextCache;
  41423. while (newSymbols.length < numberOfNewSymbols) {
  41424. var deltaHeight = decodeInteger(contextCache, 'IADH', decoder); // 6.5.6
  41425. currentHeight += deltaHeight;
  41426. var currentWidth = 0;
  41427. var totalWidth = 0;
  41428. while (true) {
  41429. var deltaWidth = decodeInteger(contextCache, 'IADW', decoder); // 6.5.7
  41430. if (deltaWidth === null) {
  41431. break; // OOB
  41432. }
  41433. currentWidth += deltaWidth;
  41434. totalWidth += currentWidth;
  41435. var bitmap;
  41436. if (refinement) {
  41437. // 6.5.8.2 Refinement/aggregate-coded symbol bitmap
  41438. var numberOfInstances = decodeInteger(contextCache, 'IAAI', decoder);
  41439. if (numberOfInstances > 1) {
  41440. bitmap = decodeTextRegion(huffman, refinement,
  41441. currentWidth, currentHeight, 0,
  41442. numberOfInstances, 1, //strip size
  41443. symbols.concat(newSymbols),
  41444. symbolCodeLength,
  41445. 0, //transposed
  41446. 0, //ds offset
  41447. 1, //top left 7.4.3.1.1
  41448. 0, //OR operator
  41449. huffmanTables,
  41450. refinementTemplateIndex, refinementAt,
  41451. decodingContext);
  41452. } else {
  41453. var symbolId = decodeIAID(contextCache, decoder, symbolCodeLength);
  41454. var rdx = decodeInteger(contextCache, 'IARDX', decoder); // 6.4.11.3
  41455. var rdy = decodeInteger(contextCache, 'IARDY', decoder); // 6.4.11.4
  41456. var symbol = (symbolId < symbols.length ? symbols[symbolId] :
  41457. newSymbols[symbolId - symbols.length]);
  41458. bitmap = decodeRefinement(currentWidth, currentHeight,
  41459. refinementTemplateIndex, symbol, rdx, rdy, false, refinementAt,
  41460. decodingContext);
  41461. }
  41462. } else {
  41463. // 6.5.8.1 Direct-coded symbol bitmap
  41464. bitmap = decodeBitmap(false, currentWidth, currentHeight,
  41465. templateIndex, false, null, at, decodingContext);
  41466. }
  41467. newSymbols.push(bitmap);
  41468. }
  41469. }
  41470. // 6.5.10 Exported symbols
  41471. var exportedSymbols = [];
  41472. var flags = [], currentFlag = false;
  41473. var totalSymbolsLength = symbols.length + numberOfNewSymbols;
  41474. while (flags.length < totalSymbolsLength) {
  41475. var runLength = decodeInteger(contextCache, 'IAEX', decoder);
  41476. while (runLength--) {
  41477. flags.push(currentFlag);
  41478. }
  41479. currentFlag = !currentFlag;
  41480. }
  41481. for (var i = 0, ii = symbols.length; i < ii; i++) {
  41482. if (flags[i]) {
  41483. exportedSymbols.push(symbols[i]);
  41484. }
  41485. }
  41486. for (var j = 0; j < numberOfNewSymbols; i++, j++) {
  41487. if (flags[i]) {
  41488. exportedSymbols.push(newSymbols[j]);
  41489. }
  41490. }
  41491. return exportedSymbols;
  41492. }
  41493. function decodeTextRegion(huffman, refinement, width, height,
  41494. defaultPixelValue, numberOfSymbolInstances,
  41495. stripSize, inputSymbols, symbolCodeLength,
  41496. transposed, dsOffset, referenceCorner,
  41497. combinationOperator, huffmanTables,
  41498. refinementTemplateIndex, refinementAt,
  41499. decodingContext) {
  41500. if (huffman) {
  41501. error('JBIG2 error: huffman is not supported');
  41502. }
  41503. // Prepare bitmap
  41504. var bitmap = [];
  41505. var i, row;
  41506. for (i = 0; i < height; i++) {
  41507. row = new Uint8Array(width);
  41508. if (defaultPixelValue) {
  41509. for (var j = 0; j < width; j++) {
  41510. row[j] = defaultPixelValue;
  41511. }
  41512. }
  41513. bitmap.push(row);
  41514. }
  41515. var decoder = decodingContext.decoder;
  41516. var contextCache = decodingContext.contextCache;
  41517. var stripT = -decodeInteger(contextCache, 'IADT', decoder); // 6.4.6
  41518. var firstS = 0;
  41519. i = 0;
  41520. while (i < numberOfSymbolInstances) {
  41521. var deltaT = decodeInteger(contextCache, 'IADT', decoder); // 6.4.6
  41522. stripT += deltaT;
  41523. var deltaFirstS = decodeInteger(contextCache, 'IAFS', decoder); // 6.4.7
  41524. firstS += deltaFirstS;
  41525. var currentS = firstS;
  41526. do {
  41527. var currentT = (stripSize === 1 ? 0 :
  41528. decodeInteger(contextCache, 'IAIT', decoder)); // 6.4.9
  41529. var t = stripSize * stripT + currentT;
  41530. var symbolId = decodeIAID(contextCache, decoder, symbolCodeLength);
  41531. var applyRefinement = (refinement &&
  41532. decodeInteger(contextCache, 'IARI', decoder));
  41533. var symbolBitmap = inputSymbols[symbolId];
  41534. var symbolWidth = symbolBitmap[0].length;
  41535. var symbolHeight = symbolBitmap.length;
  41536. if (applyRefinement) {
  41537. var rdw = decodeInteger(contextCache, 'IARDW', decoder); // 6.4.11.1
  41538. var rdh = decodeInteger(contextCache, 'IARDH', decoder); // 6.4.11.2
  41539. var rdx = decodeInteger(contextCache, 'IARDX', decoder); // 6.4.11.3
  41540. var rdy = decodeInteger(contextCache, 'IARDY', decoder); // 6.4.11.4
  41541. symbolWidth += rdw;
  41542. symbolHeight += rdh;
  41543. symbolBitmap = decodeRefinement(symbolWidth, symbolHeight,
  41544. refinementTemplateIndex, symbolBitmap, (rdw >> 1) + rdx,
  41545. (rdh >> 1) + rdy, false, refinementAt,
  41546. decodingContext);
  41547. }
  41548. var offsetT = t - ((referenceCorner & 1) ? 0 : symbolHeight);
  41549. var offsetS = currentS - ((referenceCorner & 2) ? symbolWidth : 0);
  41550. var s2, t2, symbolRow;
  41551. if (transposed) {
  41552. // Place Symbol Bitmap from T1,S1
  41553. for (s2 = 0; s2 < symbolHeight; s2++) {
  41554. row = bitmap[offsetS + s2];
  41555. if (!row) {
  41556. continue;
  41557. }
  41558. symbolRow = symbolBitmap[s2];
  41559. // To ignore Parts of Symbol bitmap which goes
  41560. // outside bitmap region
  41561. var maxWidth = Math.min(width - offsetT, symbolWidth);
  41562. switch (combinationOperator) {
  41563. case 0: // OR
  41564. for (t2 = 0; t2 < maxWidth; t2++) {
  41565. row[offsetT + t2] |= symbolRow[t2];
  41566. }
  41567. break;
  41568. case 2: // XOR
  41569. for (t2 = 0; t2 < maxWidth; t2++) {
  41570. row[offsetT + t2] ^= symbolRow[t2];
  41571. }
  41572. break;
  41573. default:
  41574. error('JBIG2 error: operator ' + combinationOperator +
  41575. ' is not supported');
  41576. }
  41577. }
  41578. currentS += symbolHeight - 1;
  41579. } else {
  41580. for (t2 = 0; t2 < symbolHeight; t2++) {
  41581. row = bitmap[offsetT + t2];
  41582. if (!row) {
  41583. continue;
  41584. }
  41585. symbolRow = symbolBitmap[t2];
  41586. switch (combinationOperator) {
  41587. case 0: // OR
  41588. for (s2 = 0; s2 < symbolWidth; s2++) {
  41589. row[offsetS + s2] |= symbolRow[s2];
  41590. }
  41591. break;
  41592. case 2: // XOR
  41593. for (s2 = 0; s2 < symbolWidth; s2++) {
  41594. row[offsetS + s2] ^= symbolRow[s2];
  41595. }
  41596. break;
  41597. default:
  41598. error('JBIG2 error: operator ' + combinationOperator +
  41599. ' is not supported');
  41600. }
  41601. }
  41602. currentS += symbolWidth - 1;
  41603. }
  41604. i++;
  41605. var deltaS = decodeInteger(contextCache, 'IADS', decoder); // 6.4.8
  41606. if (deltaS === null) {
  41607. break; // OOB
  41608. }
  41609. currentS += deltaS + dsOffset;
  41610. } while (true);
  41611. }
  41612. return bitmap;
  41613. }
  41614. function readSegmentHeader(data, start) {
  41615. var segmentHeader = {};
  41616. segmentHeader.number = readUint32(data, start);
  41617. var flags = data[start + 4];
  41618. var segmentType = flags & 0x3F;
  41619. if (!SegmentTypes[segmentType]) {
  41620. error('JBIG2 error: invalid segment type: ' + segmentType);
  41621. }
  41622. segmentHeader.type = segmentType;
  41623. segmentHeader.typeName = SegmentTypes[segmentType];
  41624. segmentHeader.deferredNonRetain = !!(flags & 0x80);
  41625. var pageAssociationFieldSize = !!(flags & 0x40);
  41626. var referredFlags = data[start + 5];
  41627. var referredToCount = (referredFlags >> 5) & 7;
  41628. var retainBits = [referredFlags & 31];
  41629. var position = start + 6;
  41630. if (referredFlags === 7) {
  41631. referredToCount = readUint32(data, position - 1) & 0x1FFFFFFF;
  41632. position += 3;
  41633. var bytes = (referredToCount + 7) >> 3;
  41634. retainBits[0] = data[position++];
  41635. while (--bytes > 0) {
  41636. retainBits.push(data[position++]);
  41637. }
  41638. } else if (referredFlags === 5 || referredFlags === 6) {
  41639. error('JBIG2 error: invalid referred-to flags');
  41640. }
  41641. segmentHeader.retainBits = retainBits;
  41642. var referredToSegmentNumberSize = (segmentHeader.number <= 256 ? 1 :
  41643. (segmentHeader.number <= 65536 ? 2 : 4));
  41644. var referredTo = [];
  41645. var i, ii;
  41646. for (i = 0; i < referredToCount; i++) {
  41647. var number = (referredToSegmentNumberSize === 1 ? data[position] :
  41648. (referredToSegmentNumberSize === 2 ? readUint16(data, position) :
  41649. readUint32(data, position)));
  41650. referredTo.push(number);
  41651. position += referredToSegmentNumberSize;
  41652. }
  41653. segmentHeader.referredTo = referredTo;
  41654. if (!pageAssociationFieldSize) {
  41655. segmentHeader.pageAssociation = data[position++];
  41656. } else {
  41657. segmentHeader.pageAssociation = readUint32(data, position);
  41658. position += 4;
  41659. }
  41660. segmentHeader.length = readUint32(data, position);
  41661. position += 4;
  41662. if (segmentHeader.length === 0xFFFFFFFF) {
  41663. // 7.2.7 Segment data length, unknown segment length
  41664. if (segmentType === 38) { // ImmediateGenericRegion
  41665. var genericRegionInfo = readRegionSegmentInformation(data, position);
  41666. var genericRegionSegmentFlags = data[position +
  41667. RegionSegmentInformationFieldLength];
  41668. var genericRegionMmr = !!(genericRegionSegmentFlags & 1);
  41669. // searching for the segment end
  41670. var searchPatternLength = 6;
  41671. var searchPattern = new Uint8Array(searchPatternLength);
  41672. if (!genericRegionMmr) {
  41673. searchPattern[0] = 0xFF;
  41674. searchPattern[1] = 0xAC;
  41675. }
  41676. searchPattern[2] = (genericRegionInfo.height >>> 24) & 0xFF;
  41677. searchPattern[3] = (genericRegionInfo.height >> 16) & 0xFF;
  41678. searchPattern[4] = (genericRegionInfo.height >> 8) & 0xFF;
  41679. searchPattern[5] = genericRegionInfo.height & 0xFF;
  41680. for (i = position, ii = data.length; i < ii; i++) {
  41681. var j = 0;
  41682. while (j < searchPatternLength && searchPattern[j] === data[i + j]) {
  41683. j++;
  41684. }
  41685. if (j === searchPatternLength) {
  41686. segmentHeader.length = i + searchPatternLength;
  41687. break;
  41688. }
  41689. }
  41690. if (segmentHeader.length === 0xFFFFFFFF) {
  41691. error('JBIG2 error: segment end was not found');
  41692. }
  41693. } else {
  41694. error('JBIG2 error: invalid unknown segment length');
  41695. }
  41696. }
  41697. segmentHeader.headerEnd = position;
  41698. return segmentHeader;
  41699. }
  41700. function readSegments(header, data, start, end) {
  41701. var segments = [];
  41702. var position = start;
  41703. while (position < end) {
  41704. var segmentHeader = readSegmentHeader(data, position);
  41705. position = segmentHeader.headerEnd;
  41706. var segment = {
  41707. header: segmentHeader,
  41708. data: data
  41709. };
  41710. if (!header.randomAccess) {
  41711. segment.start = position;
  41712. position += segmentHeader.length;
  41713. segment.end = position;
  41714. }
  41715. segments.push(segment);
  41716. if (segmentHeader.type === 51) {
  41717. break; // end of file is found
  41718. }
  41719. }
  41720. if (header.randomAccess) {
  41721. for (var i = 0, ii = segments.length; i < ii; i++) {
  41722. segments[i].start = position;
  41723. position += segments[i].header.length;
  41724. segments[i].end = position;
  41725. }
  41726. }
  41727. return segments;
  41728. }
  41729. // 7.4.1 Region segment information field
  41730. function readRegionSegmentInformation(data, start) {
  41731. return {
  41732. width: readUint32(data, start),
  41733. height: readUint32(data, start + 4),
  41734. x: readUint32(data, start + 8),
  41735. y: readUint32(data, start + 12),
  41736. combinationOperator: data[start + 16] & 7
  41737. };
  41738. }
  41739. var RegionSegmentInformationFieldLength = 17;
  41740. function processSegment(segment, visitor) {
  41741. var header = segment.header;
  41742. var data = segment.data, position = segment.start, end = segment.end;
  41743. var args, at, i, atLength;
  41744. switch (header.type) {
  41745. case 0: // SymbolDictionary
  41746. // 7.4.2 Symbol dictionary segment syntax
  41747. var dictionary = {};
  41748. var dictionaryFlags = readUint16(data, position); // 7.4.2.1.1
  41749. dictionary.huffman = !!(dictionaryFlags & 1);
  41750. dictionary.refinement = !!(dictionaryFlags & 2);
  41751. dictionary.huffmanDHSelector = (dictionaryFlags >> 2) & 3;
  41752. dictionary.huffmanDWSelector = (dictionaryFlags >> 4) & 3;
  41753. dictionary.bitmapSizeSelector = (dictionaryFlags >> 6) & 1;
  41754. dictionary.aggregationInstancesSelector = (dictionaryFlags >> 7) & 1;
  41755. dictionary.bitmapCodingContextUsed = !!(dictionaryFlags & 256);
  41756. dictionary.bitmapCodingContextRetained = !!(dictionaryFlags & 512);
  41757. dictionary.template = (dictionaryFlags >> 10) & 3;
  41758. dictionary.refinementTemplate = (dictionaryFlags >> 12) & 1;
  41759. position += 2;
  41760. if (!dictionary.huffman) {
  41761. atLength = dictionary.template === 0 ? 4 : 1;
  41762. at = [];
  41763. for (i = 0; i < atLength; i++) {
  41764. at.push({
  41765. x: readInt8(data, position),
  41766. y: readInt8(data, position + 1)
  41767. });
  41768. position += 2;
  41769. }
  41770. dictionary.at = at;
  41771. }
  41772. if (dictionary.refinement && !dictionary.refinementTemplate) {
  41773. at = [];
  41774. for (i = 0; i < 2; i++) {
  41775. at.push({
  41776. x: readInt8(data, position),
  41777. y: readInt8(data, position + 1)
  41778. });
  41779. position += 2;
  41780. }
  41781. dictionary.refinementAt = at;
  41782. }
  41783. dictionary.numberOfExportedSymbols = readUint32(data, position);
  41784. position += 4;
  41785. dictionary.numberOfNewSymbols = readUint32(data, position);
  41786. position += 4;
  41787. args = [dictionary, header.number, header.referredTo,
  41788. data, position, end];
  41789. break;
  41790. case 6: // ImmediateTextRegion
  41791. case 7: // ImmediateLosslessTextRegion
  41792. var textRegion = {};
  41793. textRegion.info = readRegionSegmentInformation(data, position);
  41794. position += RegionSegmentInformationFieldLength;
  41795. var textRegionSegmentFlags = readUint16(data, position);
  41796. position += 2;
  41797. textRegion.huffman = !!(textRegionSegmentFlags & 1);
  41798. textRegion.refinement = !!(textRegionSegmentFlags & 2);
  41799. textRegion.stripSize = 1 << ((textRegionSegmentFlags >> 2) & 3);
  41800. textRegion.referenceCorner = (textRegionSegmentFlags >> 4) & 3;
  41801. textRegion.transposed = !!(textRegionSegmentFlags & 64);
  41802. textRegion.combinationOperator = (textRegionSegmentFlags >> 7) & 3;
  41803. textRegion.defaultPixelValue = (textRegionSegmentFlags >> 9) & 1;
  41804. textRegion.dsOffset = (textRegionSegmentFlags << 17) >> 27;
  41805. textRegion.refinementTemplate = (textRegionSegmentFlags >> 15) & 1;
  41806. if (textRegion.huffman) {
  41807. var textRegionHuffmanFlags = readUint16(data, position);
  41808. position += 2;
  41809. textRegion.huffmanFS = (textRegionHuffmanFlags) & 3;
  41810. textRegion.huffmanDS = (textRegionHuffmanFlags >> 2) & 3;
  41811. textRegion.huffmanDT = (textRegionHuffmanFlags >> 4) & 3;
  41812. textRegion.huffmanRefinementDW = (textRegionHuffmanFlags >> 6) & 3;
  41813. textRegion.huffmanRefinementDH = (textRegionHuffmanFlags >> 8) & 3;
  41814. textRegion.huffmanRefinementDX = (textRegionHuffmanFlags >> 10) & 3;
  41815. textRegion.huffmanRefinementDY = (textRegionHuffmanFlags >> 12) & 3;
  41816. textRegion.huffmanRefinementSizeSelector =
  41817. !!(textRegionHuffmanFlags & 14);
  41818. }
  41819. if (textRegion.refinement && !textRegion.refinementTemplate) {
  41820. at = [];
  41821. for (i = 0; i < 2; i++) {
  41822. at.push({
  41823. x: readInt8(data, position),
  41824. y: readInt8(data, position + 1)
  41825. });
  41826. position += 2;
  41827. }
  41828. textRegion.refinementAt = at;
  41829. }
  41830. textRegion.numberOfSymbolInstances = readUint32(data, position);
  41831. position += 4;
  41832. // TODO 7.4.3.1.7 Symbol ID Huffman table decoding
  41833. if (textRegion.huffman) {
  41834. error('JBIG2 error: huffman is not supported');
  41835. }
  41836. args = [textRegion, header.referredTo, data, position, end];
  41837. break;
  41838. case 38: // ImmediateGenericRegion
  41839. case 39: // ImmediateLosslessGenericRegion
  41840. var genericRegion = {};
  41841. genericRegion.info = readRegionSegmentInformation(data, position);
  41842. position += RegionSegmentInformationFieldLength;
  41843. var genericRegionSegmentFlags = data[position++];
  41844. genericRegion.mmr = !!(genericRegionSegmentFlags & 1);
  41845. genericRegion.template = (genericRegionSegmentFlags >> 1) & 3;
  41846. genericRegion.prediction = !!(genericRegionSegmentFlags & 8);
  41847. if (!genericRegion.mmr) {
  41848. atLength = genericRegion.template === 0 ? 4 : 1;
  41849. at = [];
  41850. for (i = 0; i < atLength; i++) {
  41851. at.push({
  41852. x: readInt8(data, position),
  41853. y: readInt8(data, position + 1)
  41854. });
  41855. position += 2;
  41856. }
  41857. genericRegion.at = at;
  41858. }
  41859. args = [genericRegion, data, position, end];
  41860. break;
  41861. case 48: // PageInformation
  41862. var pageInfo = {
  41863. width: readUint32(data, position),
  41864. height: readUint32(data, position + 4),
  41865. resolutionX: readUint32(data, position + 8),
  41866. resolutionY: readUint32(data, position + 12)
  41867. };
  41868. if (pageInfo.height === 0xFFFFFFFF) {
  41869. delete pageInfo.height;
  41870. }
  41871. var pageSegmentFlags = data[position + 16];
  41872. var pageStripingInformatiom = readUint16(data, position + 17);
  41873. pageInfo.lossless = !!(pageSegmentFlags & 1);
  41874. pageInfo.refinement = !!(pageSegmentFlags & 2);
  41875. pageInfo.defaultPixelValue = (pageSegmentFlags >> 2) & 1;
  41876. pageInfo.combinationOperator = (pageSegmentFlags >> 3) & 3;
  41877. pageInfo.requiresBuffer = !!(pageSegmentFlags & 32);
  41878. pageInfo.combinationOperatorOverride = !!(pageSegmentFlags & 64);
  41879. args = [pageInfo];
  41880. break;
  41881. case 49: // EndOfPage
  41882. break;
  41883. case 50: // EndOfStripe
  41884. break;
  41885. case 51: // EndOfFile
  41886. break;
  41887. case 62: // 7.4.15 defines 2 extension types which
  41888. // are comments and can be ignored.
  41889. break;
  41890. default:
  41891. error('JBIG2 error: segment type ' + header.typeName + '(' +
  41892. header.type + ') is not implemented');
  41893. }
  41894. var callbackName = 'on' + header.typeName;
  41895. if (callbackName in visitor) {
  41896. visitor[callbackName].apply(visitor, args);
  41897. }
  41898. }
  41899. function processSegments(segments, visitor) {
  41900. for (var i = 0, ii = segments.length; i < ii; i++) {
  41901. processSegment(segments[i], visitor);
  41902. }
  41903. }
  41904. function parseJbig2(data, start, end) {
  41905. var position = start;
  41906. if (data[position] !== 0x97 || data[position + 1] !== 0x4A ||
  41907. data[position + 2] !== 0x42 || data[position + 3] !== 0x32 ||
  41908. data[position + 4] !== 0x0D || data[position + 5] !== 0x0A ||
  41909. data[position + 6] !== 0x1A || data[position + 7] !== 0x0A) {
  41910. error('JBIG2 error: invalid header');
  41911. }
  41912. var header = {};
  41913. position += 8;
  41914. var flags = data[position++];
  41915. header.randomAccess = !(flags & 1);
  41916. if (!(flags & 2)) {
  41917. header.numberOfPages = readUint32(data, position);
  41918. position += 4;
  41919. }
  41920. var segments = readSegments(header, data, position, end);
  41921. error('Not implemented');
  41922. // processSegments(segments, new SimpleSegmentVisitor());
  41923. }
  41924. function parseJbig2Chunks(chunks) {
  41925. var visitor = new SimpleSegmentVisitor();
  41926. for (var i = 0, ii = chunks.length; i < ii; i++) {
  41927. var chunk = chunks[i];
  41928. var segments = readSegments({}, chunk.data, chunk.start, chunk.end);
  41929. processSegments(segments, visitor);
  41930. }
  41931. return visitor.buffer;
  41932. }
  41933. function SimpleSegmentVisitor() {}
  41934. SimpleSegmentVisitor.prototype = {
  41935. onPageInformation: function SimpleSegmentVisitor_onPageInformation(info) {
  41936. this.currentPageInfo = info;
  41937. var rowSize = (info.width + 7) >> 3;
  41938. var buffer = new Uint8Array(rowSize * info.height);
  41939. // The contents of ArrayBuffers are initialized to 0.
  41940. // Fill the buffer with 0xFF only if info.defaultPixelValue is set
  41941. if (info.defaultPixelValue) {
  41942. for (var i = 0, ii = buffer.length; i < ii; i++) {
  41943. buffer[i] = 0xFF;
  41944. }
  41945. }
  41946. this.buffer = buffer;
  41947. },
  41948. drawBitmap: function SimpleSegmentVisitor_drawBitmap(regionInfo, bitmap) {
  41949. var pageInfo = this.currentPageInfo;
  41950. var width = regionInfo.width, height = regionInfo.height;
  41951. var rowSize = (pageInfo.width + 7) >> 3;
  41952. var combinationOperator = pageInfo.combinationOperatorOverride ?
  41953. regionInfo.combinationOperator : pageInfo.combinationOperator;
  41954. var buffer = this.buffer;
  41955. var mask0 = 128 >> (regionInfo.x & 7);
  41956. var offset0 = regionInfo.y * rowSize + (regionInfo.x >> 3);
  41957. var i, j, mask, offset;
  41958. switch (combinationOperator) {
  41959. case 0: // OR
  41960. for (i = 0; i < height; i++) {
  41961. mask = mask0;
  41962. offset = offset0;
  41963. for (j = 0; j < width; j++) {
  41964. if (bitmap[i][j]) {
  41965. buffer[offset] |= mask;
  41966. }
  41967. mask >>= 1;
  41968. if (!mask) {
  41969. mask = 128;
  41970. offset++;
  41971. }
  41972. }
  41973. offset0 += rowSize;
  41974. }
  41975. break;
  41976. case 2: // XOR
  41977. for (i = 0; i < height; i++) {
  41978. mask = mask0;
  41979. offset = offset0;
  41980. for (j = 0; j < width; j++) {
  41981. if (bitmap[i][j]) {
  41982. buffer[offset] ^= mask;
  41983. }
  41984. mask >>= 1;
  41985. if (!mask) {
  41986. mask = 128;
  41987. offset++;
  41988. }
  41989. }
  41990. offset0 += rowSize;
  41991. }
  41992. break;
  41993. default:
  41994. error('JBIG2 error: operator ' + combinationOperator +
  41995. ' is not supported');
  41996. }
  41997. },
  41998. onImmediateGenericRegion:
  41999. function SimpleSegmentVisitor_onImmediateGenericRegion(region, data,
  42000. start, end) {
  42001. var regionInfo = region.info;
  42002. var decodingContext = new DecodingContext(data, start, end);
  42003. var bitmap = decodeBitmap(region.mmr, regionInfo.width, regionInfo.height,
  42004. region.template, region.prediction, null,
  42005. region.at, decodingContext);
  42006. this.drawBitmap(regionInfo, bitmap);
  42007. },
  42008. onImmediateLosslessGenericRegion:
  42009. function SimpleSegmentVisitor_onImmediateLosslessGenericRegion() {
  42010. this.onImmediateGenericRegion.apply(this, arguments);
  42011. },
  42012. onSymbolDictionary:
  42013. function SimpleSegmentVisitor_onSymbolDictionary(dictionary,
  42014. currentSegment,
  42015. referredSegments,
  42016. data, start, end) {
  42017. var huffmanTables;
  42018. if (dictionary.huffman) {
  42019. error('JBIG2 error: huffman is not supported');
  42020. }
  42021. // Combines exported symbols from all referred segments
  42022. var symbols = this.symbols;
  42023. if (!symbols) {
  42024. this.symbols = symbols = {};
  42025. }
  42026. var inputSymbols = [];
  42027. for (var i = 0, ii = referredSegments.length; i < ii; i++) {
  42028. inputSymbols = inputSymbols.concat(symbols[referredSegments[i]]);
  42029. }
  42030. var decodingContext = new DecodingContext(data, start, end);
  42031. symbols[currentSegment] = decodeSymbolDictionary(dictionary.huffman,
  42032. dictionary.refinement, inputSymbols, dictionary.numberOfNewSymbols,
  42033. dictionary.numberOfExportedSymbols, huffmanTables,
  42034. dictionary.template, dictionary.at,
  42035. dictionary.refinementTemplate, dictionary.refinementAt,
  42036. decodingContext);
  42037. },
  42038. onImmediateTextRegion:
  42039. function SimpleSegmentVisitor_onImmediateTextRegion(region,
  42040. referredSegments,
  42041. data, start, end) {
  42042. var regionInfo = region.info;
  42043. var huffmanTables;
  42044. // Combines exported symbols from all referred segments
  42045. var symbols = this.symbols;
  42046. var inputSymbols = [];
  42047. for (var i = 0, ii = referredSegments.length; i < ii; i++) {
  42048. inputSymbols = inputSymbols.concat(symbols[referredSegments[i]]);
  42049. }
  42050. var symbolCodeLength = log2(inputSymbols.length);
  42051. var decodingContext = new DecodingContext(data, start, end);
  42052. var bitmap = decodeTextRegion(region.huffman, region.refinement,
  42053. regionInfo.width, regionInfo.height, region.defaultPixelValue,
  42054. region.numberOfSymbolInstances, region.stripSize, inputSymbols,
  42055. symbolCodeLength, region.transposed, region.dsOffset,
  42056. region.referenceCorner, region.combinationOperator, huffmanTables,
  42057. region.refinementTemplate, region.refinementAt, decodingContext);
  42058. this.drawBitmap(regionInfo, bitmap);
  42059. },
  42060. onImmediateLosslessTextRegion:
  42061. function SimpleSegmentVisitor_onImmediateLosslessTextRegion() {
  42062. this.onImmediateTextRegion.apply(this, arguments);
  42063. }
  42064. };
  42065. function Jbig2Image() {}
  42066. Jbig2Image.prototype = {
  42067. parseChunks: function Jbig2Image_parseChunks(chunks) {
  42068. return parseJbig2Chunks(chunks);
  42069. }
  42070. };
  42071. return Jbig2Image;
  42072. })();
  42073. var bidi = PDFJS.bidi = (function bidiClosure() {
  42074. // Character types for symbols from 0000 to 00FF.
  42075. var baseTypes = [
  42076. 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'S', 'B', 'S', 'WS',
  42077. 'B', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN',
  42078. 'BN', 'BN', 'B', 'B', 'B', 'S', 'WS', 'ON', 'ON', 'ET', 'ET', 'ET', 'ON',
  42079. 'ON', 'ON', 'ON', 'ON', 'ON', 'CS', 'ON', 'CS', 'ON', 'EN', 'EN', 'EN',
  42080. 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'ON', 'ON', 'ON', 'ON', 'ON',
  42081. 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  42082. 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'ON', 'ON',
  42083. 'ON', 'ON', 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  42084. 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  42085. 'L', 'ON', 'ON', 'ON', 'ON', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'B', 'BN',
  42086. 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN',
  42087. 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN',
  42088. 'BN', 'CS', 'ON', 'ET', 'ET', 'ET', 'ET', 'ON', 'ON', 'ON', 'ON', 'L', 'ON',
  42089. 'ON', 'ON', 'ON', 'ON', 'ET', 'ET', 'EN', 'EN', 'ON', 'L', 'ON', 'ON', 'ON',
  42090. 'EN', 'L', 'ON', 'ON', 'ON', 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  42091. 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  42092. 'L', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  42093. 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  42094. 'L', 'L', 'L', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L'
  42095. ];
  42096. // Character types for symbols from 0600 to 06FF
  42097. var arabicTypes = [
  42098. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42099. 'CS', 'AL', 'ON', 'ON', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'AL',
  42100. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42101. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42102. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42103. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42104. 'AL', 'AL', 'AL', 'AL', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM',
  42105. 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'AL', 'AL', 'AL', 'AL',
  42106. 'AL', 'AL', 'AL', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN',
  42107. 'AN', 'ET', 'AN', 'AN', 'AL', 'AL', 'AL', 'NSM', 'AL', 'AL', 'AL', 'AL',
  42108. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42109. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42110. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42111. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42112. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42113. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42114. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42115. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42116. 'AL', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM',
  42117. 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'ON', 'NSM',
  42118. 'NSM', 'NSM', 'NSM', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42119. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL'
  42120. ];
  42121. function isOdd(i) {
  42122. return (i & 1) !== 0;
  42123. }
  42124. function isEven(i) {
  42125. return (i & 1) === 0;
  42126. }
  42127. function findUnequal(arr, start, value) {
  42128. for (var j = start, jj = arr.length; j < jj; ++j) {
  42129. if (arr[j] !== value) {
  42130. return j;
  42131. }
  42132. }
  42133. return j;
  42134. }
  42135. function setValues(arr, start, end, value) {
  42136. for (var j = start; j < end; ++j) {
  42137. arr[j] = value;
  42138. }
  42139. }
  42140. function reverseValues(arr, start, end) {
  42141. for (var i = start, j = end - 1; i < j; ++i, --j) {
  42142. var temp = arr[i];
  42143. arr[i] = arr[j];
  42144. arr[j] = temp;
  42145. }
  42146. }
  42147. function createBidiText(str, isLTR, vertical) {
  42148. return {
  42149. str: str,
  42150. dir: (vertical ? 'ttb' : (isLTR ? 'ltr' : 'rtl'))
  42151. };
  42152. }
  42153. // These are used in bidi(), which is called frequently. We re-use them on
  42154. // each call to avoid unnecessary allocations.
  42155. var chars = [];
  42156. var types = [];
  42157. function bidi(str, startLevel, vertical) {
  42158. var isLTR = true;
  42159. var strLength = str.length;
  42160. if (strLength === 0 || vertical) {
  42161. return createBidiText(str, isLTR, vertical);
  42162. }
  42163. // Get types and fill arrays
  42164. chars.length = strLength;
  42165. types.length = strLength;
  42166. var numBidi = 0;
  42167. var i, ii;
  42168. for (i = 0; i < strLength; ++i) {
  42169. chars[i] = str.charAt(i);
  42170. var charCode = str.charCodeAt(i);
  42171. var charType = 'L';
  42172. if (charCode <= 0x00ff) {
  42173. charType = baseTypes[charCode];
  42174. } else if (0x0590 <= charCode && charCode <= 0x05f4) {
  42175. charType = 'R';
  42176. } else if (0x0600 <= charCode && charCode <= 0x06ff) {
  42177. charType = arabicTypes[charCode & 0xff];
  42178. } else if (0x0700 <= charCode && charCode <= 0x08AC) {
  42179. charType = 'AL';
  42180. }
  42181. if (charType === 'R' || charType === 'AL' || charType === 'AN') {
  42182. numBidi++;
  42183. }
  42184. types[i] = charType;
  42185. }
  42186. // Detect the bidi method
  42187. // - If there are no rtl characters then no bidi needed
  42188. // - If less than 30% chars are rtl then string is primarily ltr
  42189. // - If more than 30% chars are rtl then string is primarily rtl
  42190. if (numBidi === 0) {
  42191. isLTR = true;
  42192. return createBidiText(str, isLTR);
  42193. }
  42194. if (startLevel === -1) {
  42195. if ((strLength / numBidi) < 0.3) {
  42196. isLTR = true;
  42197. startLevel = 0;
  42198. } else {
  42199. isLTR = false;
  42200. startLevel = 1;
  42201. }
  42202. }
  42203. var levels = [];
  42204. for (i = 0; i < strLength; ++i) {
  42205. levels[i] = startLevel;
  42206. }
  42207. /*
  42208. X1-X10: skip most of this, since we are NOT doing the embeddings.
  42209. */
  42210. var e = (isOdd(startLevel) ? 'R' : 'L');
  42211. var sor = e;
  42212. var eor = sor;
  42213. /*
  42214. W1. Examine each non-spacing mark (NSM) in the level run, and change the
  42215. type of the NSM to the type of the previous character. If the NSM is at the
  42216. start of the level run, it will get the type of sor.
  42217. */
  42218. var lastType = sor;
  42219. for (i = 0; i < strLength; ++i) {
  42220. if (types[i] === 'NSM') {
  42221. types[i] = lastType;
  42222. } else {
  42223. lastType = types[i];
  42224. }
  42225. }
  42226. /*
  42227. W2. Search backwards from each instance of a European number until the
  42228. first strong type (R, L, AL, or sor) is found. If an AL is found, change
  42229. the type of the European number to Arabic number.
  42230. */
  42231. lastType = sor;
  42232. var t;
  42233. for (i = 0; i < strLength; ++i) {
  42234. t = types[i];
  42235. if (t === 'EN') {
  42236. types[i] = (lastType === 'AL') ? 'AN' : 'EN';
  42237. } else if (t === 'R' || t === 'L' || t === 'AL') {
  42238. lastType = t;
  42239. }
  42240. }
  42241. /*
  42242. W3. Change all ALs to R.
  42243. */
  42244. for (i = 0; i < strLength; ++i) {
  42245. t = types[i];
  42246. if (t === 'AL') {
  42247. types[i] = 'R';
  42248. }
  42249. }
  42250. /*
  42251. W4. A single European separator between two European numbers changes to a
  42252. European number. A single common separator between two numbers of the same
  42253. type changes to that type:
  42254. */
  42255. for (i = 1; i < strLength - 1; ++i) {
  42256. if (types[i] === 'ES' && types[i - 1] === 'EN' && types[i + 1] === 'EN') {
  42257. types[i] = 'EN';
  42258. }
  42259. if (types[i] === 'CS' &&
  42260. (types[i - 1] === 'EN' || types[i - 1] === 'AN') &&
  42261. types[i + 1] === types[i - 1]) {
  42262. types[i] = types[i - 1];
  42263. }
  42264. }
  42265. /*
  42266. W5. A sequence of European terminators adjacent to European numbers changes
  42267. to all European numbers:
  42268. */
  42269. for (i = 0; i < strLength; ++i) {
  42270. if (types[i] === 'EN') {
  42271. // do before
  42272. var j;
  42273. for (j = i - 1; j >= 0; --j) {
  42274. if (types[j] !== 'ET') {
  42275. break;
  42276. }
  42277. types[j] = 'EN';
  42278. }
  42279. // do after
  42280. for (j = i + 1; j < strLength; --j) {
  42281. if (types[j] !== 'ET') {
  42282. break;
  42283. }
  42284. types[j] = 'EN';
  42285. }
  42286. }
  42287. }
  42288. /*
  42289. W6. Otherwise, separators and terminators change to Other Neutral:
  42290. */
  42291. for (i = 0; i < strLength; ++i) {
  42292. t = types[i];
  42293. if (t === 'WS' || t === 'ES' || t === 'ET' || t === 'CS') {
  42294. types[i] = 'ON';
  42295. }
  42296. }
  42297. /*
  42298. W7. Search backwards from each instance of a European number until the
  42299. first strong type (R, L, or sor) is found. If an L is found, then change
  42300. the type of the European number to L.
  42301. */
  42302. lastType = sor;
  42303. for (i = 0; i < strLength; ++i) {
  42304. t = types[i];
  42305. if (t === 'EN') {
  42306. types[i] = ((lastType === 'L') ? 'L' : 'EN');
  42307. } else if (t === 'R' || t === 'L') {
  42308. lastType = t;
  42309. }
  42310. }
  42311. /*
  42312. N1. A sequence of neutrals takes the direction of the surrounding strong
  42313. text if the text on both sides has the same direction. European and Arabic
  42314. numbers are treated as though they were R. Start-of-level-run (sor) and
  42315. end-of-level-run (eor) are used at level run boundaries.
  42316. */
  42317. for (i = 0; i < strLength; ++i) {
  42318. if (types[i] === 'ON') {
  42319. var end = findUnequal(types, i + 1, 'ON');
  42320. var before = sor;
  42321. if (i > 0) {
  42322. before = types[i - 1];
  42323. }
  42324. var after = eor;
  42325. if (end + 1 < strLength) {
  42326. after = types[end + 1];
  42327. }
  42328. if (before !== 'L') {
  42329. before = 'R';
  42330. }
  42331. if (after !== 'L') {
  42332. after = 'R';
  42333. }
  42334. if (before === after) {
  42335. setValues(types, i, end, before);
  42336. }
  42337. i = end - 1; // reset to end (-1 so next iteration is ok)
  42338. }
  42339. }
  42340. /*
  42341. N2. Any remaining neutrals take the embedding direction.
  42342. */
  42343. for (i = 0; i < strLength; ++i) {
  42344. if (types[i] === 'ON') {
  42345. types[i] = e;
  42346. }
  42347. }
  42348. /*
  42349. I1. For all characters with an even (left-to-right) embedding direction,
  42350. those of type R go up one level and those of type AN or EN go up two
  42351. levels.
  42352. I2. For all characters with an odd (right-to-left) embedding direction,
  42353. those of type L, EN or AN go up one level.
  42354. */
  42355. for (i = 0; i < strLength; ++i) {
  42356. t = types[i];
  42357. if (isEven(levels[i])) {
  42358. if (t === 'R') {
  42359. levels[i] += 1;
  42360. } else if (t === 'AN' || t === 'EN') {
  42361. levels[i] += 2;
  42362. }
  42363. } else { // isOdd
  42364. if (t === 'L' || t === 'AN' || t === 'EN') {
  42365. levels[i] += 1;
  42366. }
  42367. }
  42368. }
  42369. /*
  42370. L1. On each line, reset the embedding level of the following characters to
  42371. the paragraph embedding level:
  42372. segment separators,
  42373. paragraph separators,
  42374. any sequence of whitespace characters preceding a segment separator or
  42375. paragraph separator, and any sequence of white space characters at the end
  42376. of the line.
  42377. */
  42378. // don't bother as text is only single line
  42379. /*
  42380. L2. From the highest level found in the text to the lowest odd level on
  42381. each line, reverse any contiguous sequence of characters that are at that
  42382. level or higher.
  42383. */
  42384. // find highest level & lowest odd level
  42385. var highestLevel = -1;
  42386. var lowestOddLevel = 99;
  42387. var level;
  42388. for (i = 0, ii = levels.length; i < ii; ++i) {
  42389. level = levels[i];
  42390. if (highestLevel < level) {
  42391. highestLevel = level;
  42392. }
  42393. if (lowestOddLevel > level && isOdd(level)) {
  42394. lowestOddLevel = level;
  42395. }
  42396. }
  42397. // now reverse between those limits
  42398. for (level = highestLevel; level >= lowestOddLevel; --level) {
  42399. // find segments to reverse
  42400. var start = -1;
  42401. for (i = 0, ii = levels.length; i < ii; ++i) {
  42402. if (levels[i] < level) {
  42403. if (start >= 0) {
  42404. reverseValues(chars, start, i);
  42405. start = -1;
  42406. }
  42407. } else if (start < 0) {
  42408. start = i;
  42409. }
  42410. }
  42411. if (start >= 0) {
  42412. reverseValues(chars, start, levels.length);
  42413. }
  42414. }
  42415. /*
  42416. L3. Combining marks applied to a right-to-left base character will at this
  42417. point precede their base character. If the rendering engine expects them to
  42418. follow the base characters in the final display process, then the ordering
  42419. of the marks and the base character must be reversed.
  42420. */
  42421. // don't bother for now
  42422. /*
  42423. L4. A character that possesses the mirrored property as specified by
  42424. Section 4.7, Mirrored, must be depicted by a mirrored glyph if the resolved
  42425. directionality of that character is R.
  42426. */
  42427. // don't mirror as characters are already mirrored in the pdf
  42428. // Finally, return string
  42429. var result = '';
  42430. for (i = 0, ii = chars.length; i < ii; ++i) {
  42431. var ch = chars[i];
  42432. if (ch !== '<' && ch !== '>') {
  42433. result += ch;
  42434. }
  42435. }
  42436. return createBidiText(result, isLTR);
  42437. }
  42438. return bidi;
  42439. })();
  42440. /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  42441. /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
  42442. /* Copyright 2014 Opera Software ASA
  42443. *
  42444. * Licensed under the Apache License, Version 2.0 (the "License");
  42445. * you may not use this file except in compliance with the License.
  42446. * You may obtain a copy of the License at
  42447. *
  42448. * http://www.apache.org/licenses/LICENSE-2.0
  42449. *
  42450. * Unless required by applicable law or agreed to in writing, software
  42451. * distributed under the License is distributed on an "AS IS" BASIS,
  42452. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  42453. * See the License for the specific language governing permissions and
  42454. * limitations under the License.
  42455. *
  42456. *
  42457. * Based on https://code.google.com/p/smhasher/wiki/MurmurHash3.
  42458. * Hashes roughly 100 KB per millisecond on i7 3.4 GHz.
  42459. */
  42460. /* globals Uint32ArrayView */
  42461. 'use strict';
  42462. var MurmurHash3_64 = (function MurmurHash3_64Closure (seed) {
  42463. // Workaround for missing math precison in JS.
  42464. var MASK_HIGH = 0xffff0000;
  42465. var MASK_LOW = 0xffff;
  42466. function MurmurHash3_64 (seed) {
  42467. var SEED = 0xc3d2e1f0;
  42468. this.h1 = seed ? seed & 0xffffffff : SEED;
  42469. this.h2 = seed ? seed & 0xffffffff : SEED;
  42470. }
  42471. var alwaysUseUint32ArrayView = false;
  42472. // old webkits have issues with non-aligned arrays
  42473. try {
  42474. new Uint32Array(new Uint8Array(5).buffer, 0, 1);
  42475. } catch (e) {
  42476. alwaysUseUint32ArrayView = true;
  42477. }
  42478. MurmurHash3_64.prototype = {
  42479. update: function MurmurHash3_64_update(input) {
  42480. var useUint32ArrayView = alwaysUseUint32ArrayView;
  42481. var i;
  42482. if (typeof input === 'string') {
  42483. var data = new Uint8Array(input.length * 2);
  42484. var length = 0;
  42485. for (i = 0; i < input.length; i++) {
  42486. var code = input.charCodeAt(i);
  42487. if (code <= 0xff) {
  42488. data[length++] = code;
  42489. }
  42490. else {
  42491. data[length++] = code >>> 8;
  42492. data[length++] = code & 0xff;
  42493. }
  42494. }
  42495. } else if (input instanceof Uint8Array) {
  42496. data = input;
  42497. length = data.length;
  42498. } else if (typeof input === 'object' && ('length' in input)) {
  42499. // processing regular arrays as well, e.g. for IE9
  42500. data = input;
  42501. length = data.length;
  42502. useUint32ArrayView = true;
  42503. } else {
  42504. throw new Error('Wrong data format in MurmurHash3_64_update. ' +
  42505. 'Input must be a string or array.');
  42506. }
  42507. var blockCounts = length >> 2;
  42508. var tailLength = length - blockCounts * 4;
  42509. // we don't care about endianness here
  42510. var dataUint32 = useUint32ArrayView ?
  42511. new Uint32ArrayView(data, blockCounts) :
  42512. new Uint32Array(data.buffer, 0, blockCounts);
  42513. var k1 = 0;
  42514. var k2 = 0;
  42515. var h1 = this.h1;
  42516. var h2 = this.h2;
  42517. var C1 = 0xcc9e2d51;
  42518. var C2 = 0x1b873593;
  42519. var C1_LOW = C1 & MASK_LOW;
  42520. var C2_LOW = C2 & MASK_LOW;
  42521. for (i = 0; i < blockCounts; i++) {
  42522. if (i & 1) {
  42523. k1 = dataUint32[i];
  42524. k1 = (k1 * C1 & MASK_HIGH) | (k1 * C1_LOW & MASK_LOW);
  42525. k1 = k1 << 15 | k1 >>> 17;
  42526. k1 = (k1 * C2 & MASK_HIGH) | (k1 * C2_LOW & MASK_LOW);
  42527. h1 ^= k1;
  42528. h1 = h1 << 13 | h1 >>> 19;
  42529. h1 = h1 * 5 + 0xe6546b64;
  42530. } else {
  42531. k2 = dataUint32[i];
  42532. k2 = (k2 * C1 & MASK_HIGH) | (k2 * C1_LOW & MASK_LOW);
  42533. k2 = k2 << 15 | k2 >>> 17;
  42534. k2 = (k2 * C2 & MASK_HIGH) | (k2 * C2_LOW & MASK_LOW);
  42535. h2 ^= k2;
  42536. h2 = h2 << 13 | h2 >>> 19;
  42537. h2 = h2 * 5 + 0xe6546b64;
  42538. }
  42539. }
  42540. k1 = 0;
  42541. switch (tailLength) {
  42542. case 3:
  42543. k1 ^= data[blockCounts * 4 + 2] << 16;
  42544. /* falls through */
  42545. case 2:
  42546. k1 ^= data[blockCounts * 4 + 1] << 8;
  42547. /* falls through */
  42548. case 1:
  42549. k1 ^= data[blockCounts * 4];
  42550. /* falls through */
  42551. k1 = (k1 * C1 & MASK_HIGH) | (k1 * C1_LOW & MASK_LOW);
  42552. k1 = k1 << 15 | k1 >>> 17;
  42553. k1 = (k1 * C2 & MASK_HIGH) | (k1 * C2_LOW & MASK_LOW);
  42554. if (blockCounts & 1) {
  42555. h1 ^= k1;
  42556. } else {
  42557. h2 ^= k1;
  42558. }
  42559. }
  42560. this.h1 = h1;
  42561. this.h2 = h2;
  42562. return this;
  42563. },
  42564. hexdigest: function MurmurHash3_64_hexdigest () {
  42565. var h1 = this.h1;
  42566. var h2 = this.h2;
  42567. h1 ^= h2 >>> 1;
  42568. h1 = (h1 * 0xed558ccd & MASK_HIGH) | (h1 * 0x8ccd & MASK_LOW);
  42569. h2 = (h2 * 0xff51afd7 & MASK_HIGH) |
  42570. (((h2 << 16 | h1 >>> 16) * 0xafd7ed55 & MASK_HIGH) >>> 16);
  42571. h1 ^= h2 >>> 1;
  42572. h1 = (h1 * 0x1a85ec53 & MASK_HIGH) | (h1 * 0xec53 & MASK_LOW);
  42573. h2 = (h2 * 0xc4ceb9fe & MASK_HIGH) |
  42574. (((h2 << 16 | h1 >>> 16) * 0xb9fe1a85 & MASK_HIGH) >>> 16);
  42575. h1 ^= h2 >>> 1;
  42576. for (var i = 0, arr = [h1, h2], str = ''; i < arr.length; i++) {
  42577. var hex = (arr[i] >>> 0).toString(16);
  42578. while (hex.length < 8) {
  42579. hex = '0' + hex;
  42580. }
  42581. str += hex;
  42582. }
  42583. return str;
  42584. }
  42585. };
  42586. return MurmurHash3_64;
  42587. })();
  42588. }).call((typeof window === 'undefined') ? this : window);
  42589. if (!PDFJS.workerSrc && typeof document !== 'undefined') {
  42590. // workerSrc is not set -- using last script url to define default location
  42591. PDFJS.workerSrc = (function () {
  42592. 'use strict';
  42593. var scriptTagContainer = document.body ||
  42594. document.getElementsByTagName('head')[0];
  42595. var pdfjsSrc = scriptTagContainer.lastChild.src;
  42596. return pdfjsSrc && pdfjsSrc.replace(/\.js$/i, '.worker.js');
  42597. })();
  42598. }