opentype.module.js 458 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568
  1. /**
  2. * https://opentype.js.org v1.3.4 | (c) Frederik De Bleser and other contributors | MIT License | Uses tiny-inflate by Devon Govett and string.prototype.codepointat polyfill by Mathias Bynens
  3. */
  4. /*! https://mths.be/codepointat v0.2.0 by @mathias */
  5. if (!String.prototype.codePointAt) {
  6. (function() {
  7. var defineProperty = (function() {
  8. // IE 8 only supports `Object.defineProperty` on DOM elements
  9. try {
  10. var object = {};
  11. var $defineProperty = Object.defineProperty;
  12. var result = $defineProperty(object, object, object) && $defineProperty;
  13. } catch(error) {}
  14. return result;
  15. }());
  16. var codePointAt = function(position) {
  17. if (this == null) {
  18. throw TypeError();
  19. }
  20. var string = String(this);
  21. var size = string.length;
  22. // `ToInteger`
  23. var index = position ? Number(position) : 0;
  24. if (index != index) { // better `isNaN`
  25. index = 0;
  26. }
  27. // Account for out-of-bounds indices:
  28. if (index < 0 || index >= size) {
  29. return undefined;
  30. }
  31. // Get the first code unit
  32. var first = string.charCodeAt(index);
  33. var second;
  34. if ( // check if it’s the start of a surrogate pair
  35. first >= 0xD800 && first <= 0xDBFF && // high surrogate
  36. size > index + 1 // there is a next code unit
  37. ) {
  38. second = string.charCodeAt(index + 1);
  39. if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
  40. // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
  41. return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
  42. }
  43. }
  44. return first;
  45. };
  46. if (defineProperty) {
  47. defineProperty(String.prototype, 'codePointAt', {
  48. 'value': codePointAt,
  49. 'configurable': true,
  50. 'writable': true
  51. });
  52. } else {
  53. String.prototype.codePointAt = codePointAt;
  54. }
  55. }());
  56. }
  57. var TINF_OK = 0;
  58. var TINF_DATA_ERROR = -3;
  59. function Tree() {
  60. this.table = new Uint16Array(16); /* table of code length counts */
  61. this.trans = new Uint16Array(288); /* code -> symbol translation table */
  62. }
  63. function Data(source, dest) {
  64. this.source = source;
  65. this.sourceIndex = 0;
  66. this.tag = 0;
  67. this.bitcount = 0;
  68. this.dest = dest;
  69. this.destLen = 0;
  70. this.ltree = new Tree(); /* dynamic length/symbol tree */
  71. this.dtree = new Tree(); /* dynamic distance tree */
  72. }
  73. /* --------------------------------------------------- *
  74. * -- uninitialized global data (static structures) -- *
  75. * --------------------------------------------------- */
  76. var sltree = new Tree();
  77. var sdtree = new Tree();
  78. /* extra bits and base tables for length codes */
  79. var length_bits = new Uint8Array(30);
  80. var length_base = new Uint16Array(30);
  81. /* extra bits and base tables for distance codes */
  82. var dist_bits = new Uint8Array(30);
  83. var dist_base = new Uint16Array(30);
  84. /* special ordering of code length codes */
  85. var clcidx = new Uint8Array([
  86. 16, 17, 18, 0, 8, 7, 9, 6,
  87. 10, 5, 11, 4, 12, 3, 13, 2,
  88. 14, 1, 15
  89. ]);
  90. /* used by tinf_decode_trees, avoids allocations every call */
  91. var code_tree = new Tree();
  92. var lengths = new Uint8Array(288 + 32);
  93. /* ----------------------- *
  94. * -- utility functions -- *
  95. * ----------------------- */
  96. /* build extra bits and base tables */
  97. function tinf_build_bits_base(bits, base, delta, first) {
  98. var i, sum;
  99. /* build bits table */
  100. for (i = 0; i < delta; ++i) { bits[i] = 0; }
  101. for (i = 0; i < 30 - delta; ++i) { bits[i + delta] = i / delta | 0; }
  102. /* build base table */
  103. for (sum = first, i = 0; i < 30; ++i) {
  104. base[i] = sum;
  105. sum += 1 << bits[i];
  106. }
  107. }
  108. /* build the fixed huffman trees */
  109. function tinf_build_fixed_trees(lt, dt) {
  110. var i;
  111. /* build fixed length tree */
  112. for (i = 0; i < 7; ++i) { lt.table[i] = 0; }
  113. lt.table[7] = 24;
  114. lt.table[8] = 152;
  115. lt.table[9] = 112;
  116. for (i = 0; i < 24; ++i) { lt.trans[i] = 256 + i; }
  117. for (i = 0; i < 144; ++i) { lt.trans[24 + i] = i; }
  118. for (i = 0; i < 8; ++i) { lt.trans[24 + 144 + i] = 280 + i; }
  119. for (i = 0; i < 112; ++i) { lt.trans[24 + 144 + 8 + i] = 144 + i; }
  120. /* build fixed distance tree */
  121. for (i = 0; i < 5; ++i) { dt.table[i] = 0; }
  122. dt.table[5] = 32;
  123. for (i = 0; i < 32; ++i) { dt.trans[i] = i; }
  124. }
  125. /* given an array of code lengths, build a tree */
  126. var offs = new Uint16Array(16);
  127. function tinf_build_tree(t, lengths, off, num) {
  128. var i, sum;
  129. /* clear code length count table */
  130. for (i = 0; i < 16; ++i) { t.table[i] = 0; }
  131. /* scan symbol lengths, and sum code length counts */
  132. for (i = 0; i < num; ++i) { t.table[lengths[off + i]]++; }
  133. t.table[0] = 0;
  134. /* compute offset table for distribution sort */
  135. for (sum = 0, i = 0; i < 16; ++i) {
  136. offs[i] = sum;
  137. sum += t.table[i];
  138. }
  139. /* create code->symbol translation table (symbols sorted by code) */
  140. for (i = 0; i < num; ++i) {
  141. if (lengths[off + i]) { t.trans[offs[lengths[off + i]]++] = i; }
  142. }
  143. }
  144. /* ---------------------- *
  145. * -- decode functions -- *
  146. * ---------------------- */
  147. /* get one bit from source stream */
  148. function tinf_getbit(d) {
  149. /* check if tag is empty */
  150. if (!d.bitcount--) {
  151. /* load next tag */
  152. d.tag = d.source[d.sourceIndex++];
  153. d.bitcount = 7;
  154. }
  155. /* shift bit out of tag */
  156. var bit = d.tag & 1;
  157. d.tag >>>= 1;
  158. return bit;
  159. }
  160. /* read a num bit value from a stream and add base */
  161. function tinf_read_bits(d, num, base) {
  162. if (!num)
  163. { return base; }
  164. while (d.bitcount < 24) {
  165. d.tag |= d.source[d.sourceIndex++] << d.bitcount;
  166. d.bitcount += 8;
  167. }
  168. var val = d.tag & (0xffff >>> (16 - num));
  169. d.tag >>>= num;
  170. d.bitcount -= num;
  171. return val + base;
  172. }
  173. /* given a data stream and a tree, decode a symbol */
  174. function tinf_decode_symbol(d, t) {
  175. while (d.bitcount < 24) {
  176. d.tag |= d.source[d.sourceIndex++] << d.bitcount;
  177. d.bitcount += 8;
  178. }
  179. var sum = 0, cur = 0, len = 0;
  180. var tag = d.tag;
  181. /* get more bits while code value is above sum */
  182. do {
  183. cur = 2 * cur + (tag & 1);
  184. tag >>>= 1;
  185. ++len;
  186. sum += t.table[len];
  187. cur -= t.table[len];
  188. } while (cur >= 0);
  189. d.tag = tag;
  190. d.bitcount -= len;
  191. return t.trans[sum + cur];
  192. }
  193. /* given a data stream, decode dynamic trees from it */
  194. function tinf_decode_trees(d, lt, dt) {
  195. var hlit, hdist, hclen;
  196. var i, num, length;
  197. /* get 5 bits HLIT (257-286) */
  198. hlit = tinf_read_bits(d, 5, 257);
  199. /* get 5 bits HDIST (1-32) */
  200. hdist = tinf_read_bits(d, 5, 1);
  201. /* get 4 bits HCLEN (4-19) */
  202. hclen = tinf_read_bits(d, 4, 4);
  203. for (i = 0; i < 19; ++i) { lengths[i] = 0; }
  204. /* read code lengths for code length alphabet */
  205. for (i = 0; i < hclen; ++i) {
  206. /* get 3 bits code length (0-7) */
  207. var clen = tinf_read_bits(d, 3, 0);
  208. lengths[clcidx[i]] = clen;
  209. }
  210. /* build code length tree */
  211. tinf_build_tree(code_tree, lengths, 0, 19);
  212. /* decode code lengths for the dynamic trees */
  213. for (num = 0; num < hlit + hdist;) {
  214. var sym = tinf_decode_symbol(d, code_tree);
  215. switch (sym) {
  216. case 16:
  217. /* copy previous code length 3-6 times (read 2 bits) */
  218. var prev = lengths[num - 1];
  219. for (length = tinf_read_bits(d, 2, 3); length; --length) {
  220. lengths[num++] = prev;
  221. }
  222. break;
  223. case 17:
  224. /* repeat code length 0 for 3-10 times (read 3 bits) */
  225. for (length = tinf_read_bits(d, 3, 3); length; --length) {
  226. lengths[num++] = 0;
  227. }
  228. break;
  229. case 18:
  230. /* repeat code length 0 for 11-138 times (read 7 bits) */
  231. for (length = tinf_read_bits(d, 7, 11); length; --length) {
  232. lengths[num++] = 0;
  233. }
  234. break;
  235. default:
  236. /* values 0-15 represent the actual code lengths */
  237. lengths[num++] = sym;
  238. break;
  239. }
  240. }
  241. /* build dynamic trees */
  242. tinf_build_tree(lt, lengths, 0, hlit);
  243. tinf_build_tree(dt, lengths, hlit, hdist);
  244. }
  245. /* ----------------------------- *
  246. * -- block inflate functions -- *
  247. * ----------------------------- */
  248. /* given a stream and two trees, inflate a block of data */
  249. function tinf_inflate_block_data(d, lt, dt) {
  250. while (1) {
  251. var sym = tinf_decode_symbol(d, lt);
  252. /* check for end of block */
  253. if (sym === 256) {
  254. return TINF_OK;
  255. }
  256. if (sym < 256) {
  257. d.dest[d.destLen++] = sym;
  258. } else {
  259. var length, dist, offs;
  260. var i;
  261. sym -= 257;
  262. /* possibly get more bits from length code */
  263. length = tinf_read_bits(d, length_bits[sym], length_base[sym]);
  264. dist = tinf_decode_symbol(d, dt);
  265. /* possibly get more bits from distance code */
  266. offs = d.destLen - tinf_read_bits(d, dist_bits[dist], dist_base[dist]);
  267. /* copy match */
  268. for (i = offs; i < offs + length; ++i) {
  269. d.dest[d.destLen++] = d.dest[i];
  270. }
  271. }
  272. }
  273. }
  274. /* inflate an uncompressed block of data */
  275. function tinf_inflate_uncompressed_block(d) {
  276. var length, invlength;
  277. var i;
  278. /* unread from bitbuffer */
  279. while (d.bitcount > 8) {
  280. d.sourceIndex--;
  281. d.bitcount -= 8;
  282. }
  283. /* get length */
  284. length = d.source[d.sourceIndex + 1];
  285. length = 256 * length + d.source[d.sourceIndex];
  286. /* get one's complement of length */
  287. invlength = d.source[d.sourceIndex + 3];
  288. invlength = 256 * invlength + d.source[d.sourceIndex + 2];
  289. /* check length */
  290. if (length !== (~invlength & 0x0000ffff))
  291. { return TINF_DATA_ERROR; }
  292. d.sourceIndex += 4;
  293. /* copy block */
  294. for (i = length; i; --i)
  295. { d.dest[d.destLen++] = d.source[d.sourceIndex++]; }
  296. /* make sure we start next block on a byte boundary */
  297. d.bitcount = 0;
  298. return TINF_OK;
  299. }
  300. /* inflate stream from source to dest */
  301. function tinf_uncompress(source, dest) {
  302. var d = new Data(source, dest);
  303. var bfinal, btype, res;
  304. do {
  305. /* read final block flag */
  306. bfinal = tinf_getbit(d);
  307. /* read block type (2 bits) */
  308. btype = tinf_read_bits(d, 2, 0);
  309. /* decompress block */
  310. switch (btype) {
  311. case 0:
  312. /* decompress uncompressed block */
  313. res = tinf_inflate_uncompressed_block(d);
  314. break;
  315. case 1:
  316. /* decompress block with fixed huffman trees */
  317. res = tinf_inflate_block_data(d, sltree, sdtree);
  318. break;
  319. case 2:
  320. /* decompress block with dynamic huffman trees */
  321. tinf_decode_trees(d, d.ltree, d.dtree);
  322. res = tinf_inflate_block_data(d, d.ltree, d.dtree);
  323. break;
  324. default:
  325. res = TINF_DATA_ERROR;
  326. }
  327. if (res !== TINF_OK)
  328. { throw new Error('Data error'); }
  329. } while (!bfinal);
  330. if (d.destLen < d.dest.length) {
  331. if (typeof d.dest.slice === 'function')
  332. { return d.dest.slice(0, d.destLen); }
  333. else
  334. { return d.dest.subarray(0, d.destLen); }
  335. }
  336. return d.dest;
  337. }
  338. /* -------------------- *
  339. * -- initialization -- *
  340. * -------------------- */
  341. /* build fixed huffman trees */
  342. tinf_build_fixed_trees(sltree, sdtree);
  343. /* build extra bits and base tables */
  344. tinf_build_bits_base(length_bits, length_base, 4, 3);
  345. tinf_build_bits_base(dist_bits, dist_base, 2, 1);
  346. /* fix a special case */
  347. length_bits[28] = 0;
  348. length_base[28] = 258;
  349. var tinyInflate = tinf_uncompress;
  350. // The Bounding Box object
  351. function derive(v0, v1, v2, v3, t) {
  352. return Math.pow(1 - t, 3) * v0 +
  353. 3 * Math.pow(1 - t, 2) * t * v1 +
  354. 3 * (1 - t) * Math.pow(t, 2) * v2 +
  355. Math.pow(t, 3) * v3;
  356. }
  357. /**
  358. * A bounding box is an enclosing box that describes the smallest measure within which all the points lie.
  359. * It is used to calculate the bounding box of a glyph or text path.
  360. *
  361. * On initialization, x1/y1/x2/y2 will be NaN. Check if the bounding box is empty using `isEmpty()`.
  362. *
  363. * @exports opentype.BoundingBox
  364. * @class
  365. * @constructor
  366. */
  367. function BoundingBox() {
  368. this.x1 = Number.NaN;
  369. this.y1 = Number.NaN;
  370. this.x2 = Number.NaN;
  371. this.y2 = Number.NaN;
  372. }
  373. /**
  374. * Returns true if the bounding box is empty, that is, no points have been added to the box yet.
  375. */
  376. BoundingBox.prototype.isEmpty = function() {
  377. return isNaN(this.x1) || isNaN(this.y1) || isNaN(this.x2) || isNaN(this.y2);
  378. };
  379. /**
  380. * Add the point to the bounding box.
  381. * The x1/y1/x2/y2 coordinates of the bounding box will now encompass the given point.
  382. * @param {number} x - The X coordinate of the point.
  383. * @param {number} y - The Y coordinate of the point.
  384. */
  385. BoundingBox.prototype.addPoint = function(x, y) {
  386. if (typeof x === 'number') {
  387. if (isNaN(this.x1) || isNaN(this.x2)) {
  388. this.x1 = x;
  389. this.x2 = x;
  390. }
  391. if (x < this.x1) {
  392. this.x1 = x;
  393. }
  394. if (x > this.x2) {
  395. this.x2 = x;
  396. }
  397. }
  398. if (typeof y === 'number') {
  399. if (isNaN(this.y1) || isNaN(this.y2)) {
  400. this.y1 = y;
  401. this.y2 = y;
  402. }
  403. if (y < this.y1) {
  404. this.y1 = y;
  405. }
  406. if (y > this.y2) {
  407. this.y2 = y;
  408. }
  409. }
  410. };
  411. /**
  412. * Add a X coordinate to the bounding box.
  413. * This extends the bounding box to include the X coordinate.
  414. * This function is used internally inside of addBezier.
  415. * @param {number} x - The X coordinate of the point.
  416. */
  417. BoundingBox.prototype.addX = function(x) {
  418. this.addPoint(x, null);
  419. };
  420. /**
  421. * Add a Y coordinate to the bounding box.
  422. * This extends the bounding box to include the Y coordinate.
  423. * This function is used internally inside of addBezier.
  424. * @param {number} y - The Y coordinate of the point.
  425. */
  426. BoundingBox.prototype.addY = function(y) {
  427. this.addPoint(null, y);
  428. };
  429. /**
  430. * Add a Bézier curve to the bounding box.
  431. * This extends the bounding box to include the entire Bézier.
  432. * @param {number} x0 - The starting X coordinate.
  433. * @param {number} y0 - The starting Y coordinate.
  434. * @param {number} x1 - The X coordinate of the first control point.
  435. * @param {number} y1 - The Y coordinate of the first control point.
  436. * @param {number} x2 - The X coordinate of the second control point.
  437. * @param {number} y2 - The Y coordinate of the second control point.
  438. * @param {number} x - The ending X coordinate.
  439. * @param {number} y - The ending Y coordinate.
  440. */
  441. BoundingBox.prototype.addBezier = function(x0, y0, x1, y1, x2, y2, x, y) {
  442. // This code is based on http://nishiohirokazu.blogspot.com/2009/06/how-to-calculate-bezier-curves-bounding.html
  443. // and https://github.com/icons8/svg-path-bounding-box
  444. var p0 = [x0, y0];
  445. var p1 = [x1, y1];
  446. var p2 = [x2, y2];
  447. var p3 = [x, y];
  448. this.addPoint(x0, y0);
  449. this.addPoint(x, y);
  450. for (var i = 0; i <= 1; i++) {
  451. var b = 6 * p0[i] - 12 * p1[i] + 6 * p2[i];
  452. var a = -3 * p0[i] + 9 * p1[i] - 9 * p2[i] + 3 * p3[i];
  453. var c = 3 * p1[i] - 3 * p0[i];
  454. if (a === 0) {
  455. if (b === 0) { continue; }
  456. var t = -c / b;
  457. if (0 < t && t < 1) {
  458. if (i === 0) { this.addX(derive(p0[i], p1[i], p2[i], p3[i], t)); }
  459. if (i === 1) { this.addY(derive(p0[i], p1[i], p2[i], p3[i], t)); }
  460. }
  461. continue;
  462. }
  463. var b2ac = Math.pow(b, 2) - 4 * c * a;
  464. if (b2ac < 0) { continue; }
  465. var t1 = (-b + Math.sqrt(b2ac)) / (2 * a);
  466. if (0 < t1 && t1 < 1) {
  467. if (i === 0) { this.addX(derive(p0[i], p1[i], p2[i], p3[i], t1)); }
  468. if (i === 1) { this.addY(derive(p0[i], p1[i], p2[i], p3[i], t1)); }
  469. }
  470. var t2 = (-b - Math.sqrt(b2ac)) / (2 * a);
  471. if (0 < t2 && t2 < 1) {
  472. if (i === 0) { this.addX(derive(p0[i], p1[i], p2[i], p3[i], t2)); }
  473. if (i === 1) { this.addY(derive(p0[i], p1[i], p2[i], p3[i], t2)); }
  474. }
  475. }
  476. };
  477. /**
  478. * Add a quadratic curve to the bounding box.
  479. * This extends the bounding box to include the entire quadratic curve.
  480. * @param {number} x0 - The starting X coordinate.
  481. * @param {number} y0 - The starting Y coordinate.
  482. * @param {number} x1 - The X coordinate of the control point.
  483. * @param {number} y1 - The Y coordinate of the control point.
  484. * @param {number} x - The ending X coordinate.
  485. * @param {number} y - The ending Y coordinate.
  486. */
  487. BoundingBox.prototype.addQuad = function(x0, y0, x1, y1, x, y) {
  488. var cp1x = x0 + 2 / 3 * (x1 - x0);
  489. var cp1y = y0 + 2 / 3 * (y1 - y0);
  490. var cp2x = cp1x + 1 / 3 * (x - x0);
  491. var cp2y = cp1y + 1 / 3 * (y - y0);
  492. this.addBezier(x0, y0, cp1x, cp1y, cp2x, cp2y, x, y);
  493. };
  494. // Geometric objects
  495. /**
  496. * A bézier path containing a set of path commands similar to a SVG path.
  497. * Paths can be drawn on a context using `draw`.
  498. * @exports opentype.Path
  499. * @class
  500. * @constructor
  501. */
  502. function Path() {
  503. this.commands = [];
  504. this.fill = 'black';
  505. this.stroke = null;
  506. this.strokeWidth = 1;
  507. }
  508. /**
  509. * @param {number} x
  510. * @param {number} y
  511. */
  512. Path.prototype.moveTo = function(x, y) {
  513. this.commands.push({
  514. type: 'M',
  515. x: x,
  516. y: y
  517. });
  518. };
  519. /**
  520. * @param {number} x
  521. * @param {number} y
  522. */
  523. Path.prototype.lineTo = function(x, y) {
  524. this.commands.push({
  525. type: 'L',
  526. x: x,
  527. y: y
  528. });
  529. };
  530. /**
  531. * Draws cubic curve
  532. * @function
  533. * curveTo
  534. * @memberof opentype.Path.prototype
  535. * @param {number} x1 - x of control 1
  536. * @param {number} y1 - y of control 1
  537. * @param {number} x2 - x of control 2
  538. * @param {number} y2 - y of control 2
  539. * @param {number} x - x of path point
  540. * @param {number} y - y of path point
  541. */
  542. /**
  543. * Draws cubic curve
  544. * @function
  545. * bezierCurveTo
  546. * @memberof opentype.Path.prototype
  547. * @param {number} x1 - x of control 1
  548. * @param {number} y1 - y of control 1
  549. * @param {number} x2 - x of control 2
  550. * @param {number} y2 - y of control 2
  551. * @param {number} x - x of path point
  552. * @param {number} y - y of path point
  553. * @see curveTo
  554. */
  555. Path.prototype.curveTo = Path.prototype.bezierCurveTo = function(x1, y1, x2, y2, x, y) {
  556. this.commands.push({
  557. type: 'C',
  558. x1: x1,
  559. y1: y1,
  560. x2: x2,
  561. y2: y2,
  562. x: x,
  563. y: y
  564. });
  565. };
  566. /**
  567. * Draws quadratic curve
  568. * @function
  569. * quadraticCurveTo
  570. * @memberof opentype.Path.prototype
  571. * @param {number} x1 - x of control
  572. * @param {number} y1 - y of control
  573. * @param {number} x - x of path point
  574. * @param {number} y - y of path point
  575. */
  576. /**
  577. * Draws quadratic curve
  578. * @function
  579. * quadTo
  580. * @memberof opentype.Path.prototype
  581. * @param {number} x1 - x of control
  582. * @param {number} y1 - y of control
  583. * @param {number} x - x of path point
  584. * @param {number} y - y of path point
  585. */
  586. Path.prototype.quadTo = Path.prototype.quadraticCurveTo = function(x1, y1, x, y) {
  587. this.commands.push({
  588. type: 'Q',
  589. x1: x1,
  590. y1: y1,
  591. x: x,
  592. y: y
  593. });
  594. };
  595. /**
  596. * Closes the path
  597. * @function closePath
  598. * @memberof opentype.Path.prototype
  599. */
  600. /**
  601. * Close the path
  602. * @function close
  603. * @memberof opentype.Path.prototype
  604. */
  605. Path.prototype.close = Path.prototype.closePath = function() {
  606. this.commands.push({
  607. type: 'Z'
  608. });
  609. };
  610. /**
  611. * Add the given path or list of commands to the commands of this path.
  612. * @param {Array} pathOrCommands - another opentype.Path, an opentype.BoundingBox, or an array of commands.
  613. */
  614. Path.prototype.extend = function(pathOrCommands) {
  615. if (pathOrCommands.commands) {
  616. pathOrCommands = pathOrCommands.commands;
  617. } else if (pathOrCommands instanceof BoundingBox) {
  618. var box = pathOrCommands;
  619. this.moveTo(box.x1, box.y1);
  620. this.lineTo(box.x2, box.y1);
  621. this.lineTo(box.x2, box.y2);
  622. this.lineTo(box.x1, box.y2);
  623. this.close();
  624. return;
  625. }
  626. Array.prototype.push.apply(this.commands, pathOrCommands);
  627. };
  628. /**
  629. * Calculate the bounding box of the path.
  630. * @returns {opentype.BoundingBox}
  631. */
  632. Path.prototype.getBoundingBox = function() {
  633. var box = new BoundingBox();
  634. var startX = 0;
  635. var startY = 0;
  636. var prevX = 0;
  637. var prevY = 0;
  638. for (var i = 0; i < this.commands.length; i++) {
  639. var cmd = this.commands[i];
  640. switch (cmd.type) {
  641. case 'M':
  642. box.addPoint(cmd.x, cmd.y);
  643. startX = prevX = cmd.x;
  644. startY = prevY = cmd.y;
  645. break;
  646. case 'L':
  647. box.addPoint(cmd.x, cmd.y);
  648. prevX = cmd.x;
  649. prevY = cmd.y;
  650. break;
  651. case 'Q':
  652. box.addQuad(prevX, prevY, cmd.x1, cmd.y1, cmd.x, cmd.y);
  653. prevX = cmd.x;
  654. prevY = cmd.y;
  655. break;
  656. case 'C':
  657. box.addBezier(prevX, prevY, cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y);
  658. prevX = cmd.x;
  659. prevY = cmd.y;
  660. break;
  661. case 'Z':
  662. prevX = startX;
  663. prevY = startY;
  664. break;
  665. default:
  666. throw new Error('Unexpected path command ' + cmd.type);
  667. }
  668. }
  669. if (box.isEmpty()) {
  670. box.addPoint(0, 0);
  671. }
  672. return box;
  673. };
  674. /**
  675. * Draw the path to a 2D context.
  676. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context.
  677. */
  678. Path.prototype.draw = function(ctx) {
  679. ctx.beginPath();
  680. for (var i = 0; i < this.commands.length; i += 1) {
  681. var cmd = this.commands[i];
  682. if (cmd.type === 'M') {
  683. ctx.moveTo(cmd.x, cmd.y);
  684. } else if (cmd.type === 'L') {
  685. ctx.lineTo(cmd.x, cmd.y);
  686. } else if (cmd.type === 'C') {
  687. ctx.bezierCurveTo(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y);
  688. } else if (cmd.type === 'Q') {
  689. ctx.quadraticCurveTo(cmd.x1, cmd.y1, cmd.x, cmd.y);
  690. } else if (cmd.type === 'Z') {
  691. ctx.closePath();
  692. }
  693. }
  694. if (this.fill) {
  695. ctx.fillStyle = this.fill;
  696. ctx.fill();
  697. }
  698. if (this.stroke) {
  699. ctx.strokeStyle = this.stroke;
  700. ctx.lineWidth = this.strokeWidth;
  701. ctx.stroke();
  702. }
  703. };
  704. /**
  705. * Convert the Path to a string of path data instructions
  706. * See http://www.w3.org/TR/SVG/paths.html#PathData
  707. * @param {number} [decimalPlaces=2] - The amount of decimal places for floating-point values
  708. * @return {string}
  709. */
  710. Path.prototype.toPathData = function(decimalPlaces) {
  711. decimalPlaces = decimalPlaces !== undefined ? decimalPlaces : 2;
  712. function floatToString(v) {
  713. if (Math.round(v) === v) {
  714. return '' + Math.round(v);
  715. } else {
  716. return v.toFixed(decimalPlaces);
  717. }
  718. }
  719. function packValues() {
  720. var arguments$1 = arguments;
  721. var s = '';
  722. for (var i = 0; i < arguments.length; i += 1) {
  723. var v = arguments$1[i];
  724. if (v >= 0 && i > 0) {
  725. s += ' ';
  726. }
  727. s += floatToString(v);
  728. }
  729. return s;
  730. }
  731. var d = '';
  732. for (var i = 0; i < this.commands.length; i += 1) {
  733. var cmd = this.commands[i];
  734. if (cmd.type === 'M') {
  735. d += 'M' + packValues(cmd.x, cmd.y);
  736. } else if (cmd.type === 'L') {
  737. d += 'L' + packValues(cmd.x, cmd.y);
  738. } else if (cmd.type === 'C') {
  739. d += 'C' + packValues(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y);
  740. } else if (cmd.type === 'Q') {
  741. d += 'Q' + packValues(cmd.x1, cmd.y1, cmd.x, cmd.y);
  742. } else if (cmd.type === 'Z') {
  743. d += 'Z';
  744. }
  745. }
  746. return d;
  747. };
  748. /**
  749. * Convert the path to an SVG <path> element, as a string.
  750. * @param {number} [decimalPlaces=2] - The amount of decimal places for floating-point values
  751. * @return {string}
  752. */
  753. Path.prototype.toSVG = function(decimalPlaces) {
  754. var svg = '<path d="';
  755. svg += this.toPathData(decimalPlaces);
  756. svg += '"';
  757. if (this.fill && this.fill !== 'black') {
  758. if (this.fill === null) {
  759. svg += ' fill="none"';
  760. } else {
  761. svg += ' fill="' + this.fill + '"';
  762. }
  763. }
  764. if (this.stroke) {
  765. svg += ' stroke="' + this.stroke + '" stroke-width="' + this.strokeWidth + '"';
  766. }
  767. svg += '/>';
  768. return svg;
  769. };
  770. /**
  771. * Convert the path to a DOM element.
  772. * @param {number} [decimalPlaces=2] - The amount of decimal places for floating-point values
  773. * @return {SVGPathElement}
  774. */
  775. Path.prototype.toDOMElement = function(decimalPlaces) {
  776. var temporaryPath = this.toPathData(decimalPlaces);
  777. var newPath = document.createElementNS('http://www.w3.org/2000/svg', 'path');
  778. newPath.setAttribute('d', temporaryPath);
  779. return newPath;
  780. };
  781. // Run-time checking of preconditions.
  782. function fail(message) {
  783. throw new Error(message);
  784. }
  785. // Precondition function that checks if the given predicate is true.
  786. // If not, it will throw an error.
  787. function argument(predicate, message) {
  788. if (!predicate) {
  789. fail(message);
  790. }
  791. }
  792. var check = { fail: fail, argument: argument, assert: argument };
  793. // Data types used in the OpenType font file.
  794. var LIMIT16 = 32768; // The limit at which a 16-bit number switches signs == 2^15
  795. var LIMIT32 = 2147483648; // The limit at which a 32-bit number switches signs == 2 ^ 31
  796. /**
  797. * @exports opentype.decode
  798. * @class
  799. */
  800. var decode = {};
  801. /**
  802. * @exports opentype.encode
  803. * @class
  804. */
  805. var encode = {};
  806. /**
  807. * @exports opentype.sizeOf
  808. * @class
  809. */
  810. var sizeOf = {};
  811. // Return a function that always returns the same value.
  812. function constant(v) {
  813. return function() {
  814. return v;
  815. };
  816. }
  817. // OpenType data types //////////////////////////////////////////////////////
  818. /**
  819. * Convert an 8-bit unsigned integer to a list of 1 byte.
  820. * @param {number}
  821. * @returns {Array}
  822. */
  823. encode.BYTE = function(v) {
  824. check.argument(v >= 0 && v <= 255, 'Byte value should be between 0 and 255.');
  825. return [v];
  826. };
  827. /**
  828. * @constant
  829. * @type {number}
  830. */
  831. sizeOf.BYTE = constant(1);
  832. /**
  833. * Convert a 8-bit signed integer to a list of 1 byte.
  834. * @param {string}
  835. * @returns {Array}
  836. */
  837. encode.CHAR = function(v) {
  838. return [v.charCodeAt(0)];
  839. };
  840. /**
  841. * @constant
  842. * @type {number}
  843. */
  844. sizeOf.CHAR = constant(1);
  845. /**
  846. * Convert an ASCII string to a list of bytes.
  847. * @param {string}
  848. * @returns {Array}
  849. */
  850. encode.CHARARRAY = function(v) {
  851. if (typeof v === 'undefined') {
  852. v = '';
  853. console.warn('Undefined CHARARRAY encountered and treated as an empty string. This is probably caused by a missing glyph name.');
  854. }
  855. var b = [];
  856. for (var i = 0; i < v.length; i += 1) {
  857. b[i] = v.charCodeAt(i);
  858. }
  859. return b;
  860. };
  861. /**
  862. * @param {Array}
  863. * @returns {number}
  864. */
  865. sizeOf.CHARARRAY = function(v) {
  866. if (typeof v === 'undefined') {
  867. return 0;
  868. }
  869. return v.length;
  870. };
  871. /**
  872. * Convert a 16-bit unsigned integer to a list of 2 bytes.
  873. * @param {number}
  874. * @returns {Array}
  875. */
  876. encode.USHORT = function(v) {
  877. return [(v >> 8) & 0xFF, v & 0xFF];
  878. };
  879. /**
  880. * @constant
  881. * @type {number}
  882. */
  883. sizeOf.USHORT = constant(2);
  884. /**
  885. * Convert a 16-bit signed integer to a list of 2 bytes.
  886. * @param {number}
  887. * @returns {Array}
  888. */
  889. encode.SHORT = function(v) {
  890. // Two's complement
  891. if (v >= LIMIT16) {
  892. v = -(2 * LIMIT16 - v);
  893. }
  894. return [(v >> 8) & 0xFF, v & 0xFF];
  895. };
  896. /**
  897. * @constant
  898. * @type {number}
  899. */
  900. sizeOf.SHORT = constant(2);
  901. /**
  902. * Convert a 24-bit unsigned integer to a list of 3 bytes.
  903. * @param {number}
  904. * @returns {Array}
  905. */
  906. encode.UINT24 = function(v) {
  907. return [(v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF];
  908. };
  909. /**
  910. * @constant
  911. * @type {number}
  912. */
  913. sizeOf.UINT24 = constant(3);
  914. /**
  915. * Convert a 32-bit unsigned integer to a list of 4 bytes.
  916. * @param {number}
  917. * @returns {Array}
  918. */
  919. encode.ULONG = function(v) {
  920. return [(v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF];
  921. };
  922. /**
  923. * @constant
  924. * @type {number}
  925. */
  926. sizeOf.ULONG = constant(4);
  927. /**
  928. * Convert a 32-bit unsigned integer to a list of 4 bytes.
  929. * @param {number}
  930. * @returns {Array}
  931. */
  932. encode.LONG = function(v) {
  933. // Two's complement
  934. if (v >= LIMIT32) {
  935. v = -(2 * LIMIT32 - v);
  936. }
  937. return [(v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF];
  938. };
  939. /**
  940. * @constant
  941. * @type {number}
  942. */
  943. sizeOf.LONG = constant(4);
  944. encode.FIXED = encode.ULONG;
  945. sizeOf.FIXED = sizeOf.ULONG;
  946. encode.FWORD = encode.SHORT;
  947. sizeOf.FWORD = sizeOf.SHORT;
  948. encode.UFWORD = encode.USHORT;
  949. sizeOf.UFWORD = sizeOf.USHORT;
  950. /**
  951. * Convert a 32-bit Apple Mac timestamp integer to a list of 8 bytes, 64-bit timestamp.
  952. * @param {number}
  953. * @returns {Array}
  954. */
  955. encode.LONGDATETIME = function(v) {
  956. return [0, 0, 0, 0, (v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF];
  957. };
  958. /**
  959. * @constant
  960. * @type {number}
  961. */
  962. sizeOf.LONGDATETIME = constant(8);
  963. /**
  964. * Convert a 4-char tag to a list of 4 bytes.
  965. * @param {string}
  966. * @returns {Array}
  967. */
  968. encode.TAG = function(v) {
  969. check.argument(v.length === 4, 'Tag should be exactly 4 ASCII characters.');
  970. return [v.charCodeAt(0),
  971. v.charCodeAt(1),
  972. v.charCodeAt(2),
  973. v.charCodeAt(3)];
  974. };
  975. /**
  976. * @constant
  977. * @type {number}
  978. */
  979. sizeOf.TAG = constant(4);
  980. // CFF data types ///////////////////////////////////////////////////////////
  981. encode.Card8 = encode.BYTE;
  982. sizeOf.Card8 = sizeOf.BYTE;
  983. encode.Card16 = encode.USHORT;
  984. sizeOf.Card16 = sizeOf.USHORT;
  985. encode.OffSize = encode.BYTE;
  986. sizeOf.OffSize = sizeOf.BYTE;
  987. encode.SID = encode.USHORT;
  988. sizeOf.SID = sizeOf.USHORT;
  989. // Convert a numeric operand or charstring number to a variable-size list of bytes.
  990. /**
  991. * Convert a numeric operand or charstring number to a variable-size list of bytes.
  992. * @param {number}
  993. * @returns {Array}
  994. */
  995. encode.NUMBER = function(v) {
  996. if (v >= -107 && v <= 107) {
  997. return [v + 139];
  998. } else if (v >= 108 && v <= 1131) {
  999. v = v - 108;
  1000. return [(v >> 8) + 247, v & 0xFF];
  1001. } else if (v >= -1131 && v <= -108) {
  1002. v = -v - 108;
  1003. return [(v >> 8) + 251, v & 0xFF];
  1004. } else if (v >= -32768 && v <= 32767) {
  1005. return encode.NUMBER16(v);
  1006. } else {
  1007. return encode.NUMBER32(v);
  1008. }
  1009. };
  1010. /**
  1011. * @param {number}
  1012. * @returns {number}
  1013. */
  1014. sizeOf.NUMBER = function(v) {
  1015. return encode.NUMBER(v).length;
  1016. };
  1017. /**
  1018. * Convert a signed number between -32768 and +32767 to a three-byte value.
  1019. * This ensures we always use three bytes, but is not the most compact format.
  1020. * @param {number}
  1021. * @returns {Array}
  1022. */
  1023. encode.NUMBER16 = function(v) {
  1024. return [28, (v >> 8) & 0xFF, v & 0xFF];
  1025. };
  1026. /**
  1027. * @constant
  1028. * @type {number}
  1029. */
  1030. sizeOf.NUMBER16 = constant(3);
  1031. /**
  1032. * Convert a signed number between -(2^31) and +(2^31-1) to a five-byte value.
  1033. * This is useful if you want to be sure you always use four bytes,
  1034. * at the expense of wasting a few bytes for smaller numbers.
  1035. * @param {number}
  1036. * @returns {Array}
  1037. */
  1038. encode.NUMBER32 = function(v) {
  1039. return [29, (v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF];
  1040. };
  1041. /**
  1042. * @constant
  1043. * @type {number}
  1044. */
  1045. sizeOf.NUMBER32 = constant(5);
  1046. /**
  1047. * @param {number}
  1048. * @returns {Array}
  1049. */
  1050. encode.REAL = function(v) {
  1051. var value = v.toString();
  1052. // Some numbers use an epsilon to encode the value. (e.g. JavaScript will store 0.0000001 as 1e-7)
  1053. // This code converts it back to a number without the epsilon.
  1054. var m = /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(value);
  1055. if (m) {
  1056. var epsilon = parseFloat('1e' + ((m[2] ? +m[2] : 0) + m[1].length));
  1057. value = (Math.round(v * epsilon) / epsilon).toString();
  1058. }
  1059. var nibbles = '';
  1060. for (var i = 0, ii = value.length; i < ii; i += 1) {
  1061. var c = value[i];
  1062. if (c === 'e') {
  1063. nibbles += value[++i] === '-' ? 'c' : 'b';
  1064. } else if (c === '.') {
  1065. nibbles += 'a';
  1066. } else if (c === '-') {
  1067. nibbles += 'e';
  1068. } else {
  1069. nibbles += c;
  1070. }
  1071. }
  1072. nibbles += (nibbles.length & 1) ? 'f' : 'ff';
  1073. var out = [30];
  1074. for (var i$1 = 0, ii$1 = nibbles.length; i$1 < ii$1; i$1 += 2) {
  1075. out.push(parseInt(nibbles.substr(i$1, 2), 16));
  1076. }
  1077. return out;
  1078. };
  1079. /**
  1080. * @param {number}
  1081. * @returns {number}
  1082. */
  1083. sizeOf.REAL = function(v) {
  1084. return encode.REAL(v).length;
  1085. };
  1086. encode.NAME = encode.CHARARRAY;
  1087. sizeOf.NAME = sizeOf.CHARARRAY;
  1088. encode.STRING = encode.CHARARRAY;
  1089. sizeOf.STRING = sizeOf.CHARARRAY;
  1090. /**
  1091. * @param {DataView} data
  1092. * @param {number} offset
  1093. * @param {number} numBytes
  1094. * @returns {string}
  1095. */
  1096. decode.UTF8 = function(data, offset, numBytes) {
  1097. var codePoints = [];
  1098. var numChars = numBytes;
  1099. for (var j = 0; j < numChars; j++, offset += 1) {
  1100. codePoints[j] = data.getUint8(offset);
  1101. }
  1102. return String.fromCharCode.apply(null, codePoints);
  1103. };
  1104. /**
  1105. * @param {DataView} data
  1106. * @param {number} offset
  1107. * @param {number} numBytes
  1108. * @returns {string}
  1109. */
  1110. decode.UTF16 = function(data, offset, numBytes) {
  1111. var codePoints = [];
  1112. var numChars = numBytes / 2;
  1113. for (var j = 0; j < numChars; j++, offset += 2) {
  1114. codePoints[j] = data.getUint16(offset);
  1115. }
  1116. return String.fromCharCode.apply(null, codePoints);
  1117. };
  1118. /**
  1119. * Convert a JavaScript string to UTF16-BE.
  1120. * @param {string}
  1121. * @returns {Array}
  1122. */
  1123. encode.UTF16 = function(v) {
  1124. var b = [];
  1125. for (var i = 0; i < v.length; i += 1) {
  1126. var codepoint = v.charCodeAt(i);
  1127. b[b.length] = (codepoint >> 8) & 0xFF;
  1128. b[b.length] = codepoint & 0xFF;
  1129. }
  1130. return b;
  1131. };
  1132. /**
  1133. * @param {string}
  1134. * @returns {number}
  1135. */
  1136. sizeOf.UTF16 = function(v) {
  1137. return v.length * 2;
  1138. };
  1139. // Data for converting old eight-bit Macintosh encodings to Unicode.
  1140. // This representation is optimized for decoding; encoding is slower
  1141. // and needs more memory. The assumption is that all opentype.js users
  1142. // want to open fonts, but saving a font will be comparatively rare
  1143. // so it can be more expensive. Keyed by IANA character set name.
  1144. //
  1145. // Python script for generating these strings:
  1146. //
  1147. // s = u''.join([chr(c).decode('mac_greek') for c in range(128, 256)])
  1148. // print(s.encode('utf-8'))
  1149. /**
  1150. * @private
  1151. */
  1152. var eightBitMacEncodings = {
  1153. 'x-mac-croatian': // Python: 'mac_croatian'
  1154. 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø' +
  1155. '¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ',
  1156. 'x-mac-cyrillic': // Python: 'mac_cyrillic'
  1157. 'АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњ' +
  1158. 'јЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю',
  1159. 'x-mac-gaelic': // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/GAELIC.TXT
  1160. 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæø' +
  1161. 'ṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ',
  1162. 'x-mac-greek': // Python: 'mac_greek'
  1163. 'Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩ' +
  1164. 'άΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ\u00AD',
  1165. 'x-mac-icelandic': // Python: 'mac_iceland'
  1166. 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' +
  1167. '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ',
  1168. 'x-mac-inuit': // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/INUIT.TXT
  1169. 'ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗ' +
  1170. 'ᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł',
  1171. 'x-mac-ce': // Python: 'mac_latin2'
  1172. 'ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅ' +
  1173. 'ņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ',
  1174. macintosh: // Python: 'mac_roman'
  1175. 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' +
  1176. '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ',
  1177. 'x-mac-romanian': // Python: 'mac_romanian'
  1178. 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș' +
  1179. '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ',
  1180. 'x-mac-turkish': // Python: 'mac_turkish'
  1181. 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' +
  1182. '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ'
  1183. };
  1184. /**
  1185. * Decodes an old-style Macintosh string. Returns either a Unicode JavaScript
  1186. * string, or 'undefined' if the encoding is unsupported. For example, we do
  1187. * not support Chinese, Japanese or Korean because these would need large
  1188. * mapping tables.
  1189. * @param {DataView} dataView
  1190. * @param {number} offset
  1191. * @param {number} dataLength
  1192. * @param {string} encoding
  1193. * @returns {string}
  1194. */
  1195. decode.MACSTRING = function(dataView, offset, dataLength, encoding) {
  1196. var table = eightBitMacEncodings[encoding];
  1197. if (table === undefined) {
  1198. return undefined;
  1199. }
  1200. var result = '';
  1201. for (var i = 0; i < dataLength; i++) {
  1202. var c = dataView.getUint8(offset + i);
  1203. // In all eight-bit Mac encodings, the characters 0x00..0x7F are
  1204. // mapped to U+0000..U+007F; we only need to look up the others.
  1205. if (c <= 0x7F) {
  1206. result += String.fromCharCode(c);
  1207. } else {
  1208. result += table[c & 0x7F];
  1209. }
  1210. }
  1211. return result;
  1212. };
  1213. // Helper function for encode.MACSTRING. Returns a dictionary for mapping
  1214. // Unicode character codes to their 8-bit MacOS equivalent. This table
  1215. // is not exactly a super cheap data structure, but we do not care because
  1216. // encoding Macintosh strings is only rarely needed in typical applications.
  1217. var macEncodingTableCache = typeof WeakMap === 'function' && new WeakMap();
  1218. var macEncodingCacheKeys;
  1219. var getMacEncodingTable = function (encoding) {
  1220. // Since we use encoding as a cache key for WeakMap, it has to be
  1221. // a String object and not a literal. And at least on NodeJS 2.10.1,
  1222. // WeakMap requires that the same String instance is passed for cache hits.
  1223. if (!macEncodingCacheKeys) {
  1224. macEncodingCacheKeys = {};
  1225. for (var e in eightBitMacEncodings) {
  1226. /*jshint -W053 */ // Suppress "Do not use String as a constructor."
  1227. macEncodingCacheKeys[e] = new String(e);
  1228. }
  1229. }
  1230. var cacheKey = macEncodingCacheKeys[encoding];
  1231. if (cacheKey === undefined) {
  1232. return undefined;
  1233. }
  1234. // We can't do "if (cache.has(key)) {return cache.get(key)}" here:
  1235. // since garbage collection may run at any time, it could also kick in
  1236. // between the calls to cache.has() and cache.get(). In that case,
  1237. // we would return 'undefined' even though we do support the encoding.
  1238. if (macEncodingTableCache) {
  1239. var cachedTable = macEncodingTableCache.get(cacheKey);
  1240. if (cachedTable !== undefined) {
  1241. return cachedTable;
  1242. }
  1243. }
  1244. var decodingTable = eightBitMacEncodings[encoding];
  1245. if (decodingTable === undefined) {
  1246. return undefined;
  1247. }
  1248. var encodingTable = {};
  1249. for (var i = 0; i < decodingTable.length; i++) {
  1250. encodingTable[decodingTable.charCodeAt(i)] = i + 0x80;
  1251. }
  1252. if (macEncodingTableCache) {
  1253. macEncodingTableCache.set(cacheKey, encodingTable);
  1254. }
  1255. return encodingTable;
  1256. };
  1257. /**
  1258. * Encodes an old-style Macintosh string. Returns a byte array upon success.
  1259. * If the requested encoding is unsupported, or if the input string contains
  1260. * a character that cannot be expressed in the encoding, the function returns
  1261. * 'undefined'.
  1262. * @param {string} str
  1263. * @param {string} encoding
  1264. * @returns {Array}
  1265. */
  1266. encode.MACSTRING = function(str, encoding) {
  1267. var table = getMacEncodingTable(encoding);
  1268. if (table === undefined) {
  1269. return undefined;
  1270. }
  1271. var result = [];
  1272. for (var i = 0; i < str.length; i++) {
  1273. var c = str.charCodeAt(i);
  1274. // In all eight-bit Mac encodings, the characters 0x00..0x7F are
  1275. // mapped to U+0000..U+007F; we only need to look up the others.
  1276. if (c >= 0x80) {
  1277. c = table[c];
  1278. if (c === undefined) {
  1279. // str contains a Unicode character that cannot be encoded
  1280. // in the requested encoding.
  1281. return undefined;
  1282. }
  1283. }
  1284. result[i] = c;
  1285. // result.push(c);
  1286. }
  1287. return result;
  1288. };
  1289. /**
  1290. * @param {string} str
  1291. * @param {string} encoding
  1292. * @returns {number}
  1293. */
  1294. sizeOf.MACSTRING = function(str, encoding) {
  1295. var b = encode.MACSTRING(str, encoding);
  1296. if (b !== undefined) {
  1297. return b.length;
  1298. } else {
  1299. return 0;
  1300. }
  1301. };
  1302. // Helper for encode.VARDELTAS
  1303. function isByteEncodable(value) {
  1304. return value >= -128 && value <= 127;
  1305. }
  1306. // Helper for encode.VARDELTAS
  1307. function encodeVarDeltaRunAsZeroes(deltas, pos, result) {
  1308. var runLength = 0;
  1309. var numDeltas = deltas.length;
  1310. while (pos < numDeltas && runLength < 64 && deltas[pos] === 0) {
  1311. ++pos;
  1312. ++runLength;
  1313. }
  1314. result.push(0x80 | (runLength - 1));
  1315. return pos;
  1316. }
  1317. // Helper for encode.VARDELTAS
  1318. function encodeVarDeltaRunAsBytes(deltas, offset, result) {
  1319. var runLength = 0;
  1320. var numDeltas = deltas.length;
  1321. var pos = offset;
  1322. while (pos < numDeltas && runLength < 64) {
  1323. var value = deltas[pos];
  1324. if (!isByteEncodable(value)) {
  1325. break;
  1326. }
  1327. // Within a byte-encoded run of deltas, a single zero is best
  1328. // stored literally as 0x00 value. However, if we have two or
  1329. // more zeroes in a sequence, it is better to start a new run.
  1330. // Fore example, the sequence of deltas [15, 15, 0, 15, 15]
  1331. // becomes 6 bytes (04 0F 0F 00 0F 0F) when storing the zero
  1332. // within the current run, but 7 bytes (01 0F 0F 80 01 0F 0F)
  1333. // when starting a new run.
  1334. if (value === 0 && pos + 1 < numDeltas && deltas[pos + 1] === 0) {
  1335. break;
  1336. }
  1337. ++pos;
  1338. ++runLength;
  1339. }
  1340. result.push(runLength - 1);
  1341. for (var i = offset; i < pos; ++i) {
  1342. result.push((deltas[i] + 256) & 0xff);
  1343. }
  1344. return pos;
  1345. }
  1346. // Helper for encode.VARDELTAS
  1347. function encodeVarDeltaRunAsWords(deltas, offset, result) {
  1348. var runLength = 0;
  1349. var numDeltas = deltas.length;
  1350. var pos = offset;
  1351. while (pos < numDeltas && runLength < 64) {
  1352. var value = deltas[pos];
  1353. // Within a word-encoded run of deltas, it is easiest to start
  1354. // a new run (with a different encoding) whenever we encounter
  1355. // a zero value. For example, the sequence [0x6666, 0, 0x7777]
  1356. // needs 7 bytes when storing the zero inside the current run
  1357. // (42 66 66 00 00 77 77), and equally 7 bytes when starting a
  1358. // new run (40 66 66 80 40 77 77).
  1359. if (value === 0) {
  1360. break;
  1361. }
  1362. // Within a word-encoded run of deltas, a single value in the
  1363. // range (-128..127) should be encoded within the current run
  1364. // because it is more compact. For example, the sequence
  1365. // [0x6666, 2, 0x7777] becomes 7 bytes when storing the value
  1366. // literally (42 66 66 00 02 77 77), but 8 bytes when starting
  1367. // a new run (40 66 66 00 02 40 77 77).
  1368. if (isByteEncodable(value) && pos + 1 < numDeltas && isByteEncodable(deltas[pos + 1])) {
  1369. break;
  1370. }
  1371. ++pos;
  1372. ++runLength;
  1373. }
  1374. result.push(0x40 | (runLength - 1));
  1375. for (var i = offset; i < pos; ++i) {
  1376. var val = deltas[i];
  1377. result.push(((val + 0x10000) >> 8) & 0xff, (val + 0x100) & 0xff);
  1378. }
  1379. return pos;
  1380. }
  1381. /**
  1382. * Encode a list of variation adjustment deltas.
  1383. *
  1384. * Variation adjustment deltas are used in ‘gvar’ and ‘cvar’ tables.
  1385. * They indicate how points (in ‘gvar’) or values (in ‘cvar’) get adjusted
  1386. * when generating instances of variation fonts.
  1387. *
  1388. * @see https://www.microsoft.com/typography/otspec/gvar.htm
  1389. * @see https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6gvar.html
  1390. * @param {Array}
  1391. * @return {Array}
  1392. */
  1393. encode.VARDELTAS = function(deltas) {
  1394. var pos = 0;
  1395. var result = [];
  1396. while (pos < deltas.length) {
  1397. var value = deltas[pos];
  1398. if (value === 0) {
  1399. pos = encodeVarDeltaRunAsZeroes(deltas, pos, result);
  1400. } else if (value >= -128 && value <= 127) {
  1401. pos = encodeVarDeltaRunAsBytes(deltas, pos, result);
  1402. } else {
  1403. pos = encodeVarDeltaRunAsWords(deltas, pos, result);
  1404. }
  1405. }
  1406. return result;
  1407. };
  1408. // Convert a list of values to a CFF INDEX structure.
  1409. // The values should be objects containing name / type / value.
  1410. /**
  1411. * @param {Array} l
  1412. * @returns {Array}
  1413. */
  1414. encode.INDEX = function(l) {
  1415. //var offset, offsets, offsetEncoder, encodedOffsets, encodedOffset, data,
  1416. // i, v;
  1417. // Because we have to know which data type to use to encode the offsets,
  1418. // we have to go through the values twice: once to encode the data and
  1419. // calculate the offsets, then again to encode the offsets using the fitting data type.
  1420. var offset = 1; // First offset is always 1.
  1421. var offsets = [offset];
  1422. var data = [];
  1423. for (var i = 0; i < l.length; i += 1) {
  1424. var v = encode.OBJECT(l[i]);
  1425. Array.prototype.push.apply(data, v);
  1426. offset += v.length;
  1427. offsets.push(offset);
  1428. }
  1429. if (data.length === 0) {
  1430. return [0, 0];
  1431. }
  1432. var encodedOffsets = [];
  1433. var offSize = (1 + Math.floor(Math.log(offset) / Math.log(2)) / 8) | 0;
  1434. var offsetEncoder = [undefined, encode.BYTE, encode.USHORT, encode.UINT24, encode.ULONG][offSize];
  1435. for (var i$1 = 0; i$1 < offsets.length; i$1 += 1) {
  1436. var encodedOffset = offsetEncoder(offsets[i$1]);
  1437. Array.prototype.push.apply(encodedOffsets, encodedOffset);
  1438. }
  1439. return Array.prototype.concat(encode.Card16(l.length),
  1440. encode.OffSize(offSize),
  1441. encodedOffsets,
  1442. data);
  1443. };
  1444. /**
  1445. * @param {Array}
  1446. * @returns {number}
  1447. */
  1448. sizeOf.INDEX = function(v) {
  1449. return encode.INDEX(v).length;
  1450. };
  1451. /**
  1452. * Convert an object to a CFF DICT structure.
  1453. * The keys should be numeric.
  1454. * The values should be objects containing name / type / value.
  1455. * @param {Object} m
  1456. * @returns {Array}
  1457. */
  1458. encode.DICT = function(m) {
  1459. var d = [];
  1460. var keys = Object.keys(m);
  1461. var length = keys.length;
  1462. for (var i = 0; i < length; i += 1) {
  1463. // Object.keys() return string keys, but our keys are always numeric.
  1464. var k = parseInt(keys[i], 0);
  1465. var v = m[k];
  1466. // Value comes before the key.
  1467. d = d.concat(encode.OPERAND(v.value, v.type));
  1468. d = d.concat(encode.OPERATOR(k));
  1469. }
  1470. return d;
  1471. };
  1472. /**
  1473. * @param {Object}
  1474. * @returns {number}
  1475. */
  1476. sizeOf.DICT = function(m) {
  1477. return encode.DICT(m).length;
  1478. };
  1479. /**
  1480. * @param {number}
  1481. * @returns {Array}
  1482. */
  1483. encode.OPERATOR = function(v) {
  1484. if (v < 1200) {
  1485. return [v];
  1486. } else {
  1487. return [12, v - 1200];
  1488. }
  1489. };
  1490. /**
  1491. * @param {Array} v
  1492. * @param {string}
  1493. * @returns {Array}
  1494. */
  1495. encode.OPERAND = function(v, type) {
  1496. var d = [];
  1497. if (Array.isArray(type)) {
  1498. for (var i = 0; i < type.length; i += 1) {
  1499. check.argument(v.length === type.length, 'Not enough arguments given for type' + type);
  1500. d = d.concat(encode.OPERAND(v[i], type[i]));
  1501. }
  1502. } else {
  1503. if (type === 'SID') {
  1504. d = d.concat(encode.NUMBER(v));
  1505. } else if (type === 'offset') {
  1506. // We make it easy for ourselves and always encode offsets as
  1507. // 4 bytes. This makes offset calculation for the top dict easier.
  1508. d = d.concat(encode.NUMBER32(v));
  1509. } else if (type === 'number') {
  1510. d = d.concat(encode.NUMBER(v));
  1511. } else if (type === 'real') {
  1512. d = d.concat(encode.REAL(v));
  1513. } else {
  1514. throw new Error('Unknown operand type ' + type);
  1515. // FIXME Add support for booleans
  1516. }
  1517. }
  1518. return d;
  1519. };
  1520. encode.OP = encode.BYTE;
  1521. sizeOf.OP = sizeOf.BYTE;
  1522. // memoize charstring encoding using WeakMap if available
  1523. var wmm = typeof WeakMap === 'function' && new WeakMap();
  1524. /**
  1525. * Convert a list of CharString operations to bytes.
  1526. * @param {Array}
  1527. * @returns {Array}
  1528. */
  1529. encode.CHARSTRING = function(ops) {
  1530. // See encode.MACSTRING for why we don't do "if (wmm && wmm.has(ops))".
  1531. if (wmm) {
  1532. var cachedValue = wmm.get(ops);
  1533. if (cachedValue !== undefined) {
  1534. return cachedValue;
  1535. }
  1536. }
  1537. var d = [];
  1538. var length = ops.length;
  1539. for (var i = 0; i < length; i += 1) {
  1540. var op = ops[i];
  1541. d = d.concat(encode[op.type](op.value));
  1542. }
  1543. if (wmm) {
  1544. wmm.set(ops, d);
  1545. }
  1546. return d;
  1547. };
  1548. /**
  1549. * @param {Array}
  1550. * @returns {number}
  1551. */
  1552. sizeOf.CHARSTRING = function(ops) {
  1553. return encode.CHARSTRING(ops).length;
  1554. };
  1555. // Utility functions ////////////////////////////////////////////////////////
  1556. /**
  1557. * Convert an object containing name / type / value to bytes.
  1558. * @param {Object}
  1559. * @returns {Array}
  1560. */
  1561. encode.OBJECT = function(v) {
  1562. var encodingFunction = encode[v.type];
  1563. check.argument(encodingFunction !== undefined, 'No encoding function for type ' + v.type);
  1564. return encodingFunction(v.value);
  1565. };
  1566. /**
  1567. * @param {Object}
  1568. * @returns {number}
  1569. */
  1570. sizeOf.OBJECT = function(v) {
  1571. var sizeOfFunction = sizeOf[v.type];
  1572. check.argument(sizeOfFunction !== undefined, 'No sizeOf function for type ' + v.type);
  1573. return sizeOfFunction(v.value);
  1574. };
  1575. /**
  1576. * Convert a table object to bytes.
  1577. * A table contains a list of fields containing the metadata (name, type and default value).
  1578. * The table itself has the field values set as attributes.
  1579. * @param {opentype.Table}
  1580. * @returns {Array}
  1581. */
  1582. encode.TABLE = function(table) {
  1583. var d = [];
  1584. var length = table.fields.length;
  1585. var subtables = [];
  1586. var subtableOffsets = [];
  1587. for (var i = 0; i < length; i += 1) {
  1588. var field = table.fields[i];
  1589. var encodingFunction = encode[field.type];
  1590. check.argument(encodingFunction !== undefined, 'No encoding function for field type ' + field.type + ' (' + field.name + ')');
  1591. var value = table[field.name];
  1592. if (value === undefined) {
  1593. value = field.value;
  1594. }
  1595. var bytes = encodingFunction(value);
  1596. if (field.type === 'TABLE') {
  1597. subtableOffsets.push(d.length);
  1598. d = d.concat([0, 0]);
  1599. subtables.push(bytes);
  1600. } else {
  1601. d = d.concat(bytes);
  1602. }
  1603. }
  1604. for (var i$1 = 0; i$1 < subtables.length; i$1 += 1) {
  1605. var o = subtableOffsets[i$1];
  1606. var offset = d.length;
  1607. check.argument(offset < 65536, 'Table ' + table.tableName + ' too big.');
  1608. d[o] = offset >> 8;
  1609. d[o + 1] = offset & 0xff;
  1610. d = d.concat(subtables[i$1]);
  1611. }
  1612. return d;
  1613. };
  1614. /**
  1615. * @param {opentype.Table}
  1616. * @returns {number}
  1617. */
  1618. sizeOf.TABLE = function(table) {
  1619. var numBytes = 0;
  1620. var length = table.fields.length;
  1621. for (var i = 0; i < length; i += 1) {
  1622. var field = table.fields[i];
  1623. var sizeOfFunction = sizeOf[field.type];
  1624. check.argument(sizeOfFunction !== undefined, 'No sizeOf function for field type ' + field.type + ' (' + field.name + ')');
  1625. var value = table[field.name];
  1626. if (value === undefined) {
  1627. value = field.value;
  1628. }
  1629. numBytes += sizeOfFunction(value);
  1630. // Subtables take 2 more bytes for offsets.
  1631. if (field.type === 'TABLE') {
  1632. numBytes += 2;
  1633. }
  1634. }
  1635. return numBytes;
  1636. };
  1637. encode.RECORD = encode.TABLE;
  1638. sizeOf.RECORD = sizeOf.TABLE;
  1639. // Merge in a list of bytes.
  1640. encode.LITERAL = function(v) {
  1641. return v;
  1642. };
  1643. sizeOf.LITERAL = function(v) {
  1644. return v.length;
  1645. };
  1646. // Table metadata
  1647. /**
  1648. * @exports opentype.Table
  1649. * @class
  1650. * @param {string} tableName
  1651. * @param {Array} fields
  1652. * @param {Object} options
  1653. * @constructor
  1654. */
  1655. function Table(tableName, fields, options) {
  1656. // For coverage tables with coverage format 2, we do not want to add the coverage data directly to the table object,
  1657. // as this will result in wrong encoding order of the coverage data on serialization to bytes.
  1658. // The fallback of using the field values directly when not present on the table is handled in types.encode.TABLE() already.
  1659. if (fields.length && (fields[0].name !== 'coverageFormat' || fields[0].value === 1)) {
  1660. for (var i = 0; i < fields.length; i += 1) {
  1661. var field = fields[i];
  1662. this[field.name] = field.value;
  1663. }
  1664. }
  1665. this.tableName = tableName;
  1666. this.fields = fields;
  1667. if (options) {
  1668. var optionKeys = Object.keys(options);
  1669. for (var i$1 = 0; i$1 < optionKeys.length; i$1 += 1) {
  1670. var k = optionKeys[i$1];
  1671. var v = options[k];
  1672. if (this[k] !== undefined) {
  1673. this[k] = v;
  1674. }
  1675. }
  1676. }
  1677. }
  1678. /**
  1679. * Encodes the table and returns an array of bytes
  1680. * @return {Array}
  1681. */
  1682. Table.prototype.encode = function() {
  1683. return encode.TABLE(this);
  1684. };
  1685. /**
  1686. * Get the size of the table.
  1687. * @return {number}
  1688. */
  1689. Table.prototype.sizeOf = function() {
  1690. return sizeOf.TABLE(this);
  1691. };
  1692. /**
  1693. * @private
  1694. */
  1695. function ushortList(itemName, list, count) {
  1696. if (count === undefined) {
  1697. count = list.length;
  1698. }
  1699. var fields = new Array(list.length + 1);
  1700. fields[0] = {name: itemName + 'Count', type: 'USHORT', value: count};
  1701. for (var i = 0; i < list.length; i++) {
  1702. fields[i + 1] = {name: itemName + i, type: 'USHORT', value: list[i]};
  1703. }
  1704. return fields;
  1705. }
  1706. /**
  1707. * @private
  1708. */
  1709. function tableList(itemName, records, itemCallback) {
  1710. var count = records.length;
  1711. var fields = new Array(count + 1);
  1712. fields[0] = {name: itemName + 'Count', type: 'USHORT', value: count};
  1713. for (var i = 0; i < count; i++) {
  1714. fields[i + 1] = {name: itemName + i, type: 'TABLE', value: itemCallback(records[i], i)};
  1715. }
  1716. return fields;
  1717. }
  1718. /**
  1719. * @private
  1720. */
  1721. function recordList(itemName, records, itemCallback) {
  1722. var count = records.length;
  1723. var fields = [];
  1724. fields[0] = {name: itemName + 'Count', type: 'USHORT', value: count};
  1725. for (var i = 0; i < count; i++) {
  1726. fields = fields.concat(itemCallback(records[i], i));
  1727. }
  1728. return fields;
  1729. }
  1730. // Common Layout Tables
  1731. /**
  1732. * @exports opentype.Coverage
  1733. * @class
  1734. * @param {opentype.Table}
  1735. * @constructor
  1736. * @extends opentype.Table
  1737. */
  1738. function Coverage(coverageTable) {
  1739. if (coverageTable.format === 1) {
  1740. Table.call(this, 'coverageTable',
  1741. [{name: 'coverageFormat', type: 'USHORT', value: 1}]
  1742. .concat(ushortList('glyph', coverageTable.glyphs))
  1743. );
  1744. } else if (coverageTable.format === 2) {
  1745. Table.call(this, 'coverageTable',
  1746. [{name: 'coverageFormat', type: 'USHORT', value: 2}]
  1747. .concat(recordList('rangeRecord', coverageTable.ranges, function(RangeRecord) {
  1748. return [
  1749. {name: 'startGlyphID', type: 'USHORT', value: RangeRecord.start},
  1750. {name: 'endGlyphID', type: 'USHORT', value: RangeRecord.end},
  1751. {name: 'startCoverageIndex', type: 'USHORT', value: RangeRecord.index} ];
  1752. }))
  1753. );
  1754. } else {
  1755. check.assert(false, 'Coverage format must be 1 or 2.');
  1756. }
  1757. }
  1758. Coverage.prototype = Object.create(Table.prototype);
  1759. Coverage.prototype.constructor = Coverage;
  1760. function ScriptList(scriptListTable) {
  1761. Table.call(this, 'scriptListTable',
  1762. recordList('scriptRecord', scriptListTable, function(scriptRecord, i) {
  1763. var script = scriptRecord.script;
  1764. var defaultLangSys = script.defaultLangSys;
  1765. check.assert(!!defaultLangSys, 'Unable to write GSUB: script ' + scriptRecord.tag + ' has no default language system.');
  1766. return [
  1767. {name: 'scriptTag' + i, type: 'TAG', value: scriptRecord.tag},
  1768. {name: 'script' + i, type: 'TABLE', value: new Table('scriptTable', [
  1769. {name: 'defaultLangSys', type: 'TABLE', value: new Table('defaultLangSys', [
  1770. {name: 'lookupOrder', type: 'USHORT', value: 0},
  1771. {name: 'reqFeatureIndex', type: 'USHORT', value: defaultLangSys.reqFeatureIndex}]
  1772. .concat(ushortList('featureIndex', defaultLangSys.featureIndexes)))}
  1773. ].concat(recordList('langSys', script.langSysRecords, function(langSysRecord, i) {
  1774. var langSys = langSysRecord.langSys;
  1775. return [
  1776. {name: 'langSysTag' + i, type: 'TAG', value: langSysRecord.tag},
  1777. {name: 'langSys' + i, type: 'TABLE', value: new Table('langSys', [
  1778. {name: 'lookupOrder', type: 'USHORT', value: 0},
  1779. {name: 'reqFeatureIndex', type: 'USHORT', value: langSys.reqFeatureIndex}
  1780. ].concat(ushortList('featureIndex', langSys.featureIndexes)))}
  1781. ];
  1782. })))}
  1783. ];
  1784. })
  1785. );
  1786. }
  1787. ScriptList.prototype = Object.create(Table.prototype);
  1788. ScriptList.prototype.constructor = ScriptList;
  1789. /**
  1790. * @exports opentype.FeatureList
  1791. * @class
  1792. * @param {opentype.Table}
  1793. * @constructor
  1794. * @extends opentype.Table
  1795. */
  1796. function FeatureList(featureListTable) {
  1797. Table.call(this, 'featureListTable',
  1798. recordList('featureRecord', featureListTable, function(featureRecord, i) {
  1799. var feature = featureRecord.feature;
  1800. return [
  1801. {name: 'featureTag' + i, type: 'TAG', value: featureRecord.tag},
  1802. {name: 'feature' + i, type: 'TABLE', value: new Table('featureTable', [
  1803. {name: 'featureParams', type: 'USHORT', value: feature.featureParams} ].concat(ushortList('lookupListIndex', feature.lookupListIndexes)))}
  1804. ];
  1805. })
  1806. );
  1807. }
  1808. FeatureList.prototype = Object.create(Table.prototype);
  1809. FeatureList.prototype.constructor = FeatureList;
  1810. /**
  1811. * @exports opentype.LookupList
  1812. * @class
  1813. * @param {opentype.Table}
  1814. * @param {Object}
  1815. * @constructor
  1816. * @extends opentype.Table
  1817. */
  1818. function LookupList(lookupListTable, subtableMakers) {
  1819. Table.call(this, 'lookupListTable', tableList('lookup', lookupListTable, function(lookupTable) {
  1820. var subtableCallback = subtableMakers[lookupTable.lookupType];
  1821. check.assert(!!subtableCallback, 'Unable to write GSUB lookup type ' + lookupTable.lookupType + ' tables.');
  1822. return new Table('lookupTable', [
  1823. {name: 'lookupType', type: 'USHORT', value: lookupTable.lookupType},
  1824. {name: 'lookupFlag', type: 'USHORT', value: lookupTable.lookupFlag}
  1825. ].concat(tableList('subtable', lookupTable.subtables, subtableCallback)));
  1826. }));
  1827. }
  1828. LookupList.prototype = Object.create(Table.prototype);
  1829. LookupList.prototype.constructor = LookupList;
  1830. // Record = same as Table, but inlined (a Table has an offset and its data is further in the stream)
  1831. // Don't use offsets inside Records (probable bug), only in Tables.
  1832. var table = {
  1833. Table: Table,
  1834. Record: Table,
  1835. Coverage: Coverage,
  1836. ScriptList: ScriptList,
  1837. FeatureList: FeatureList,
  1838. LookupList: LookupList,
  1839. ushortList: ushortList,
  1840. tableList: tableList,
  1841. recordList: recordList,
  1842. };
  1843. // Parsing utility functions
  1844. // Retrieve an unsigned byte from the DataView.
  1845. function getByte(dataView, offset) {
  1846. return dataView.getUint8(offset);
  1847. }
  1848. // Retrieve an unsigned 16-bit short from the DataView.
  1849. // The value is stored in big endian.
  1850. function getUShort(dataView, offset) {
  1851. return dataView.getUint16(offset, false);
  1852. }
  1853. // Retrieve a signed 16-bit short from the DataView.
  1854. // The value is stored in big endian.
  1855. function getShort(dataView, offset) {
  1856. return dataView.getInt16(offset, false);
  1857. }
  1858. // Retrieve an unsigned 32-bit long from the DataView.
  1859. // The value is stored in big endian.
  1860. function getULong(dataView, offset) {
  1861. return dataView.getUint32(offset, false);
  1862. }
  1863. // Retrieve a 32-bit signed fixed-point number (16.16) from the DataView.
  1864. // The value is stored in big endian.
  1865. function getFixed(dataView, offset) {
  1866. var decimal = dataView.getInt16(offset, false);
  1867. var fraction = dataView.getUint16(offset + 2, false);
  1868. return decimal + fraction / 65535;
  1869. }
  1870. // Retrieve a 4-character tag from the DataView.
  1871. // Tags are used to identify tables.
  1872. function getTag(dataView, offset) {
  1873. var tag = '';
  1874. for (var i = offset; i < offset + 4; i += 1) {
  1875. tag += String.fromCharCode(dataView.getInt8(i));
  1876. }
  1877. return tag;
  1878. }
  1879. // Retrieve an offset from the DataView.
  1880. // Offsets are 1 to 4 bytes in length, depending on the offSize argument.
  1881. function getOffset(dataView, offset, offSize) {
  1882. var v = 0;
  1883. for (var i = 0; i < offSize; i += 1) {
  1884. v <<= 8;
  1885. v += dataView.getUint8(offset + i);
  1886. }
  1887. return v;
  1888. }
  1889. // Retrieve a number of bytes from start offset to the end offset from the DataView.
  1890. function getBytes(dataView, startOffset, endOffset) {
  1891. var bytes = [];
  1892. for (var i = startOffset; i < endOffset; i += 1) {
  1893. bytes.push(dataView.getUint8(i));
  1894. }
  1895. return bytes;
  1896. }
  1897. // Convert the list of bytes to a string.
  1898. function bytesToString(bytes) {
  1899. var s = '';
  1900. for (var i = 0; i < bytes.length; i += 1) {
  1901. s += String.fromCharCode(bytes[i]);
  1902. }
  1903. return s;
  1904. }
  1905. var typeOffsets = {
  1906. byte: 1,
  1907. uShort: 2,
  1908. short: 2,
  1909. uLong: 4,
  1910. fixed: 4,
  1911. longDateTime: 8,
  1912. tag: 4
  1913. };
  1914. // A stateful parser that changes the offset whenever a value is retrieved.
  1915. // The data is a DataView.
  1916. function Parser(data, offset) {
  1917. this.data = data;
  1918. this.offset = offset;
  1919. this.relativeOffset = 0;
  1920. }
  1921. Parser.prototype.parseByte = function() {
  1922. var v = this.data.getUint8(this.offset + this.relativeOffset);
  1923. this.relativeOffset += 1;
  1924. return v;
  1925. };
  1926. Parser.prototype.parseChar = function() {
  1927. var v = this.data.getInt8(this.offset + this.relativeOffset);
  1928. this.relativeOffset += 1;
  1929. return v;
  1930. };
  1931. Parser.prototype.parseCard8 = Parser.prototype.parseByte;
  1932. Parser.prototype.parseUShort = function() {
  1933. var v = this.data.getUint16(this.offset + this.relativeOffset);
  1934. this.relativeOffset += 2;
  1935. return v;
  1936. };
  1937. Parser.prototype.parseCard16 = Parser.prototype.parseUShort;
  1938. Parser.prototype.parseSID = Parser.prototype.parseUShort;
  1939. Parser.prototype.parseOffset16 = Parser.prototype.parseUShort;
  1940. Parser.prototype.parseShort = function() {
  1941. var v = this.data.getInt16(this.offset + this.relativeOffset);
  1942. this.relativeOffset += 2;
  1943. return v;
  1944. };
  1945. Parser.prototype.parseF2Dot14 = function() {
  1946. var v = this.data.getInt16(this.offset + this.relativeOffset) / 16384;
  1947. this.relativeOffset += 2;
  1948. return v;
  1949. };
  1950. Parser.prototype.parseULong = function() {
  1951. var v = getULong(this.data, this.offset + this.relativeOffset);
  1952. this.relativeOffset += 4;
  1953. return v;
  1954. };
  1955. Parser.prototype.parseOffset32 = Parser.prototype.parseULong;
  1956. Parser.prototype.parseFixed = function() {
  1957. var v = getFixed(this.data, this.offset + this.relativeOffset);
  1958. this.relativeOffset += 4;
  1959. return v;
  1960. };
  1961. Parser.prototype.parseString = function(length) {
  1962. var dataView = this.data;
  1963. var offset = this.offset + this.relativeOffset;
  1964. var string = '';
  1965. this.relativeOffset += length;
  1966. for (var i = 0; i < length; i++) {
  1967. string += String.fromCharCode(dataView.getUint8(offset + i));
  1968. }
  1969. return string;
  1970. };
  1971. Parser.prototype.parseTag = function() {
  1972. return this.parseString(4);
  1973. };
  1974. // LONGDATETIME is a 64-bit integer.
  1975. // JavaScript and unix timestamps traditionally use 32 bits, so we
  1976. // only take the last 32 bits.
  1977. // + Since until 2038 those bits will be filled by zeros we can ignore them.
  1978. Parser.prototype.parseLongDateTime = function() {
  1979. var v = getULong(this.data, this.offset + this.relativeOffset + 4);
  1980. // Subtract seconds between 01/01/1904 and 01/01/1970
  1981. // to convert Apple Mac timestamp to Standard Unix timestamp
  1982. v -= 2082844800;
  1983. this.relativeOffset += 8;
  1984. return v;
  1985. };
  1986. Parser.prototype.parseVersion = function(minorBase) {
  1987. var major = getUShort(this.data, this.offset + this.relativeOffset);
  1988. // How to interpret the minor version is very vague in the spec. 0x5000 is 5, 0x1000 is 1
  1989. // Default returns the correct number if minor = 0xN000 where N is 0-9
  1990. // Set minorBase to 1 for tables that use minor = N where N is 0-9
  1991. var minor = getUShort(this.data, this.offset + this.relativeOffset + 2);
  1992. this.relativeOffset += 4;
  1993. if (minorBase === undefined) { minorBase = 0x1000; }
  1994. return major + minor / minorBase / 10;
  1995. };
  1996. Parser.prototype.skip = function(type, amount) {
  1997. if (amount === undefined) {
  1998. amount = 1;
  1999. }
  2000. this.relativeOffset += typeOffsets[type] * amount;
  2001. };
  2002. ///// Parsing lists and records ///////////////////////////////
  2003. // Parse a list of 32 bit unsigned integers.
  2004. Parser.prototype.parseULongList = function(count) {
  2005. if (count === undefined) { count = this.parseULong(); }
  2006. var offsets = new Array(count);
  2007. var dataView = this.data;
  2008. var offset = this.offset + this.relativeOffset;
  2009. for (var i = 0; i < count; i++) {
  2010. offsets[i] = dataView.getUint32(offset);
  2011. offset += 4;
  2012. }
  2013. this.relativeOffset += count * 4;
  2014. return offsets;
  2015. };
  2016. // Parse a list of 16 bit unsigned integers. The length of the list can be read on the stream
  2017. // or provided as an argument.
  2018. Parser.prototype.parseOffset16List =
  2019. Parser.prototype.parseUShortList = function(count) {
  2020. if (count === undefined) { count = this.parseUShort(); }
  2021. var offsets = new Array(count);
  2022. var dataView = this.data;
  2023. var offset = this.offset + this.relativeOffset;
  2024. for (var i = 0; i < count; i++) {
  2025. offsets[i] = dataView.getUint16(offset);
  2026. offset += 2;
  2027. }
  2028. this.relativeOffset += count * 2;
  2029. return offsets;
  2030. };
  2031. // Parses a list of 16 bit signed integers.
  2032. Parser.prototype.parseShortList = function(count) {
  2033. var list = new Array(count);
  2034. var dataView = this.data;
  2035. var offset = this.offset + this.relativeOffset;
  2036. for (var i = 0; i < count; i++) {
  2037. list[i] = dataView.getInt16(offset);
  2038. offset += 2;
  2039. }
  2040. this.relativeOffset += count * 2;
  2041. return list;
  2042. };
  2043. // Parses a list of bytes.
  2044. Parser.prototype.parseByteList = function(count) {
  2045. var list = new Array(count);
  2046. var dataView = this.data;
  2047. var offset = this.offset + this.relativeOffset;
  2048. for (var i = 0; i < count; i++) {
  2049. list[i] = dataView.getUint8(offset++);
  2050. }
  2051. this.relativeOffset += count;
  2052. return list;
  2053. };
  2054. /**
  2055. * Parse a list of items.
  2056. * Record count is optional, if omitted it is read from the stream.
  2057. * itemCallback is one of the Parser methods.
  2058. */
  2059. Parser.prototype.parseList = function(count, itemCallback) {
  2060. if (!itemCallback) {
  2061. itemCallback = count;
  2062. count = this.parseUShort();
  2063. }
  2064. var list = new Array(count);
  2065. for (var i = 0; i < count; i++) {
  2066. list[i] = itemCallback.call(this);
  2067. }
  2068. return list;
  2069. };
  2070. Parser.prototype.parseList32 = function(count, itemCallback) {
  2071. if (!itemCallback) {
  2072. itemCallback = count;
  2073. count = this.parseULong();
  2074. }
  2075. var list = new Array(count);
  2076. for (var i = 0; i < count; i++) {
  2077. list[i] = itemCallback.call(this);
  2078. }
  2079. return list;
  2080. };
  2081. /**
  2082. * Parse a list of records.
  2083. * Record count is optional, if omitted it is read from the stream.
  2084. * Example of recordDescription: { sequenceIndex: Parser.uShort, lookupListIndex: Parser.uShort }
  2085. */
  2086. Parser.prototype.parseRecordList = function(count, recordDescription) {
  2087. // If the count argument is absent, read it in the stream.
  2088. if (!recordDescription) {
  2089. recordDescription = count;
  2090. count = this.parseUShort();
  2091. }
  2092. var records = new Array(count);
  2093. var fields = Object.keys(recordDescription);
  2094. for (var i = 0; i < count; i++) {
  2095. var rec = {};
  2096. for (var j = 0; j < fields.length; j++) {
  2097. var fieldName = fields[j];
  2098. var fieldType = recordDescription[fieldName];
  2099. rec[fieldName] = fieldType.call(this);
  2100. }
  2101. records[i] = rec;
  2102. }
  2103. return records;
  2104. };
  2105. Parser.prototype.parseRecordList32 = function(count, recordDescription) {
  2106. // If the count argument is absent, read it in the stream.
  2107. if (!recordDescription) {
  2108. recordDescription = count;
  2109. count = this.parseULong();
  2110. }
  2111. var records = new Array(count);
  2112. var fields = Object.keys(recordDescription);
  2113. for (var i = 0; i < count; i++) {
  2114. var rec = {};
  2115. for (var j = 0; j < fields.length; j++) {
  2116. var fieldName = fields[j];
  2117. var fieldType = recordDescription[fieldName];
  2118. rec[fieldName] = fieldType.call(this);
  2119. }
  2120. records[i] = rec;
  2121. }
  2122. return records;
  2123. };
  2124. // Parse a data structure into an object
  2125. // Example of description: { sequenceIndex: Parser.uShort, lookupListIndex: Parser.uShort }
  2126. Parser.prototype.parseStruct = function(description) {
  2127. if (typeof description === 'function') {
  2128. return description.call(this);
  2129. } else {
  2130. var fields = Object.keys(description);
  2131. var struct = {};
  2132. for (var j = 0; j < fields.length; j++) {
  2133. var fieldName = fields[j];
  2134. var fieldType = description[fieldName];
  2135. struct[fieldName] = fieldType.call(this);
  2136. }
  2137. return struct;
  2138. }
  2139. };
  2140. /**
  2141. * Parse a GPOS valueRecord
  2142. * https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#value-record
  2143. * valueFormat is optional, if omitted it is read from the stream.
  2144. */
  2145. Parser.prototype.parseValueRecord = function(valueFormat) {
  2146. if (valueFormat === undefined) {
  2147. valueFormat = this.parseUShort();
  2148. }
  2149. if (valueFormat === 0) {
  2150. // valueFormat2 in kerning pairs is most often 0
  2151. // in this case return undefined instead of an empty object, to save space
  2152. return;
  2153. }
  2154. var valueRecord = {};
  2155. if (valueFormat & 0x0001) { valueRecord.xPlacement = this.parseShort(); }
  2156. if (valueFormat & 0x0002) { valueRecord.yPlacement = this.parseShort(); }
  2157. if (valueFormat & 0x0004) { valueRecord.xAdvance = this.parseShort(); }
  2158. if (valueFormat & 0x0008) { valueRecord.yAdvance = this.parseShort(); }
  2159. // Device table (non-variable font) / VariationIndex table (variable font) not supported
  2160. // https://docs.microsoft.com/fr-fr/typography/opentype/spec/chapter2#devVarIdxTbls
  2161. if (valueFormat & 0x0010) { valueRecord.xPlaDevice = undefined; this.parseShort(); }
  2162. if (valueFormat & 0x0020) { valueRecord.yPlaDevice = undefined; this.parseShort(); }
  2163. if (valueFormat & 0x0040) { valueRecord.xAdvDevice = undefined; this.parseShort(); }
  2164. if (valueFormat & 0x0080) { valueRecord.yAdvDevice = undefined; this.parseShort(); }
  2165. return valueRecord;
  2166. };
  2167. /**
  2168. * Parse a list of GPOS valueRecords
  2169. * https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#value-record
  2170. * valueFormat and valueCount are read from the stream.
  2171. */
  2172. Parser.prototype.parseValueRecordList = function() {
  2173. var valueFormat = this.parseUShort();
  2174. var valueCount = this.parseUShort();
  2175. var values = new Array(valueCount);
  2176. for (var i = 0; i < valueCount; i++) {
  2177. values[i] = this.parseValueRecord(valueFormat);
  2178. }
  2179. return values;
  2180. };
  2181. Parser.prototype.parsePointer = function(description) {
  2182. var structOffset = this.parseOffset16();
  2183. if (structOffset > 0) {
  2184. // NULL offset => return undefined
  2185. return new Parser(this.data, this.offset + structOffset).parseStruct(description);
  2186. }
  2187. return undefined;
  2188. };
  2189. Parser.prototype.parsePointer32 = function(description) {
  2190. var structOffset = this.parseOffset32();
  2191. if (structOffset > 0) {
  2192. // NULL offset => return undefined
  2193. return new Parser(this.data, this.offset + structOffset).parseStruct(description);
  2194. }
  2195. return undefined;
  2196. };
  2197. /**
  2198. * Parse a list of offsets to lists of 16-bit integers,
  2199. * or a list of offsets to lists of offsets to any kind of items.
  2200. * If itemCallback is not provided, a list of list of UShort is assumed.
  2201. * If provided, itemCallback is called on each item and must parse the item.
  2202. * See examples in tables/gsub.js
  2203. */
  2204. Parser.prototype.parseListOfLists = function(itemCallback) {
  2205. var offsets = this.parseOffset16List();
  2206. var count = offsets.length;
  2207. var relativeOffset = this.relativeOffset;
  2208. var list = new Array(count);
  2209. for (var i = 0; i < count; i++) {
  2210. var start = offsets[i];
  2211. if (start === 0) {
  2212. // NULL offset
  2213. // Add i as owned property to list. Convenient with assert.
  2214. list[i] = undefined;
  2215. continue;
  2216. }
  2217. this.relativeOffset = start;
  2218. if (itemCallback) {
  2219. var subOffsets = this.parseOffset16List();
  2220. var subList = new Array(subOffsets.length);
  2221. for (var j = 0; j < subOffsets.length; j++) {
  2222. this.relativeOffset = start + subOffsets[j];
  2223. subList[j] = itemCallback.call(this);
  2224. }
  2225. list[i] = subList;
  2226. } else {
  2227. list[i] = this.parseUShortList();
  2228. }
  2229. }
  2230. this.relativeOffset = relativeOffset;
  2231. return list;
  2232. };
  2233. ///// Complex tables parsing //////////////////////////////////
  2234. // Parse a coverage table in a GSUB, GPOS or GDEF table.
  2235. // https://www.microsoft.com/typography/OTSPEC/chapter2.htm
  2236. // parser.offset must point to the start of the table containing the coverage.
  2237. Parser.prototype.parseCoverage = function() {
  2238. var startOffset = this.offset + this.relativeOffset;
  2239. var format = this.parseUShort();
  2240. var count = this.parseUShort();
  2241. if (format === 1) {
  2242. return {
  2243. format: 1,
  2244. glyphs: this.parseUShortList(count)
  2245. };
  2246. } else if (format === 2) {
  2247. var ranges = new Array(count);
  2248. for (var i = 0; i < count; i++) {
  2249. ranges[i] = {
  2250. start: this.parseUShort(),
  2251. end: this.parseUShort(),
  2252. index: this.parseUShort()
  2253. };
  2254. }
  2255. return {
  2256. format: 2,
  2257. ranges: ranges
  2258. };
  2259. }
  2260. throw new Error('0x' + startOffset.toString(16) + ': Coverage format must be 1 or 2.');
  2261. };
  2262. // Parse a Class Definition Table in a GSUB, GPOS or GDEF table.
  2263. // https://www.microsoft.com/typography/OTSPEC/chapter2.htm
  2264. Parser.prototype.parseClassDef = function() {
  2265. var startOffset = this.offset + this.relativeOffset;
  2266. var format = this.parseUShort();
  2267. if (format === 1) {
  2268. return {
  2269. format: 1,
  2270. startGlyph: this.parseUShort(),
  2271. classes: this.parseUShortList()
  2272. };
  2273. } else if (format === 2) {
  2274. return {
  2275. format: 2,
  2276. ranges: this.parseRecordList({
  2277. start: Parser.uShort,
  2278. end: Parser.uShort,
  2279. classId: Parser.uShort
  2280. })
  2281. };
  2282. }
  2283. throw new Error('0x' + startOffset.toString(16) + ': ClassDef format must be 1 or 2.');
  2284. };
  2285. ///// Static methods ///////////////////////////////////
  2286. // These convenience methods can be used as callbacks and should be called with "this" context set to a Parser instance.
  2287. Parser.list = function(count, itemCallback) {
  2288. return function() {
  2289. return this.parseList(count, itemCallback);
  2290. };
  2291. };
  2292. Parser.list32 = function(count, itemCallback) {
  2293. return function() {
  2294. return this.parseList32(count, itemCallback);
  2295. };
  2296. };
  2297. Parser.recordList = function(count, recordDescription) {
  2298. return function() {
  2299. return this.parseRecordList(count, recordDescription);
  2300. };
  2301. };
  2302. Parser.recordList32 = function(count, recordDescription) {
  2303. return function() {
  2304. return this.parseRecordList32(count, recordDescription);
  2305. };
  2306. };
  2307. Parser.pointer = function(description) {
  2308. return function() {
  2309. return this.parsePointer(description);
  2310. };
  2311. };
  2312. Parser.pointer32 = function(description) {
  2313. return function() {
  2314. return this.parsePointer32(description);
  2315. };
  2316. };
  2317. Parser.tag = Parser.prototype.parseTag;
  2318. Parser.byte = Parser.prototype.parseByte;
  2319. Parser.uShort = Parser.offset16 = Parser.prototype.parseUShort;
  2320. Parser.uShortList = Parser.prototype.parseUShortList;
  2321. Parser.uLong = Parser.offset32 = Parser.prototype.parseULong;
  2322. Parser.uLongList = Parser.prototype.parseULongList;
  2323. Parser.struct = Parser.prototype.parseStruct;
  2324. Parser.coverage = Parser.prototype.parseCoverage;
  2325. Parser.classDef = Parser.prototype.parseClassDef;
  2326. ///// Script, Feature, Lookup lists ///////////////////////////////////////////////
  2327. // https://www.microsoft.com/typography/OTSPEC/chapter2.htm
  2328. var langSysTable = {
  2329. reserved: Parser.uShort,
  2330. reqFeatureIndex: Parser.uShort,
  2331. featureIndexes: Parser.uShortList
  2332. };
  2333. Parser.prototype.parseScriptList = function() {
  2334. return this.parsePointer(Parser.recordList({
  2335. tag: Parser.tag,
  2336. script: Parser.pointer({
  2337. defaultLangSys: Parser.pointer(langSysTable),
  2338. langSysRecords: Parser.recordList({
  2339. tag: Parser.tag,
  2340. langSys: Parser.pointer(langSysTable)
  2341. })
  2342. })
  2343. })) || [];
  2344. };
  2345. Parser.prototype.parseFeatureList = function() {
  2346. return this.parsePointer(Parser.recordList({
  2347. tag: Parser.tag,
  2348. feature: Parser.pointer({
  2349. featureParams: Parser.offset16,
  2350. lookupListIndexes: Parser.uShortList
  2351. })
  2352. })) || [];
  2353. };
  2354. Parser.prototype.parseLookupList = function(lookupTableParsers) {
  2355. return this.parsePointer(Parser.list(Parser.pointer(function() {
  2356. var lookupType = this.parseUShort();
  2357. check.argument(1 <= lookupType && lookupType <= 9, 'GPOS/GSUB lookup type ' + lookupType + ' unknown.');
  2358. var lookupFlag = this.parseUShort();
  2359. var useMarkFilteringSet = lookupFlag & 0x10;
  2360. return {
  2361. lookupType: lookupType,
  2362. lookupFlag: lookupFlag,
  2363. subtables: this.parseList(Parser.pointer(lookupTableParsers[lookupType])),
  2364. markFilteringSet: useMarkFilteringSet ? this.parseUShort() : undefined
  2365. };
  2366. }))) || [];
  2367. };
  2368. Parser.prototype.parseFeatureVariationsList = function() {
  2369. return this.parsePointer32(function() {
  2370. var majorVersion = this.parseUShort();
  2371. var minorVersion = this.parseUShort();
  2372. check.argument(majorVersion === 1 && minorVersion < 1, 'GPOS/GSUB feature variations table unknown.');
  2373. var featureVariations = this.parseRecordList32({
  2374. conditionSetOffset: Parser.offset32,
  2375. featureTableSubstitutionOffset: Parser.offset32
  2376. });
  2377. return featureVariations;
  2378. }) || [];
  2379. };
  2380. var parse = {
  2381. getByte: getByte,
  2382. getCard8: getByte,
  2383. getUShort: getUShort,
  2384. getCard16: getUShort,
  2385. getShort: getShort,
  2386. getULong: getULong,
  2387. getFixed: getFixed,
  2388. getTag: getTag,
  2389. getOffset: getOffset,
  2390. getBytes: getBytes,
  2391. bytesToString: bytesToString,
  2392. Parser: Parser,
  2393. };
  2394. // The `cmap` table stores the mappings from characters to glyphs.
  2395. function parseCmapTableFormat12(cmap, p) {
  2396. //Skip reserved.
  2397. p.parseUShort();
  2398. // Length in bytes of the sub-tables.
  2399. cmap.length = p.parseULong();
  2400. cmap.language = p.parseULong();
  2401. var groupCount;
  2402. cmap.groupCount = groupCount = p.parseULong();
  2403. cmap.glyphIndexMap = {};
  2404. for (var i = 0; i < groupCount; i += 1) {
  2405. var startCharCode = p.parseULong();
  2406. var endCharCode = p.parseULong();
  2407. var startGlyphId = p.parseULong();
  2408. for (var c = startCharCode; c <= endCharCode; c += 1) {
  2409. cmap.glyphIndexMap[c] = startGlyphId;
  2410. startGlyphId++;
  2411. }
  2412. }
  2413. }
  2414. function parseCmapTableFormat4(cmap, p, data, start, offset) {
  2415. // Length in bytes of the sub-tables.
  2416. cmap.length = p.parseUShort();
  2417. cmap.language = p.parseUShort();
  2418. // segCount is stored x 2.
  2419. var segCount;
  2420. cmap.segCount = segCount = p.parseUShort() >> 1;
  2421. // Skip searchRange, entrySelector, rangeShift.
  2422. p.skip('uShort', 3);
  2423. // The "unrolled" mapping from character codes to glyph indices.
  2424. cmap.glyphIndexMap = {};
  2425. var endCountParser = new parse.Parser(data, start + offset + 14);
  2426. var startCountParser = new parse.Parser(data, start + offset + 16 + segCount * 2);
  2427. var idDeltaParser = new parse.Parser(data, start + offset + 16 + segCount * 4);
  2428. var idRangeOffsetParser = new parse.Parser(data, start + offset + 16 + segCount * 6);
  2429. var glyphIndexOffset = start + offset + 16 + segCount * 8;
  2430. for (var i = 0; i < segCount - 1; i += 1) {
  2431. var glyphIndex = (void 0);
  2432. var endCount = endCountParser.parseUShort();
  2433. var startCount = startCountParser.parseUShort();
  2434. var idDelta = idDeltaParser.parseShort();
  2435. var idRangeOffset = idRangeOffsetParser.parseUShort();
  2436. for (var c = startCount; c <= endCount; c += 1) {
  2437. if (idRangeOffset !== 0) {
  2438. // The idRangeOffset is relative to the current position in the idRangeOffset array.
  2439. // Take the current offset in the idRangeOffset array.
  2440. glyphIndexOffset = (idRangeOffsetParser.offset + idRangeOffsetParser.relativeOffset - 2);
  2441. // Add the value of the idRangeOffset, which will move us into the glyphIndex array.
  2442. glyphIndexOffset += idRangeOffset;
  2443. // Then add the character index of the current segment, multiplied by 2 for USHORTs.
  2444. glyphIndexOffset += (c - startCount) * 2;
  2445. glyphIndex = parse.getUShort(data, glyphIndexOffset);
  2446. if (glyphIndex !== 0) {
  2447. glyphIndex = (glyphIndex + idDelta) & 0xFFFF;
  2448. }
  2449. } else {
  2450. glyphIndex = (c + idDelta) & 0xFFFF;
  2451. }
  2452. cmap.glyphIndexMap[c] = glyphIndex;
  2453. }
  2454. }
  2455. }
  2456. // Parse the `cmap` table. This table stores the mappings from characters to glyphs.
  2457. // There are many available formats, but we only support the Windows format 4 and 12.
  2458. // This function returns a `CmapEncoding` object or null if no supported format could be found.
  2459. function parseCmapTable(data, start) {
  2460. var cmap = {};
  2461. cmap.version = parse.getUShort(data, start);
  2462. check.argument(cmap.version === 0, 'cmap table version should be 0.');
  2463. // The cmap table can contain many sub-tables, each with their own format.
  2464. // We're only interested in a "platform 0" (Unicode format) and "platform 3" (Windows format) table.
  2465. cmap.numTables = parse.getUShort(data, start + 2);
  2466. var offset = -1;
  2467. for (var i = cmap.numTables - 1; i >= 0; i -= 1) {
  2468. var platformId = parse.getUShort(data, start + 4 + (i * 8));
  2469. var encodingId = parse.getUShort(data, start + 4 + (i * 8) + 2);
  2470. if ((platformId === 3 && (encodingId === 0 || encodingId === 1 || encodingId === 10)) ||
  2471. (platformId === 0 && (encodingId === 0 || encodingId === 1 || encodingId === 2 || encodingId === 3 || encodingId === 4))) {
  2472. offset = parse.getULong(data, start + 4 + (i * 8) + 4);
  2473. break;
  2474. }
  2475. }
  2476. if (offset === -1) {
  2477. // There is no cmap table in the font that we support.
  2478. throw new Error('No valid cmap sub-tables found.');
  2479. }
  2480. var p = new parse.Parser(data, start + offset);
  2481. cmap.format = p.parseUShort();
  2482. if (cmap.format === 12) {
  2483. parseCmapTableFormat12(cmap, p);
  2484. } else if (cmap.format === 4) {
  2485. parseCmapTableFormat4(cmap, p, data, start, offset);
  2486. } else {
  2487. throw new Error('Only format 4 and 12 cmap tables are supported (found format ' + cmap.format + ').');
  2488. }
  2489. return cmap;
  2490. }
  2491. function addSegment(t, code, glyphIndex) {
  2492. t.segments.push({
  2493. end: code,
  2494. start: code,
  2495. delta: -(code - glyphIndex),
  2496. offset: 0,
  2497. glyphIndex: glyphIndex
  2498. });
  2499. }
  2500. function addTerminatorSegment(t) {
  2501. t.segments.push({
  2502. end: 0xFFFF,
  2503. start: 0xFFFF,
  2504. delta: 1,
  2505. offset: 0
  2506. });
  2507. }
  2508. // Make cmap table, format 4 by default, 12 if needed only
  2509. function makeCmapTable(glyphs) {
  2510. // Plan 0 is the base Unicode Plan but emojis, for example are on another plan, and needs cmap 12 format (with 32bit)
  2511. var isPlan0Only = true;
  2512. var i;
  2513. // Check if we need to add cmap format 12 or if format 4 only is fine
  2514. for (i = glyphs.length - 1; i > 0; i -= 1) {
  2515. var g = glyphs.get(i);
  2516. if (g.unicode > 65535) {
  2517. console.log('Adding CMAP format 12 (needed!)');
  2518. isPlan0Only = false;
  2519. break;
  2520. }
  2521. }
  2522. var cmapTable = [
  2523. {name: 'version', type: 'USHORT', value: 0},
  2524. {name: 'numTables', type: 'USHORT', value: isPlan0Only ? 1 : 2},
  2525. // CMAP 4 header
  2526. {name: 'platformID', type: 'USHORT', value: 3},
  2527. {name: 'encodingID', type: 'USHORT', value: 1},
  2528. {name: 'offset', type: 'ULONG', value: isPlan0Only ? 12 : (12 + 8)}
  2529. ];
  2530. if (!isPlan0Only)
  2531. { cmapTable = cmapTable.concat([
  2532. // CMAP 12 header
  2533. {name: 'cmap12PlatformID', type: 'USHORT', value: 3}, // We encode only for PlatformID = 3 (Windows) because it is supported everywhere
  2534. {name: 'cmap12EncodingID', type: 'USHORT', value: 10},
  2535. {name: 'cmap12Offset', type: 'ULONG', value: 0}
  2536. ]); }
  2537. cmapTable = cmapTable.concat([
  2538. // CMAP 4 Subtable
  2539. {name: 'format', type: 'USHORT', value: 4},
  2540. {name: 'cmap4Length', type: 'USHORT', value: 0},
  2541. {name: 'language', type: 'USHORT', value: 0},
  2542. {name: 'segCountX2', type: 'USHORT', value: 0},
  2543. {name: 'searchRange', type: 'USHORT', value: 0},
  2544. {name: 'entrySelector', type: 'USHORT', value: 0},
  2545. {name: 'rangeShift', type: 'USHORT', value: 0}
  2546. ]);
  2547. var t = new table.Table('cmap', cmapTable);
  2548. t.segments = [];
  2549. for (i = 0; i < glyphs.length; i += 1) {
  2550. var glyph = glyphs.get(i);
  2551. for (var j = 0; j < glyph.unicodes.length; j += 1) {
  2552. addSegment(t, glyph.unicodes[j], i);
  2553. }
  2554. t.segments = t.segments.sort(function (a, b) {
  2555. return a.start - b.start;
  2556. });
  2557. }
  2558. addTerminatorSegment(t);
  2559. var segCount = t.segments.length;
  2560. var segCountToRemove = 0;
  2561. // CMAP 4
  2562. // Set up parallel segment arrays.
  2563. var endCounts = [];
  2564. var startCounts = [];
  2565. var idDeltas = [];
  2566. var idRangeOffsets = [];
  2567. var glyphIds = [];
  2568. // CMAP 12
  2569. var cmap12Groups = [];
  2570. // Reminder this loop is not following the specification at 100%
  2571. // The specification -> find suites of characters and make a group
  2572. // Here we're doing one group for each letter
  2573. // Doing as the spec can save 8 times (or more) space
  2574. for (i = 0; i < segCount; i += 1) {
  2575. var segment = t.segments[i];
  2576. // CMAP 4
  2577. if (segment.end <= 65535 && segment.start <= 65535) {
  2578. endCounts = endCounts.concat({name: 'end_' + i, type: 'USHORT', value: segment.end});
  2579. startCounts = startCounts.concat({name: 'start_' + i, type: 'USHORT', value: segment.start});
  2580. idDeltas = idDeltas.concat({name: 'idDelta_' + i, type: 'SHORT', value: segment.delta});
  2581. idRangeOffsets = idRangeOffsets.concat({name: 'idRangeOffset_' + i, type: 'USHORT', value: segment.offset});
  2582. if (segment.glyphId !== undefined) {
  2583. glyphIds = glyphIds.concat({name: 'glyph_' + i, type: 'USHORT', value: segment.glyphId});
  2584. }
  2585. } else {
  2586. // Skip Unicode > 65535 (16bit unsigned max) for CMAP 4, will be added in CMAP 12
  2587. segCountToRemove += 1;
  2588. }
  2589. // CMAP 12
  2590. // Skip Terminator Segment
  2591. if (!isPlan0Only && segment.glyphIndex !== undefined) {
  2592. cmap12Groups = cmap12Groups.concat({name: 'cmap12Start_' + i, type: 'ULONG', value: segment.start});
  2593. cmap12Groups = cmap12Groups.concat({name: 'cmap12End_' + i, type: 'ULONG', value: segment.end});
  2594. cmap12Groups = cmap12Groups.concat({name: 'cmap12Glyph_' + i, type: 'ULONG', value: segment.glyphIndex});
  2595. }
  2596. }
  2597. // CMAP 4 Subtable
  2598. t.segCountX2 = (segCount - segCountToRemove) * 2;
  2599. t.searchRange = Math.pow(2, Math.floor(Math.log((segCount - segCountToRemove)) / Math.log(2))) * 2;
  2600. t.entrySelector = Math.log(t.searchRange / 2) / Math.log(2);
  2601. t.rangeShift = t.segCountX2 - t.searchRange;
  2602. t.fields = t.fields.concat(endCounts);
  2603. t.fields.push({name: 'reservedPad', type: 'USHORT', value: 0});
  2604. t.fields = t.fields.concat(startCounts);
  2605. t.fields = t.fields.concat(idDeltas);
  2606. t.fields = t.fields.concat(idRangeOffsets);
  2607. t.fields = t.fields.concat(glyphIds);
  2608. t.cmap4Length = 14 + // Subtable header
  2609. endCounts.length * 2 +
  2610. 2 + // reservedPad
  2611. startCounts.length * 2 +
  2612. idDeltas.length * 2 +
  2613. idRangeOffsets.length * 2 +
  2614. glyphIds.length * 2;
  2615. if (!isPlan0Only) {
  2616. // CMAP 12 Subtable
  2617. var cmap12Length = 16 + // Subtable header
  2618. cmap12Groups.length * 4;
  2619. t.cmap12Offset = 12 + (2 * 2) + 4 + t.cmap4Length;
  2620. t.fields = t.fields.concat([
  2621. {name: 'cmap12Format', type: 'USHORT', value: 12},
  2622. {name: 'cmap12Reserved', type: 'USHORT', value: 0},
  2623. {name: 'cmap12Length', type: 'ULONG', value: cmap12Length},
  2624. {name: 'cmap12Language', type: 'ULONG', value: 0},
  2625. {name: 'cmap12nGroups', type: 'ULONG', value: cmap12Groups.length / 3}
  2626. ]);
  2627. t.fields = t.fields.concat(cmap12Groups);
  2628. }
  2629. return t;
  2630. }
  2631. var cmap = { parse: parseCmapTable, make: makeCmapTable };
  2632. // Glyph encoding
  2633. var cffStandardStrings = [
  2634. '.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quoteright',
  2635. 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two',
  2636. 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater',
  2637. 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
  2638. 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore',
  2639. 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
  2640. 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', 'exclamdown', 'cent', 'sterling',
  2641. 'fraction', 'yen', 'florin', 'section', 'currency', 'quotesingle', 'quotedblleft', 'guillemotleft',
  2642. 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'endash', 'dagger', 'daggerdbl', 'periodcentered', 'paragraph',
  2643. 'bullet', 'quotesinglbase', 'quotedblbase', 'quotedblright', 'guillemotright', 'ellipsis', 'perthousand',
  2644. 'questiondown', 'grave', 'acute', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'dieresis', 'ring',
  2645. 'cedilla', 'hungarumlaut', 'ogonek', 'caron', 'emdash', 'AE', 'ordfeminine', 'Lslash', 'Oslash', 'OE',
  2646. 'ordmasculine', 'ae', 'dotlessi', 'lslash', 'oslash', 'oe', 'germandbls', 'onesuperior', 'logicalnot', 'mu',
  2647. 'trademark', 'Eth', 'onehalf', 'plusminus', 'Thorn', 'onequarter', 'divide', 'brokenbar', 'degree', 'thorn',
  2648. 'threequarters', 'twosuperior', 'registered', 'minus', 'eth', 'multiply', 'threesuperior', 'copyright',
  2649. 'Aacute', 'Acircumflex', 'Adieresis', 'Agrave', 'Aring', 'Atilde', 'Ccedilla', 'Eacute', 'Ecircumflex',
  2650. 'Edieresis', 'Egrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Ntilde', 'Oacute', 'Ocircumflex',
  2651. 'Odieresis', 'Ograve', 'Otilde', 'Scaron', 'Uacute', 'Ucircumflex', 'Udieresis', 'Ugrave', 'Yacute',
  2652. 'Ydieresis', 'Zcaron', 'aacute', 'acircumflex', 'adieresis', 'agrave', 'aring', 'atilde', 'ccedilla', 'eacute',
  2653. 'ecircumflex', 'edieresis', 'egrave', 'iacute', 'icircumflex', 'idieresis', 'igrave', 'ntilde', 'oacute',
  2654. 'ocircumflex', 'odieresis', 'ograve', 'otilde', 'scaron', 'uacute', 'ucircumflex', 'udieresis', 'ugrave',
  2655. 'yacute', 'ydieresis', 'zcaron', 'exclamsmall', 'Hungarumlautsmall', 'dollaroldstyle', 'dollarsuperior',
  2656. 'ampersandsmall', 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', '266 ff', 'onedotenleader',
  2657. 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle',
  2658. 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'commasuperior', 'threequartersemdash', 'periodsuperior',
  2659. 'questionsmall', 'asuperior', 'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', 'isuperior', 'lsuperior',
  2660. 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior', 'tsuperior', 'ff', 'ffi', 'ffl',
  2661. 'parenleftinferior', 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall',
  2662. 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall',
  2663. 'Msmall', 'Nsmall', 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall',
  2664. 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah', 'Tildesmall', 'exclamdownsmall',
  2665. 'centoldstyle', 'Lslashsmall', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall', 'Caronsmall',
  2666. 'Dotaccentsmall', 'Macronsmall', 'figuredash', 'hypheninferior', 'Ogoneksmall', 'Ringsmall', 'Cedillasmall',
  2667. 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds',
  2668. 'zerosuperior', 'foursuperior', 'fivesuperior', 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior',
  2669. 'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior',
  2670. 'seveninferior', 'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior',
  2671. 'commainferior', 'Agravesmall', 'Aacutesmall', 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall',
  2672. 'Aringsmall', 'AEsmall', 'Ccedillasmall', 'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall',
  2673. 'Igravesmall', 'Iacutesmall', 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall', 'Ogravesmall',
  2674. 'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall',
  2675. 'Uacutesmall', 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall', 'Ydieresissmall', '001.000',
  2676. '001.001', '001.002', '001.003', 'Black', 'Bold', 'Book', 'Light', 'Medium', 'Regular', 'Roman', 'Semibold'];
  2677. var cffStandardEncoding = [
  2678. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  2679. '', '', '', '', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quoteright',
  2680. 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two',
  2681. 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater',
  2682. 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
  2683. 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore',
  2684. 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
  2685. 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', '', '', '', '', '', '', '', '',
  2686. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  2687. 'exclamdown', 'cent', 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency', 'quotesingle',
  2688. 'quotedblleft', 'guillemotleft', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', '', 'endash', 'dagger',
  2689. 'daggerdbl', 'periodcentered', '', 'paragraph', 'bullet', 'quotesinglbase', 'quotedblbase', 'quotedblright',
  2690. 'guillemotright', 'ellipsis', 'perthousand', '', 'questiondown', '', 'grave', 'acute', 'circumflex', 'tilde',
  2691. 'macron', 'breve', 'dotaccent', 'dieresis', '', 'ring', 'cedilla', '', 'hungarumlaut', 'ogonek', 'caron',
  2692. 'emdash', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'AE', '', 'ordfeminine', '', '', '',
  2693. '', 'Lslash', 'Oslash', 'OE', 'ordmasculine', '', '', '', '', '', 'ae', '', '', '', 'dotlessi', '', '',
  2694. 'lslash', 'oslash', 'oe', 'germandbls'];
  2695. var cffExpertEncoding = [
  2696. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  2697. '', '', '', '', 'space', 'exclamsmall', 'Hungarumlautsmall', '', 'dollaroldstyle', 'dollarsuperior',
  2698. 'ampersandsmall', 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader', 'onedotenleader',
  2699. 'comma', 'hyphen', 'period', 'fraction', 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle',
  2700. 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'colon',
  2701. 'semicolon', 'commasuperior', 'threequartersemdash', 'periodsuperior', 'questionsmall', '', 'asuperior',
  2702. 'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', '', '', 'isuperior', '', '', 'lsuperior', 'msuperior',
  2703. 'nsuperior', 'osuperior', '', '', 'rsuperior', 'ssuperior', 'tsuperior', '', 'ff', 'fi', 'fl', 'ffi', 'ffl',
  2704. 'parenleftinferior', '', 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall',
  2705. 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall',
  2706. 'Msmall', 'Nsmall', 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall',
  2707. 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah', 'Tildesmall', '', '', '', '', '', '', '',
  2708. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  2709. 'exclamdownsmall', 'centoldstyle', 'Lslashsmall', '', '', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall',
  2710. 'Brevesmall', 'Caronsmall', '', 'Dotaccentsmall', '', '', 'Macronsmall', '', '', 'figuredash', 'hypheninferior',
  2711. '', '', 'Ogoneksmall', 'Ringsmall', 'Cedillasmall', '', '', '', 'onequarter', 'onehalf', 'threequarters',
  2712. 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds', '',
  2713. '', 'zerosuperior', 'onesuperior', 'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior',
  2714. 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior', 'zeroinferior', 'oneinferior', 'twoinferior',
  2715. 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior', 'eightinferior',
  2716. 'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior', 'commainferior', 'Agravesmall',
  2717. 'Aacutesmall', 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall', 'Aringsmall', 'AEsmall', 'Ccedillasmall',
  2718. 'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall',
  2719. 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall', 'Ogravesmall', 'Oacutesmall',
  2720. 'Ocircumflexsmall', 'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall',
  2721. 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall', 'Ydieresissmall'];
  2722. var standardNames = [
  2723. '.notdef', '.null', 'nonmarkingreturn', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent',
  2724. 'ampersand', 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash',
  2725. 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less',
  2726. 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
  2727. 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright',
  2728. 'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
  2729. 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde',
  2730. 'Adieresis', 'Aring', 'Ccedilla', 'Eacute', 'Ntilde', 'Odieresis', 'Udieresis', 'aacute', 'agrave',
  2731. 'acircumflex', 'adieresis', 'atilde', 'aring', 'ccedilla', 'eacute', 'egrave', 'ecircumflex', 'edieresis',
  2732. 'iacute', 'igrave', 'icircumflex', 'idieresis', 'ntilde', 'oacute', 'ograve', 'ocircumflex', 'odieresis',
  2733. 'otilde', 'uacute', 'ugrave', 'ucircumflex', 'udieresis', 'dagger', 'degree', 'cent', 'sterling', 'section',
  2734. 'bullet', 'paragraph', 'germandbls', 'registered', 'copyright', 'trademark', 'acute', 'dieresis', 'notequal',
  2735. 'AE', 'Oslash', 'infinity', 'plusminus', 'lessequal', 'greaterequal', 'yen', 'mu', 'partialdiff', 'summation',
  2736. 'product', 'pi', 'integral', 'ordfeminine', 'ordmasculine', 'Omega', 'ae', 'oslash', 'questiondown',
  2737. 'exclamdown', 'logicalnot', 'radical', 'florin', 'approxequal', 'Delta', 'guillemotleft', 'guillemotright',
  2738. 'ellipsis', 'nonbreakingspace', 'Agrave', 'Atilde', 'Otilde', 'OE', 'oe', 'endash', 'emdash', 'quotedblleft',
  2739. 'quotedblright', 'quoteleft', 'quoteright', 'divide', 'lozenge', 'ydieresis', 'Ydieresis', 'fraction',
  2740. 'currency', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'daggerdbl', 'periodcentered', 'quotesinglbase',
  2741. 'quotedblbase', 'perthousand', 'Acircumflex', 'Ecircumflex', 'Aacute', 'Edieresis', 'Egrave', 'Iacute',
  2742. 'Icircumflex', 'Idieresis', 'Igrave', 'Oacute', 'Ocircumflex', 'apple', 'Ograve', 'Uacute', 'Ucircumflex',
  2743. 'Ugrave', 'dotlessi', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'ring', 'cedilla', 'hungarumlaut',
  2744. 'ogonek', 'caron', 'Lslash', 'lslash', 'Scaron', 'scaron', 'Zcaron', 'zcaron', 'brokenbar', 'Eth', 'eth',
  2745. 'Yacute', 'yacute', 'Thorn', 'thorn', 'minus', 'multiply', 'onesuperior', 'twosuperior', 'threesuperior',
  2746. 'onehalf', 'onequarter', 'threequarters', 'franc', 'Gbreve', 'gbreve', 'Idotaccent', 'Scedilla', 'scedilla',
  2747. 'Cacute', 'cacute', 'Ccaron', 'ccaron', 'dcroat'];
  2748. /**
  2749. * This is the encoding used for fonts created from scratch.
  2750. * It loops through all glyphs and finds the appropriate unicode value.
  2751. * Since it's linear time, other encodings will be faster.
  2752. * @exports opentype.DefaultEncoding
  2753. * @class
  2754. * @constructor
  2755. * @param {opentype.Font}
  2756. */
  2757. function DefaultEncoding(font) {
  2758. this.font = font;
  2759. }
  2760. DefaultEncoding.prototype.charToGlyphIndex = function(c) {
  2761. var code = c.codePointAt(0);
  2762. var glyphs = this.font.glyphs;
  2763. if (glyphs) {
  2764. for (var i = 0; i < glyphs.length; i += 1) {
  2765. var glyph = glyphs.get(i);
  2766. for (var j = 0; j < glyph.unicodes.length; j += 1) {
  2767. if (glyph.unicodes[j] === code) {
  2768. return i;
  2769. }
  2770. }
  2771. }
  2772. }
  2773. return null;
  2774. };
  2775. /**
  2776. * @exports opentype.CmapEncoding
  2777. * @class
  2778. * @constructor
  2779. * @param {Object} cmap - a object with the cmap encoded data
  2780. */
  2781. function CmapEncoding(cmap) {
  2782. this.cmap = cmap;
  2783. }
  2784. /**
  2785. * @param {string} c - the character
  2786. * @return {number} The glyph index.
  2787. */
  2788. CmapEncoding.prototype.charToGlyphIndex = function(c) {
  2789. return this.cmap.glyphIndexMap[c.codePointAt(0)] || 0;
  2790. };
  2791. /**
  2792. * @exports opentype.CffEncoding
  2793. * @class
  2794. * @constructor
  2795. * @param {string} encoding - The encoding
  2796. * @param {Array} charset - The character set.
  2797. */
  2798. function CffEncoding(encoding, charset) {
  2799. this.encoding = encoding;
  2800. this.charset = charset;
  2801. }
  2802. /**
  2803. * @param {string} s - The character
  2804. * @return {number} The index.
  2805. */
  2806. CffEncoding.prototype.charToGlyphIndex = function(s) {
  2807. var code = s.codePointAt(0);
  2808. var charName = this.encoding[code];
  2809. return this.charset.indexOf(charName);
  2810. };
  2811. /**
  2812. * @exports opentype.GlyphNames
  2813. * @class
  2814. * @constructor
  2815. * @param {Object} post
  2816. */
  2817. function GlyphNames(post) {
  2818. switch (post.version) {
  2819. case 1:
  2820. this.names = standardNames.slice();
  2821. break;
  2822. case 2:
  2823. this.names = new Array(post.numberOfGlyphs);
  2824. for (var i = 0; i < post.numberOfGlyphs; i++) {
  2825. if (post.glyphNameIndex[i] < standardNames.length) {
  2826. this.names[i] = standardNames[post.glyphNameIndex[i]];
  2827. } else {
  2828. this.names[i] = post.names[post.glyphNameIndex[i] - standardNames.length];
  2829. }
  2830. }
  2831. break;
  2832. case 2.5:
  2833. this.names = new Array(post.numberOfGlyphs);
  2834. for (var i$1 = 0; i$1 < post.numberOfGlyphs; i$1++) {
  2835. this.names[i$1] = standardNames[i$1 + post.glyphNameIndex[i$1]];
  2836. }
  2837. break;
  2838. case 3:
  2839. this.names = [];
  2840. break;
  2841. default:
  2842. this.names = [];
  2843. break;
  2844. }
  2845. }
  2846. /**
  2847. * Gets the index of a glyph by name.
  2848. * @param {string} name - The glyph name
  2849. * @return {number} The index
  2850. */
  2851. GlyphNames.prototype.nameToGlyphIndex = function(name) {
  2852. return this.names.indexOf(name);
  2853. };
  2854. /**
  2855. * @param {number} gid
  2856. * @return {string}
  2857. */
  2858. GlyphNames.prototype.glyphIndexToName = function(gid) {
  2859. return this.names[gid];
  2860. };
  2861. function addGlyphNamesAll(font) {
  2862. var glyph;
  2863. var glyphIndexMap = font.tables.cmap.glyphIndexMap;
  2864. var charCodes = Object.keys(glyphIndexMap);
  2865. for (var i = 0; i < charCodes.length; i += 1) {
  2866. var c = charCodes[i];
  2867. var glyphIndex = glyphIndexMap[c];
  2868. glyph = font.glyphs.get(glyphIndex);
  2869. glyph.addUnicode(parseInt(c));
  2870. }
  2871. for (var i$1 = 0; i$1 < font.glyphs.length; i$1 += 1) {
  2872. glyph = font.glyphs.get(i$1);
  2873. if (font.cffEncoding) {
  2874. if (font.isCIDFont) {
  2875. glyph.name = 'gid' + i$1;
  2876. } else {
  2877. glyph.name = font.cffEncoding.charset[i$1];
  2878. }
  2879. } else if (font.glyphNames.names) {
  2880. glyph.name = font.glyphNames.glyphIndexToName(i$1);
  2881. }
  2882. }
  2883. }
  2884. function addGlyphNamesToUnicodeMap(font) {
  2885. font._IndexToUnicodeMap = {};
  2886. var glyphIndexMap = font.tables.cmap.glyphIndexMap;
  2887. var charCodes = Object.keys(glyphIndexMap);
  2888. for (var i = 0; i < charCodes.length; i += 1) {
  2889. var c = charCodes[i];
  2890. var glyphIndex = glyphIndexMap[c];
  2891. if (font._IndexToUnicodeMap[glyphIndex] === undefined) {
  2892. font._IndexToUnicodeMap[glyphIndex] = {
  2893. unicodes: [parseInt(c)]
  2894. };
  2895. } else {
  2896. font._IndexToUnicodeMap[glyphIndex].unicodes.push(parseInt(c));
  2897. }
  2898. }
  2899. }
  2900. /**
  2901. * @alias opentype.addGlyphNames
  2902. * @param {opentype.Font}
  2903. * @param {Object}
  2904. */
  2905. function addGlyphNames(font, opt) {
  2906. if (opt.lowMemory) {
  2907. addGlyphNamesToUnicodeMap(font);
  2908. } else {
  2909. addGlyphNamesAll(font);
  2910. }
  2911. }
  2912. // Drawing utility functions.
  2913. // Draw a line on the given context from point `x1,y1` to point `x2,y2`.
  2914. function line(ctx, x1, y1, x2, y2) {
  2915. ctx.beginPath();
  2916. ctx.moveTo(x1, y1);
  2917. ctx.lineTo(x2, y2);
  2918. ctx.stroke();
  2919. }
  2920. var draw = { line: line };
  2921. // The Glyph object
  2922. // import glyf from './tables/glyf' Can't be imported here, because it's a circular dependency
  2923. function getPathDefinition(glyph, path) {
  2924. var _path = path || new Path();
  2925. return {
  2926. configurable: true,
  2927. get: function() {
  2928. if (typeof _path === 'function') {
  2929. _path = _path();
  2930. }
  2931. return _path;
  2932. },
  2933. set: function(p) {
  2934. _path = p;
  2935. }
  2936. };
  2937. }
  2938. /**
  2939. * @typedef GlyphOptions
  2940. * @type Object
  2941. * @property {string} [name] - The glyph name
  2942. * @property {number} [unicode]
  2943. * @property {Array} [unicodes]
  2944. * @property {number} [xMin]
  2945. * @property {number} [yMin]
  2946. * @property {number} [xMax]
  2947. * @property {number} [yMax]
  2948. * @property {number} [advanceWidth]
  2949. */
  2950. // A Glyph is an individual mark that often corresponds to a character.
  2951. // Some glyphs, such as ligatures, are a combination of many characters.
  2952. // Glyphs are the basic building blocks of a font.
  2953. //
  2954. // The `Glyph` class contains utility methods for drawing the path and its points.
  2955. /**
  2956. * @exports opentype.Glyph
  2957. * @class
  2958. * @param {GlyphOptions}
  2959. * @constructor
  2960. */
  2961. function Glyph(options) {
  2962. // By putting all the code on a prototype function (which is only declared once)
  2963. // we reduce the memory requirements for larger fonts by some 2%
  2964. this.bindConstructorValues(options);
  2965. }
  2966. /**
  2967. * @param {GlyphOptions}
  2968. */
  2969. Glyph.prototype.bindConstructorValues = function(options) {
  2970. this.index = options.index || 0;
  2971. // These three values cannot be deferred for memory optimization:
  2972. this.name = options.name || null;
  2973. this.unicode = options.unicode || undefined;
  2974. this.unicodes = options.unicodes || options.unicode !== undefined ? [options.unicode] : [];
  2975. // But by binding these values only when necessary, we reduce can
  2976. // the memory requirements by almost 3% for larger fonts.
  2977. if ('xMin' in options) {
  2978. this.xMin = options.xMin;
  2979. }
  2980. if ('yMin' in options) {
  2981. this.yMin = options.yMin;
  2982. }
  2983. if ('xMax' in options) {
  2984. this.xMax = options.xMax;
  2985. }
  2986. if ('yMax' in options) {
  2987. this.yMax = options.yMax;
  2988. }
  2989. if ('advanceWidth' in options) {
  2990. this.advanceWidth = options.advanceWidth;
  2991. }
  2992. // The path for a glyph is the most memory intensive, and is bound as a value
  2993. // with a getter/setter to ensure we actually do path parsing only once the
  2994. // path is actually needed by anything.
  2995. Object.defineProperty(this, 'path', getPathDefinition(this, options.path));
  2996. };
  2997. /**
  2998. * @param {number}
  2999. */
  3000. Glyph.prototype.addUnicode = function(unicode) {
  3001. if (this.unicodes.length === 0) {
  3002. this.unicode = unicode;
  3003. }
  3004. this.unicodes.push(unicode);
  3005. };
  3006. /**
  3007. * Calculate the minimum bounding box for this glyph.
  3008. * @return {opentype.BoundingBox}
  3009. */
  3010. Glyph.prototype.getBoundingBox = function() {
  3011. return this.path.getBoundingBox();
  3012. };
  3013. /**
  3014. * Convert the glyph to a Path we can draw on a drawing context.
  3015. * @param {number} [x=0] - Horizontal position of the beginning of the text.
  3016. * @param {number} [y=0] - Vertical position of the *baseline* of the text.
  3017. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
  3018. * @param {Object=} options - xScale, yScale to stretch the glyph.
  3019. * @param {opentype.Font} if hinting is to be used, the font
  3020. * @return {opentype.Path}
  3021. */
  3022. Glyph.prototype.getPath = function(x, y, fontSize, options, font) {
  3023. x = x !== undefined ? x : 0;
  3024. y = y !== undefined ? y : 0;
  3025. fontSize = fontSize !== undefined ? fontSize : 72;
  3026. var commands;
  3027. var hPoints;
  3028. if (!options) { options = { }; }
  3029. var xScale = options.xScale;
  3030. var yScale = options.yScale;
  3031. if (options.hinting && font && font.hinting) {
  3032. // in case of hinting, the hinting engine takes care
  3033. // of scaling the points (not the path) before hinting.
  3034. hPoints = this.path && font.hinting.exec(this, fontSize);
  3035. // in case the hinting engine failed hPoints is undefined
  3036. // and thus reverts to plain rending
  3037. }
  3038. if (hPoints) {
  3039. // Call font.hinting.getCommands instead of `glyf.getPath(hPoints).commands` to avoid a circular dependency
  3040. commands = font.hinting.getCommands(hPoints);
  3041. x = Math.round(x);
  3042. y = Math.round(y);
  3043. // TODO in case of hinting xyScaling is not yet supported
  3044. xScale = yScale = 1;
  3045. } else {
  3046. commands = this.path.commands;
  3047. var scale = 1 / (this.path.unitsPerEm || 1000) * fontSize;
  3048. if (xScale === undefined) { xScale = scale; }
  3049. if (yScale === undefined) { yScale = scale; }
  3050. }
  3051. var p = new Path();
  3052. for (var i = 0; i < commands.length; i += 1) {
  3053. var cmd = commands[i];
  3054. if (cmd.type === 'M') {
  3055. p.moveTo(x + (cmd.x * xScale), y + (-cmd.y * yScale));
  3056. } else if (cmd.type === 'L') {
  3057. p.lineTo(x + (cmd.x * xScale), y + (-cmd.y * yScale));
  3058. } else if (cmd.type === 'Q') {
  3059. p.quadraticCurveTo(x + (cmd.x1 * xScale), y + (-cmd.y1 * yScale),
  3060. x + (cmd.x * xScale), y + (-cmd.y * yScale));
  3061. } else if (cmd.type === 'C') {
  3062. p.curveTo(x + (cmd.x1 * xScale), y + (-cmd.y1 * yScale),
  3063. x + (cmd.x2 * xScale), y + (-cmd.y2 * yScale),
  3064. x + (cmd.x * xScale), y + (-cmd.y * yScale));
  3065. } else if (cmd.type === 'Z') {
  3066. p.closePath();
  3067. }
  3068. }
  3069. return p;
  3070. };
  3071. /**
  3072. * Split the glyph into contours.
  3073. * This function is here for backwards compatibility, and to
  3074. * provide raw access to the TrueType glyph outlines.
  3075. * @return {Array}
  3076. */
  3077. Glyph.prototype.getContours = function() {
  3078. if (this.points === undefined) {
  3079. return [];
  3080. }
  3081. var contours = [];
  3082. var currentContour = [];
  3083. for (var i = 0; i < this.points.length; i += 1) {
  3084. var pt = this.points[i];
  3085. currentContour.push(pt);
  3086. if (pt.lastPointOfContour) {
  3087. contours.push(currentContour);
  3088. currentContour = [];
  3089. }
  3090. }
  3091. check.argument(currentContour.length === 0, 'There are still points left in the current contour.');
  3092. return contours;
  3093. };
  3094. /**
  3095. * Calculate the xMin/yMin/xMax/yMax/lsb/rsb for a Glyph.
  3096. * @return {Object}
  3097. */
  3098. Glyph.prototype.getMetrics = function() {
  3099. var commands = this.path.commands;
  3100. var xCoords = [];
  3101. var yCoords = [];
  3102. for (var i = 0; i < commands.length; i += 1) {
  3103. var cmd = commands[i];
  3104. if (cmd.type !== 'Z') {
  3105. xCoords.push(cmd.x);
  3106. yCoords.push(cmd.y);
  3107. }
  3108. if (cmd.type === 'Q' || cmd.type === 'C') {
  3109. xCoords.push(cmd.x1);
  3110. yCoords.push(cmd.y1);
  3111. }
  3112. if (cmd.type === 'C') {
  3113. xCoords.push(cmd.x2);
  3114. yCoords.push(cmd.y2);
  3115. }
  3116. }
  3117. var metrics = {
  3118. xMin: Math.min.apply(null, xCoords),
  3119. yMin: Math.min.apply(null, yCoords),
  3120. xMax: Math.max.apply(null, xCoords),
  3121. yMax: Math.max.apply(null, yCoords),
  3122. leftSideBearing: this.leftSideBearing
  3123. };
  3124. if (!isFinite(metrics.xMin)) {
  3125. metrics.xMin = 0;
  3126. }
  3127. if (!isFinite(metrics.xMax)) {
  3128. metrics.xMax = this.advanceWidth;
  3129. }
  3130. if (!isFinite(metrics.yMin)) {
  3131. metrics.yMin = 0;
  3132. }
  3133. if (!isFinite(metrics.yMax)) {
  3134. metrics.yMax = 0;
  3135. }
  3136. metrics.rightSideBearing = this.advanceWidth - metrics.leftSideBearing - (metrics.xMax - metrics.xMin);
  3137. return metrics;
  3138. };
  3139. /**
  3140. * Draw the glyph on the given context.
  3141. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas.
  3142. * @param {number} [x=0] - Horizontal position of the beginning of the text.
  3143. * @param {number} [y=0] - Vertical position of the *baseline* of the text.
  3144. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
  3145. * @param {Object=} options - xScale, yScale to stretch the glyph.
  3146. */
  3147. Glyph.prototype.draw = function(ctx, x, y, fontSize, options) {
  3148. this.getPath(x, y, fontSize, options).draw(ctx);
  3149. };
  3150. /**
  3151. * Draw the points of the glyph.
  3152. * On-curve points will be drawn in blue, off-curve points will be drawn in red.
  3153. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas.
  3154. * @param {number} [x=0] - Horizontal position of the beginning of the text.
  3155. * @param {number} [y=0] - Vertical position of the *baseline* of the text.
  3156. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
  3157. */
  3158. Glyph.prototype.drawPoints = function(ctx, x, y, fontSize) {
  3159. function drawCircles(l, x, y, scale) {
  3160. ctx.beginPath();
  3161. for (var j = 0; j < l.length; j += 1) {
  3162. ctx.moveTo(x + (l[j].x * scale), y + (l[j].y * scale));
  3163. ctx.arc(x + (l[j].x * scale), y + (l[j].y * scale), 2, 0, Math.PI * 2, false);
  3164. }
  3165. ctx.closePath();
  3166. ctx.fill();
  3167. }
  3168. x = x !== undefined ? x : 0;
  3169. y = y !== undefined ? y : 0;
  3170. fontSize = fontSize !== undefined ? fontSize : 24;
  3171. var scale = 1 / this.path.unitsPerEm * fontSize;
  3172. var blueCircles = [];
  3173. var redCircles = [];
  3174. var path = this.path;
  3175. for (var i = 0; i < path.commands.length; i += 1) {
  3176. var cmd = path.commands[i];
  3177. if (cmd.x !== undefined) {
  3178. blueCircles.push({x: cmd.x, y: -cmd.y});
  3179. }
  3180. if (cmd.x1 !== undefined) {
  3181. redCircles.push({x: cmd.x1, y: -cmd.y1});
  3182. }
  3183. if (cmd.x2 !== undefined) {
  3184. redCircles.push({x: cmd.x2, y: -cmd.y2});
  3185. }
  3186. }
  3187. ctx.fillStyle = 'blue';
  3188. drawCircles(blueCircles, x, y, scale);
  3189. ctx.fillStyle = 'red';
  3190. drawCircles(redCircles, x, y, scale);
  3191. };
  3192. /**
  3193. * Draw lines indicating important font measurements.
  3194. * Black lines indicate the origin of the coordinate system (point 0,0).
  3195. * Blue lines indicate the glyph bounding box.
  3196. * Green line indicates the advance width of the glyph.
  3197. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas.
  3198. * @param {number} [x=0] - Horizontal position of the beginning of the text.
  3199. * @param {number} [y=0] - Vertical position of the *baseline* of the text.
  3200. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
  3201. */
  3202. Glyph.prototype.drawMetrics = function(ctx, x, y, fontSize) {
  3203. var scale;
  3204. x = x !== undefined ? x : 0;
  3205. y = y !== undefined ? y : 0;
  3206. fontSize = fontSize !== undefined ? fontSize : 24;
  3207. scale = 1 / this.path.unitsPerEm * fontSize;
  3208. ctx.lineWidth = 1;
  3209. // Draw the origin
  3210. ctx.strokeStyle = 'black';
  3211. draw.line(ctx, x, -10000, x, 10000);
  3212. draw.line(ctx, -10000, y, 10000, y);
  3213. // This code is here due to memory optimization: by not using
  3214. // defaults in the constructor, we save a notable amount of memory.
  3215. var xMin = this.xMin || 0;
  3216. var yMin = this.yMin || 0;
  3217. var xMax = this.xMax || 0;
  3218. var yMax = this.yMax || 0;
  3219. var advanceWidth = this.advanceWidth || 0;
  3220. // Draw the glyph box
  3221. ctx.strokeStyle = 'blue';
  3222. draw.line(ctx, x + (xMin * scale), -10000, x + (xMin * scale), 10000);
  3223. draw.line(ctx, x + (xMax * scale), -10000, x + (xMax * scale), 10000);
  3224. draw.line(ctx, -10000, y + (-yMin * scale), 10000, y + (-yMin * scale));
  3225. draw.line(ctx, -10000, y + (-yMax * scale), 10000, y + (-yMax * scale));
  3226. // Draw the advance width
  3227. ctx.strokeStyle = 'green';
  3228. draw.line(ctx, x + (advanceWidth * scale), -10000, x + (advanceWidth * scale), 10000);
  3229. };
  3230. // The GlyphSet object
  3231. // Define a property on the glyph that depends on the path being loaded.
  3232. function defineDependentProperty(glyph, externalName, internalName) {
  3233. Object.defineProperty(glyph, externalName, {
  3234. get: function() {
  3235. // Request the path property to make sure the path is loaded.
  3236. glyph.path; // jshint ignore:line
  3237. return glyph[internalName];
  3238. },
  3239. set: function(newValue) {
  3240. glyph[internalName] = newValue;
  3241. },
  3242. enumerable: true,
  3243. configurable: true
  3244. });
  3245. }
  3246. /**
  3247. * A GlyphSet represents all glyphs available in the font, but modelled using
  3248. * a deferred glyph loader, for retrieving glyphs only once they are absolutely
  3249. * necessary, to keep the memory footprint down.
  3250. * @exports opentype.GlyphSet
  3251. * @class
  3252. * @param {opentype.Font}
  3253. * @param {Array}
  3254. */
  3255. function GlyphSet(font, glyphs) {
  3256. this.font = font;
  3257. this.glyphs = {};
  3258. if (Array.isArray(glyphs)) {
  3259. for (var i = 0; i < glyphs.length; i++) {
  3260. var glyph = glyphs[i];
  3261. glyph.path.unitsPerEm = font.unitsPerEm;
  3262. this.glyphs[i] = glyph;
  3263. }
  3264. }
  3265. this.length = (glyphs && glyphs.length) || 0;
  3266. }
  3267. /**
  3268. * @param {number} index
  3269. * @return {opentype.Glyph}
  3270. */
  3271. GlyphSet.prototype.get = function(index) {
  3272. // this.glyphs[index] is 'undefined' when low memory mode is on. glyph is pushed on request only.
  3273. if (this.glyphs[index] === undefined) {
  3274. this.font._push(index);
  3275. if (typeof this.glyphs[index] === 'function') {
  3276. this.glyphs[index] = this.glyphs[index]();
  3277. }
  3278. var glyph = this.glyphs[index];
  3279. var unicodeObj = this.font._IndexToUnicodeMap[index];
  3280. if (unicodeObj) {
  3281. for (var j = 0; j < unicodeObj.unicodes.length; j++)
  3282. { glyph.addUnicode(unicodeObj.unicodes[j]); }
  3283. }
  3284. if (this.font.cffEncoding) {
  3285. if (this.font.isCIDFont) {
  3286. glyph.name = 'gid' + index;
  3287. } else {
  3288. glyph.name = this.font.cffEncoding.charset[index];
  3289. }
  3290. } else if (this.font.glyphNames.names) {
  3291. glyph.name = this.font.glyphNames.glyphIndexToName(index);
  3292. }
  3293. this.glyphs[index].advanceWidth = this.font._hmtxTableData[index].advanceWidth;
  3294. this.glyphs[index].leftSideBearing = this.font._hmtxTableData[index].leftSideBearing;
  3295. } else {
  3296. if (typeof this.glyphs[index] === 'function') {
  3297. this.glyphs[index] = this.glyphs[index]();
  3298. }
  3299. }
  3300. return this.glyphs[index];
  3301. };
  3302. /**
  3303. * @param {number} index
  3304. * @param {Object}
  3305. */
  3306. GlyphSet.prototype.push = function(index, loader) {
  3307. this.glyphs[index] = loader;
  3308. this.length++;
  3309. };
  3310. /**
  3311. * @alias opentype.glyphLoader
  3312. * @param {opentype.Font} font
  3313. * @param {number} index
  3314. * @return {opentype.Glyph}
  3315. */
  3316. function glyphLoader(font, index) {
  3317. return new Glyph({index: index, font: font});
  3318. }
  3319. /**
  3320. * Generate a stub glyph that can be filled with all metadata *except*
  3321. * the "points" and "path" properties, which must be loaded only once
  3322. * the glyph's path is actually requested for text shaping.
  3323. * @alias opentype.ttfGlyphLoader
  3324. * @param {opentype.Font} font
  3325. * @param {number} index
  3326. * @param {Function} parseGlyph
  3327. * @param {Object} data
  3328. * @param {number} position
  3329. * @param {Function} buildPath
  3330. * @return {opentype.Glyph}
  3331. */
  3332. function ttfGlyphLoader(font, index, parseGlyph, data, position, buildPath) {
  3333. return function() {
  3334. var glyph = new Glyph({index: index, font: font});
  3335. glyph.path = function() {
  3336. parseGlyph(glyph, data, position);
  3337. var path = buildPath(font.glyphs, glyph);
  3338. path.unitsPerEm = font.unitsPerEm;
  3339. return path;
  3340. };
  3341. defineDependentProperty(glyph, 'xMin', '_xMin');
  3342. defineDependentProperty(glyph, 'xMax', '_xMax');
  3343. defineDependentProperty(glyph, 'yMin', '_yMin');
  3344. defineDependentProperty(glyph, 'yMax', '_yMax');
  3345. return glyph;
  3346. };
  3347. }
  3348. /**
  3349. * @alias opentype.cffGlyphLoader
  3350. * @param {opentype.Font} font
  3351. * @param {number} index
  3352. * @param {Function} parseCFFCharstring
  3353. * @param {string} charstring
  3354. * @return {opentype.Glyph}
  3355. */
  3356. function cffGlyphLoader(font, index, parseCFFCharstring, charstring) {
  3357. return function() {
  3358. var glyph = new Glyph({index: index, font: font});
  3359. glyph.path = function() {
  3360. var path = parseCFFCharstring(font, glyph, charstring);
  3361. path.unitsPerEm = font.unitsPerEm;
  3362. return path;
  3363. };
  3364. return glyph;
  3365. };
  3366. }
  3367. var glyphset = { GlyphSet: GlyphSet, glyphLoader: glyphLoader, ttfGlyphLoader: ttfGlyphLoader, cffGlyphLoader: cffGlyphLoader };
  3368. // The `CFF` table contains the glyph outlines in PostScript format.
  3369. // Custom equals function that can also check lists.
  3370. function equals(a, b) {
  3371. if (a === b) {
  3372. return true;
  3373. } else if (Array.isArray(a) && Array.isArray(b)) {
  3374. if (a.length !== b.length) {
  3375. return false;
  3376. }
  3377. for (var i = 0; i < a.length; i += 1) {
  3378. if (!equals(a[i], b[i])) {
  3379. return false;
  3380. }
  3381. }
  3382. return true;
  3383. } else {
  3384. return false;
  3385. }
  3386. }
  3387. // Subroutines are encoded using the negative half of the number space.
  3388. // See type 2 chapter 4.7 "Subroutine operators".
  3389. function calcCFFSubroutineBias(subrs) {
  3390. var bias;
  3391. if (subrs.length < 1240) {
  3392. bias = 107;
  3393. } else if (subrs.length < 33900) {
  3394. bias = 1131;
  3395. } else {
  3396. bias = 32768;
  3397. }
  3398. return bias;
  3399. }
  3400. // Parse a `CFF` INDEX array.
  3401. // An index array consists of a list of offsets, then a list of objects at those offsets.
  3402. function parseCFFIndex(data, start, conversionFn) {
  3403. var offsets = [];
  3404. var objects = [];
  3405. var count = parse.getCard16(data, start);
  3406. var objectOffset;
  3407. var endOffset;
  3408. if (count !== 0) {
  3409. var offsetSize = parse.getByte(data, start + 2);
  3410. objectOffset = start + ((count + 1) * offsetSize) + 2;
  3411. var pos = start + 3;
  3412. for (var i = 0; i < count + 1; i += 1) {
  3413. offsets.push(parse.getOffset(data, pos, offsetSize));
  3414. pos += offsetSize;
  3415. }
  3416. // The total size of the index array is 4 header bytes + the value of the last offset.
  3417. endOffset = objectOffset + offsets[count];
  3418. } else {
  3419. endOffset = start + 2;
  3420. }
  3421. for (var i$1 = 0; i$1 < offsets.length - 1; i$1 += 1) {
  3422. var value = parse.getBytes(data, objectOffset + offsets[i$1], objectOffset + offsets[i$1 + 1]);
  3423. if (conversionFn) {
  3424. value = conversionFn(value);
  3425. }
  3426. objects.push(value);
  3427. }
  3428. return {objects: objects, startOffset: start, endOffset: endOffset};
  3429. }
  3430. function parseCFFIndexLowMemory(data, start) {
  3431. var offsets = [];
  3432. var count = parse.getCard16(data, start);
  3433. var objectOffset;
  3434. var endOffset;
  3435. if (count !== 0) {
  3436. var offsetSize = parse.getByte(data, start + 2);
  3437. objectOffset = start + ((count + 1) * offsetSize) + 2;
  3438. var pos = start + 3;
  3439. for (var i = 0; i < count + 1; i += 1) {
  3440. offsets.push(parse.getOffset(data, pos, offsetSize));
  3441. pos += offsetSize;
  3442. }
  3443. // The total size of the index array is 4 header bytes + the value of the last offset.
  3444. endOffset = objectOffset + offsets[count];
  3445. } else {
  3446. endOffset = start + 2;
  3447. }
  3448. return {offsets: offsets, startOffset: start, endOffset: endOffset};
  3449. }
  3450. function getCffIndexObject(i, offsets, data, start, conversionFn) {
  3451. var count = parse.getCard16(data, start);
  3452. var objectOffset = 0;
  3453. if (count !== 0) {
  3454. var offsetSize = parse.getByte(data, start + 2);
  3455. objectOffset = start + ((count + 1) * offsetSize) + 2;
  3456. }
  3457. var value = parse.getBytes(data, objectOffset + offsets[i], objectOffset + offsets[i + 1]);
  3458. if (conversionFn) {
  3459. value = conversionFn(value);
  3460. }
  3461. return value;
  3462. }
  3463. // Parse a `CFF` DICT real value.
  3464. function parseFloatOperand(parser) {
  3465. var s = '';
  3466. var eof = 15;
  3467. var lookup = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', 'E', 'E-', null, '-'];
  3468. while (true) {
  3469. var b = parser.parseByte();
  3470. var n1 = b >> 4;
  3471. var n2 = b & 15;
  3472. if (n1 === eof) {
  3473. break;
  3474. }
  3475. s += lookup[n1];
  3476. if (n2 === eof) {
  3477. break;
  3478. }
  3479. s += lookup[n2];
  3480. }
  3481. return parseFloat(s);
  3482. }
  3483. // Parse a `CFF` DICT operand.
  3484. function parseOperand(parser, b0) {
  3485. var b1;
  3486. var b2;
  3487. var b3;
  3488. var b4;
  3489. if (b0 === 28) {
  3490. b1 = parser.parseByte();
  3491. b2 = parser.parseByte();
  3492. return b1 << 8 | b2;
  3493. }
  3494. if (b0 === 29) {
  3495. b1 = parser.parseByte();
  3496. b2 = parser.parseByte();
  3497. b3 = parser.parseByte();
  3498. b4 = parser.parseByte();
  3499. return b1 << 24 | b2 << 16 | b3 << 8 | b4;
  3500. }
  3501. if (b0 === 30) {
  3502. return parseFloatOperand(parser);
  3503. }
  3504. if (b0 >= 32 && b0 <= 246) {
  3505. return b0 - 139;
  3506. }
  3507. if (b0 >= 247 && b0 <= 250) {
  3508. b1 = parser.parseByte();
  3509. return (b0 - 247) * 256 + b1 + 108;
  3510. }
  3511. if (b0 >= 251 && b0 <= 254) {
  3512. b1 = parser.parseByte();
  3513. return -(b0 - 251) * 256 - b1 - 108;
  3514. }
  3515. throw new Error('Invalid b0 ' + b0);
  3516. }
  3517. // Convert the entries returned by `parseDict` to a proper dictionary.
  3518. // If a value is a list of one, it is unpacked.
  3519. function entriesToObject(entries) {
  3520. var o = {};
  3521. for (var i = 0; i < entries.length; i += 1) {
  3522. var key = entries[i][0];
  3523. var values = entries[i][1];
  3524. var value = (void 0);
  3525. if (values.length === 1) {
  3526. value = values[0];
  3527. } else {
  3528. value = values;
  3529. }
  3530. if (o.hasOwnProperty(key) && !isNaN(o[key])) {
  3531. throw new Error('Object ' + o + ' already has key ' + key);
  3532. }
  3533. o[key] = value;
  3534. }
  3535. return o;
  3536. }
  3537. // Parse a `CFF` DICT object.
  3538. // A dictionary contains key-value pairs in a compact tokenized format.
  3539. function parseCFFDict(data, start, size) {
  3540. start = start !== undefined ? start : 0;
  3541. var parser = new parse.Parser(data, start);
  3542. var entries = [];
  3543. var operands = [];
  3544. size = size !== undefined ? size : data.length;
  3545. while (parser.relativeOffset < size) {
  3546. var op = parser.parseByte();
  3547. // The first byte for each dict item distinguishes between operator (key) and operand (value).
  3548. // Values <= 21 are operators.
  3549. if (op <= 21) {
  3550. // Two-byte operators have an initial escape byte of 12.
  3551. if (op === 12) {
  3552. op = 1200 + parser.parseByte();
  3553. }
  3554. entries.push([op, operands]);
  3555. operands = [];
  3556. } else {
  3557. // Since the operands (values) come before the operators (keys), we store all operands in a list
  3558. // until we encounter an operator.
  3559. operands.push(parseOperand(parser, op));
  3560. }
  3561. }
  3562. return entriesToObject(entries);
  3563. }
  3564. // Given a String Index (SID), return the value of the string.
  3565. // Strings below index 392 are standard CFF strings and are not encoded in the font.
  3566. function getCFFString(strings, index) {
  3567. if (index <= 390) {
  3568. index = cffStandardStrings[index];
  3569. } else {
  3570. index = strings[index - 391];
  3571. }
  3572. return index;
  3573. }
  3574. // Interpret a dictionary and return a new dictionary with readable keys and values for missing entries.
  3575. // This function takes `meta` which is a list of objects containing `operand`, `name` and `default`.
  3576. function interpretDict(dict, meta, strings) {
  3577. var newDict = {};
  3578. var value;
  3579. // Because we also want to include missing values, we start out from the meta list
  3580. // and lookup values in the dict.
  3581. for (var i = 0; i < meta.length; i += 1) {
  3582. var m = meta[i];
  3583. if (Array.isArray(m.type)) {
  3584. var values = [];
  3585. values.length = m.type.length;
  3586. for (var j = 0; j < m.type.length; j++) {
  3587. value = dict[m.op] !== undefined ? dict[m.op][j] : undefined;
  3588. if (value === undefined) {
  3589. value = m.value !== undefined && m.value[j] !== undefined ? m.value[j] : null;
  3590. }
  3591. if (m.type[j] === 'SID') {
  3592. value = getCFFString(strings, value);
  3593. }
  3594. values[j] = value;
  3595. }
  3596. newDict[m.name] = values;
  3597. } else {
  3598. value = dict[m.op];
  3599. if (value === undefined) {
  3600. value = m.value !== undefined ? m.value : null;
  3601. }
  3602. if (m.type === 'SID') {
  3603. value = getCFFString(strings, value);
  3604. }
  3605. newDict[m.name] = value;
  3606. }
  3607. }
  3608. return newDict;
  3609. }
  3610. // Parse the CFF header.
  3611. function parseCFFHeader(data, start) {
  3612. var header = {};
  3613. header.formatMajor = parse.getCard8(data, start);
  3614. header.formatMinor = parse.getCard8(data, start + 1);
  3615. header.size = parse.getCard8(data, start + 2);
  3616. header.offsetSize = parse.getCard8(data, start + 3);
  3617. header.startOffset = start;
  3618. header.endOffset = start + 4;
  3619. return header;
  3620. }
  3621. var TOP_DICT_META = [
  3622. {name: 'version', op: 0, type: 'SID'},
  3623. {name: 'notice', op: 1, type: 'SID'},
  3624. {name: 'copyright', op: 1200, type: 'SID'},
  3625. {name: 'fullName', op: 2, type: 'SID'},
  3626. {name: 'familyName', op: 3, type: 'SID'},
  3627. {name: 'weight', op: 4, type: 'SID'},
  3628. {name: 'isFixedPitch', op: 1201, type: 'number', value: 0},
  3629. {name: 'italicAngle', op: 1202, type: 'number', value: 0},
  3630. {name: 'underlinePosition', op: 1203, type: 'number', value: -100},
  3631. {name: 'underlineThickness', op: 1204, type: 'number', value: 50},
  3632. {name: 'paintType', op: 1205, type: 'number', value: 0},
  3633. {name: 'charstringType', op: 1206, type: 'number', value: 2},
  3634. {
  3635. name: 'fontMatrix',
  3636. op: 1207,
  3637. type: ['real', 'real', 'real', 'real', 'real', 'real'],
  3638. value: [0.001, 0, 0, 0.001, 0, 0]
  3639. },
  3640. {name: 'uniqueId', op: 13, type: 'number'},
  3641. {name: 'fontBBox', op: 5, type: ['number', 'number', 'number', 'number'], value: [0, 0, 0, 0]},
  3642. {name: 'strokeWidth', op: 1208, type: 'number', value: 0},
  3643. {name: 'xuid', op: 14, type: [], value: null},
  3644. {name: 'charset', op: 15, type: 'offset', value: 0},
  3645. {name: 'encoding', op: 16, type: 'offset', value: 0},
  3646. {name: 'charStrings', op: 17, type: 'offset', value: 0},
  3647. {name: 'private', op: 18, type: ['number', 'offset'], value: [0, 0]},
  3648. {name: 'ros', op: 1230, type: ['SID', 'SID', 'number']},
  3649. {name: 'cidFontVersion', op: 1231, type: 'number', value: 0},
  3650. {name: 'cidFontRevision', op: 1232, type: 'number', value: 0},
  3651. {name: 'cidFontType', op: 1233, type: 'number', value: 0},
  3652. {name: 'cidCount', op: 1234, type: 'number', value: 8720},
  3653. {name: 'uidBase', op: 1235, type: 'number'},
  3654. {name: 'fdArray', op: 1236, type: 'offset'},
  3655. {name: 'fdSelect', op: 1237, type: 'offset'},
  3656. {name: 'fontName', op: 1238, type: 'SID'}
  3657. ];
  3658. var PRIVATE_DICT_META = [
  3659. {name: 'subrs', op: 19, type: 'offset', value: 0},
  3660. {name: 'defaultWidthX', op: 20, type: 'number', value: 0},
  3661. {name: 'nominalWidthX', op: 21, type: 'number', value: 0}
  3662. ];
  3663. // Parse the CFF top dictionary. A CFF table can contain multiple fonts, each with their own top dictionary.
  3664. // The top dictionary contains the essential metadata for the font, together with the private dictionary.
  3665. function parseCFFTopDict(data, strings) {
  3666. var dict = parseCFFDict(data, 0, data.byteLength);
  3667. return interpretDict(dict, TOP_DICT_META, strings);
  3668. }
  3669. // Parse the CFF private dictionary. We don't fully parse out all the values, only the ones we need.
  3670. function parseCFFPrivateDict(data, start, size, strings) {
  3671. var dict = parseCFFDict(data, start, size);
  3672. return interpretDict(dict, PRIVATE_DICT_META, strings);
  3673. }
  3674. // Returns a list of "Top DICT"s found using an INDEX list.
  3675. // Used to read both the usual high-level Top DICTs and also the FDArray
  3676. // discovered inside CID-keyed fonts. When a Top DICT has a reference to
  3677. // a Private DICT that is read and saved into the Top DICT.
  3678. //
  3679. // In addition to the expected/optional values as outlined in TOP_DICT_META
  3680. // the following values might be saved into the Top DICT.
  3681. //
  3682. // _subrs [] array of local CFF subroutines from Private DICT
  3683. // _subrsBias bias value computed from number of subroutines
  3684. // (see calcCFFSubroutineBias() and parseCFFCharstring())
  3685. // _defaultWidthX default widths for CFF characters
  3686. // _nominalWidthX bias added to width embedded within glyph description
  3687. //
  3688. // _privateDict saved copy of parsed Private DICT from Top DICT
  3689. function gatherCFFTopDicts(data, start, cffIndex, strings) {
  3690. var topDictArray = [];
  3691. for (var iTopDict = 0; iTopDict < cffIndex.length; iTopDict += 1) {
  3692. var topDictData = new DataView(new Uint8Array(cffIndex[iTopDict]).buffer);
  3693. var topDict = parseCFFTopDict(topDictData, strings);
  3694. topDict._subrs = [];
  3695. topDict._subrsBias = 0;
  3696. topDict._defaultWidthX = 0;
  3697. topDict._nominalWidthX = 0;
  3698. var privateSize = topDict.private[0];
  3699. var privateOffset = topDict.private[1];
  3700. if (privateSize !== 0 && privateOffset !== 0) {
  3701. var privateDict = parseCFFPrivateDict(data, privateOffset + start, privateSize, strings);
  3702. topDict._defaultWidthX = privateDict.defaultWidthX;
  3703. topDict._nominalWidthX = privateDict.nominalWidthX;
  3704. if (privateDict.subrs !== 0) {
  3705. var subrOffset = privateOffset + privateDict.subrs;
  3706. var subrIndex = parseCFFIndex(data, subrOffset + start);
  3707. topDict._subrs = subrIndex.objects;
  3708. topDict._subrsBias = calcCFFSubroutineBias(topDict._subrs);
  3709. }
  3710. topDict._privateDict = privateDict;
  3711. }
  3712. topDictArray.push(topDict);
  3713. }
  3714. return topDictArray;
  3715. }
  3716. // Parse the CFF charset table, which contains internal names for all the glyphs.
  3717. // This function will return a list of glyph names.
  3718. // See Adobe TN #5176 chapter 13, "Charsets".
  3719. function parseCFFCharset(data, start, nGlyphs, strings) {
  3720. var sid;
  3721. var count;
  3722. var parser = new parse.Parser(data, start);
  3723. // The .notdef glyph is not included, so subtract 1.
  3724. nGlyphs -= 1;
  3725. var charset = ['.notdef'];
  3726. var format = parser.parseCard8();
  3727. if (format === 0) {
  3728. for (var i = 0; i < nGlyphs; i += 1) {
  3729. sid = parser.parseSID();
  3730. charset.push(getCFFString(strings, sid));
  3731. }
  3732. } else if (format === 1) {
  3733. while (charset.length <= nGlyphs) {
  3734. sid = parser.parseSID();
  3735. count = parser.parseCard8();
  3736. for (var i$1 = 0; i$1 <= count; i$1 += 1) {
  3737. charset.push(getCFFString(strings, sid));
  3738. sid += 1;
  3739. }
  3740. }
  3741. } else if (format === 2) {
  3742. while (charset.length <= nGlyphs) {
  3743. sid = parser.parseSID();
  3744. count = parser.parseCard16();
  3745. for (var i$2 = 0; i$2 <= count; i$2 += 1) {
  3746. charset.push(getCFFString(strings, sid));
  3747. sid += 1;
  3748. }
  3749. }
  3750. } else {
  3751. throw new Error('Unknown charset format ' + format);
  3752. }
  3753. return charset;
  3754. }
  3755. // Parse the CFF encoding data. Only one encoding can be specified per font.
  3756. // See Adobe TN #5176 chapter 12, "Encodings".
  3757. function parseCFFEncoding(data, start, charset) {
  3758. var code;
  3759. var enc = {};
  3760. var parser = new parse.Parser(data, start);
  3761. var format = parser.parseCard8();
  3762. if (format === 0) {
  3763. var nCodes = parser.parseCard8();
  3764. for (var i = 0; i < nCodes; i += 1) {
  3765. code = parser.parseCard8();
  3766. enc[code] = i;
  3767. }
  3768. } else if (format === 1) {
  3769. var nRanges = parser.parseCard8();
  3770. code = 1;
  3771. for (var i$1 = 0; i$1 < nRanges; i$1 += 1) {
  3772. var first = parser.parseCard8();
  3773. var nLeft = parser.parseCard8();
  3774. for (var j = first; j <= first + nLeft; j += 1) {
  3775. enc[j] = code;
  3776. code += 1;
  3777. }
  3778. }
  3779. } else {
  3780. throw new Error('Unknown encoding format ' + format);
  3781. }
  3782. return new CffEncoding(enc, charset);
  3783. }
  3784. // Take in charstring code and return a Glyph object.
  3785. // The encoding is described in the Type 2 Charstring Format
  3786. // https://www.microsoft.com/typography/OTSPEC/charstr2.htm
  3787. function parseCFFCharstring(font, glyph, code) {
  3788. var c1x;
  3789. var c1y;
  3790. var c2x;
  3791. var c2y;
  3792. var p = new Path();
  3793. var stack = [];
  3794. var nStems = 0;
  3795. var haveWidth = false;
  3796. var open = false;
  3797. var x = 0;
  3798. var y = 0;
  3799. var subrs;
  3800. var subrsBias;
  3801. var defaultWidthX;
  3802. var nominalWidthX;
  3803. if (font.isCIDFont) {
  3804. var fdIndex = font.tables.cff.topDict._fdSelect[glyph.index];
  3805. var fdDict = font.tables.cff.topDict._fdArray[fdIndex];
  3806. subrs = fdDict._subrs;
  3807. subrsBias = fdDict._subrsBias;
  3808. defaultWidthX = fdDict._defaultWidthX;
  3809. nominalWidthX = fdDict._nominalWidthX;
  3810. } else {
  3811. subrs = font.tables.cff.topDict._subrs;
  3812. subrsBias = font.tables.cff.topDict._subrsBias;
  3813. defaultWidthX = font.tables.cff.topDict._defaultWidthX;
  3814. nominalWidthX = font.tables.cff.topDict._nominalWidthX;
  3815. }
  3816. var width = defaultWidthX;
  3817. function newContour(x, y) {
  3818. if (open) {
  3819. p.closePath();
  3820. }
  3821. p.moveTo(x, y);
  3822. open = true;
  3823. }
  3824. function parseStems() {
  3825. var hasWidthArg;
  3826. // The number of stem operators on the stack is always even.
  3827. // If the value is uneven, that means a width is specified.
  3828. hasWidthArg = stack.length % 2 !== 0;
  3829. if (hasWidthArg && !haveWidth) {
  3830. width = stack.shift() + nominalWidthX;
  3831. }
  3832. nStems += stack.length >> 1;
  3833. stack.length = 0;
  3834. haveWidth = true;
  3835. }
  3836. function parse(code) {
  3837. var b1;
  3838. var b2;
  3839. var b3;
  3840. var b4;
  3841. var codeIndex;
  3842. var subrCode;
  3843. var jpx;
  3844. var jpy;
  3845. var c3x;
  3846. var c3y;
  3847. var c4x;
  3848. var c4y;
  3849. var i = 0;
  3850. while (i < code.length) {
  3851. var v = code[i];
  3852. i += 1;
  3853. switch (v) {
  3854. case 1: // hstem
  3855. parseStems();
  3856. break;
  3857. case 3: // vstem
  3858. parseStems();
  3859. break;
  3860. case 4: // vmoveto
  3861. if (stack.length > 1 && !haveWidth) {
  3862. width = stack.shift() + nominalWidthX;
  3863. haveWidth = true;
  3864. }
  3865. y += stack.pop();
  3866. newContour(x, y);
  3867. break;
  3868. case 5: // rlineto
  3869. while (stack.length > 0) {
  3870. x += stack.shift();
  3871. y += stack.shift();
  3872. p.lineTo(x, y);
  3873. }
  3874. break;
  3875. case 6: // hlineto
  3876. while (stack.length > 0) {
  3877. x += stack.shift();
  3878. p.lineTo(x, y);
  3879. if (stack.length === 0) {
  3880. break;
  3881. }
  3882. y += stack.shift();
  3883. p.lineTo(x, y);
  3884. }
  3885. break;
  3886. case 7: // vlineto
  3887. while (stack.length > 0) {
  3888. y += stack.shift();
  3889. p.lineTo(x, y);
  3890. if (stack.length === 0) {
  3891. break;
  3892. }
  3893. x += stack.shift();
  3894. p.lineTo(x, y);
  3895. }
  3896. break;
  3897. case 8: // rrcurveto
  3898. while (stack.length > 0) {
  3899. c1x = x + stack.shift();
  3900. c1y = y + stack.shift();
  3901. c2x = c1x + stack.shift();
  3902. c2y = c1y + stack.shift();
  3903. x = c2x + stack.shift();
  3904. y = c2y + stack.shift();
  3905. p.curveTo(c1x, c1y, c2x, c2y, x, y);
  3906. }
  3907. break;
  3908. case 10: // callsubr
  3909. codeIndex = stack.pop() + subrsBias;
  3910. subrCode = subrs[codeIndex];
  3911. if (subrCode) {
  3912. parse(subrCode);
  3913. }
  3914. break;
  3915. case 11: // return
  3916. return;
  3917. case 12: // flex operators
  3918. v = code[i];
  3919. i += 1;
  3920. switch (v) {
  3921. case 35: // flex
  3922. // |- dx1 dy1 dx2 dy2 dx3 dy3 dx4 dy4 dx5 dy5 dx6 dy6 fd flex (12 35) |-
  3923. c1x = x + stack.shift(); // dx1
  3924. c1y = y + stack.shift(); // dy1
  3925. c2x = c1x + stack.shift(); // dx2
  3926. c2y = c1y + stack.shift(); // dy2
  3927. jpx = c2x + stack.shift(); // dx3
  3928. jpy = c2y + stack.shift(); // dy3
  3929. c3x = jpx + stack.shift(); // dx4
  3930. c3y = jpy + stack.shift(); // dy4
  3931. c4x = c3x + stack.shift(); // dx5
  3932. c4y = c3y + stack.shift(); // dy5
  3933. x = c4x + stack.shift(); // dx6
  3934. y = c4y + stack.shift(); // dy6
  3935. stack.shift(); // flex depth
  3936. p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy);
  3937. p.curveTo(c3x, c3y, c4x, c4y, x, y);
  3938. break;
  3939. case 34: // hflex
  3940. // |- dx1 dx2 dy2 dx3 dx4 dx5 dx6 hflex (12 34) |-
  3941. c1x = x + stack.shift(); // dx1
  3942. c1y = y; // dy1
  3943. c2x = c1x + stack.shift(); // dx2
  3944. c2y = c1y + stack.shift(); // dy2
  3945. jpx = c2x + stack.shift(); // dx3
  3946. jpy = c2y; // dy3
  3947. c3x = jpx + stack.shift(); // dx4
  3948. c3y = c2y; // dy4
  3949. c4x = c3x + stack.shift(); // dx5
  3950. c4y = y; // dy5
  3951. x = c4x + stack.shift(); // dx6
  3952. p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy);
  3953. p.curveTo(c3x, c3y, c4x, c4y, x, y);
  3954. break;
  3955. case 36: // hflex1
  3956. // |- dx1 dy1 dx2 dy2 dx3 dx4 dx5 dy5 dx6 hflex1 (12 36) |-
  3957. c1x = x + stack.shift(); // dx1
  3958. c1y = y + stack.shift(); // dy1
  3959. c2x = c1x + stack.shift(); // dx2
  3960. c2y = c1y + stack.shift(); // dy2
  3961. jpx = c2x + stack.shift(); // dx3
  3962. jpy = c2y; // dy3
  3963. c3x = jpx + stack.shift(); // dx4
  3964. c3y = c2y; // dy4
  3965. c4x = c3x + stack.shift(); // dx5
  3966. c4y = c3y + stack.shift(); // dy5
  3967. x = c4x + stack.shift(); // dx6
  3968. p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy);
  3969. p.curveTo(c3x, c3y, c4x, c4y, x, y);
  3970. break;
  3971. case 37: // flex1
  3972. // |- dx1 dy1 dx2 dy2 dx3 dy3 dx4 dy4 dx5 dy5 d6 flex1 (12 37) |-
  3973. c1x = x + stack.shift(); // dx1
  3974. c1y = y + stack.shift(); // dy1
  3975. c2x = c1x + stack.shift(); // dx2
  3976. c2y = c1y + stack.shift(); // dy2
  3977. jpx = c2x + stack.shift(); // dx3
  3978. jpy = c2y + stack.shift(); // dy3
  3979. c3x = jpx + stack.shift(); // dx4
  3980. c3y = jpy + stack.shift(); // dy4
  3981. c4x = c3x + stack.shift(); // dx5
  3982. c4y = c3y + stack.shift(); // dy5
  3983. if (Math.abs(c4x - x) > Math.abs(c4y - y)) {
  3984. x = c4x + stack.shift();
  3985. } else {
  3986. y = c4y + stack.shift();
  3987. }
  3988. p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy);
  3989. p.curveTo(c3x, c3y, c4x, c4y, x, y);
  3990. break;
  3991. default:
  3992. console.log('Glyph ' + glyph.index + ': unknown operator ' + 1200 + v);
  3993. stack.length = 0;
  3994. }
  3995. break;
  3996. case 14: // endchar
  3997. if (stack.length > 0 && !haveWidth) {
  3998. width = stack.shift() + nominalWidthX;
  3999. haveWidth = true;
  4000. }
  4001. if (open) {
  4002. p.closePath();
  4003. open = false;
  4004. }
  4005. break;
  4006. case 18: // hstemhm
  4007. parseStems();
  4008. break;
  4009. case 19: // hintmask
  4010. case 20: // cntrmask
  4011. parseStems();
  4012. i += (nStems + 7) >> 3;
  4013. break;
  4014. case 21: // rmoveto
  4015. if (stack.length > 2 && !haveWidth) {
  4016. width = stack.shift() + nominalWidthX;
  4017. haveWidth = true;
  4018. }
  4019. y += stack.pop();
  4020. x += stack.pop();
  4021. newContour(x, y);
  4022. break;
  4023. case 22: // hmoveto
  4024. if (stack.length > 1 && !haveWidth) {
  4025. width = stack.shift() + nominalWidthX;
  4026. haveWidth = true;
  4027. }
  4028. x += stack.pop();
  4029. newContour(x, y);
  4030. break;
  4031. case 23: // vstemhm
  4032. parseStems();
  4033. break;
  4034. case 24: // rcurveline
  4035. while (stack.length > 2) {
  4036. c1x = x + stack.shift();
  4037. c1y = y + stack.shift();
  4038. c2x = c1x + stack.shift();
  4039. c2y = c1y + stack.shift();
  4040. x = c2x + stack.shift();
  4041. y = c2y + stack.shift();
  4042. p.curveTo(c1x, c1y, c2x, c2y, x, y);
  4043. }
  4044. x += stack.shift();
  4045. y += stack.shift();
  4046. p.lineTo(x, y);
  4047. break;
  4048. case 25: // rlinecurve
  4049. while (stack.length > 6) {
  4050. x += stack.shift();
  4051. y += stack.shift();
  4052. p.lineTo(x, y);
  4053. }
  4054. c1x = x + stack.shift();
  4055. c1y = y + stack.shift();
  4056. c2x = c1x + stack.shift();
  4057. c2y = c1y + stack.shift();
  4058. x = c2x + stack.shift();
  4059. y = c2y + stack.shift();
  4060. p.curveTo(c1x, c1y, c2x, c2y, x, y);
  4061. break;
  4062. case 26: // vvcurveto
  4063. if (stack.length % 2) {
  4064. x += stack.shift();
  4065. }
  4066. while (stack.length > 0) {
  4067. c1x = x;
  4068. c1y = y + stack.shift();
  4069. c2x = c1x + stack.shift();
  4070. c2y = c1y + stack.shift();
  4071. x = c2x;
  4072. y = c2y + stack.shift();
  4073. p.curveTo(c1x, c1y, c2x, c2y, x, y);
  4074. }
  4075. break;
  4076. case 27: // hhcurveto
  4077. if (stack.length % 2) {
  4078. y += stack.shift();
  4079. }
  4080. while (stack.length > 0) {
  4081. c1x = x + stack.shift();
  4082. c1y = y;
  4083. c2x = c1x + stack.shift();
  4084. c2y = c1y + stack.shift();
  4085. x = c2x + stack.shift();
  4086. y = c2y;
  4087. p.curveTo(c1x, c1y, c2x, c2y, x, y);
  4088. }
  4089. break;
  4090. case 28: // shortint
  4091. b1 = code[i];
  4092. b2 = code[i + 1];
  4093. stack.push(((b1 << 24) | (b2 << 16)) >> 16);
  4094. i += 2;
  4095. break;
  4096. case 29: // callgsubr
  4097. codeIndex = stack.pop() + font.gsubrsBias;
  4098. subrCode = font.gsubrs[codeIndex];
  4099. if (subrCode) {
  4100. parse(subrCode);
  4101. }
  4102. break;
  4103. case 30: // vhcurveto
  4104. while (stack.length > 0) {
  4105. c1x = x;
  4106. c1y = y + stack.shift();
  4107. c2x = c1x + stack.shift();
  4108. c2y = c1y + stack.shift();
  4109. x = c2x + stack.shift();
  4110. y = c2y + (stack.length === 1 ? stack.shift() : 0);
  4111. p.curveTo(c1x, c1y, c2x, c2y, x, y);
  4112. if (stack.length === 0) {
  4113. break;
  4114. }
  4115. c1x = x + stack.shift();
  4116. c1y = y;
  4117. c2x = c1x + stack.shift();
  4118. c2y = c1y + stack.shift();
  4119. y = c2y + stack.shift();
  4120. x = c2x + (stack.length === 1 ? stack.shift() : 0);
  4121. p.curveTo(c1x, c1y, c2x, c2y, x, y);
  4122. }
  4123. break;
  4124. case 31: // hvcurveto
  4125. while (stack.length > 0) {
  4126. c1x = x + stack.shift();
  4127. c1y = y;
  4128. c2x = c1x + stack.shift();
  4129. c2y = c1y + stack.shift();
  4130. y = c2y + stack.shift();
  4131. x = c2x + (stack.length === 1 ? stack.shift() : 0);
  4132. p.curveTo(c1x, c1y, c2x, c2y, x, y);
  4133. if (stack.length === 0) {
  4134. break;
  4135. }
  4136. c1x = x;
  4137. c1y = y + stack.shift();
  4138. c2x = c1x + stack.shift();
  4139. c2y = c1y + stack.shift();
  4140. x = c2x + stack.shift();
  4141. y = c2y + (stack.length === 1 ? stack.shift() : 0);
  4142. p.curveTo(c1x, c1y, c2x, c2y, x, y);
  4143. }
  4144. break;
  4145. default:
  4146. if (v < 32) {
  4147. console.log('Glyph ' + glyph.index + ': unknown operator ' + v);
  4148. } else if (v < 247) {
  4149. stack.push(v - 139);
  4150. } else if (v < 251) {
  4151. b1 = code[i];
  4152. i += 1;
  4153. stack.push((v - 247) * 256 + b1 + 108);
  4154. } else if (v < 255) {
  4155. b1 = code[i];
  4156. i += 1;
  4157. stack.push(-(v - 251) * 256 - b1 - 108);
  4158. } else {
  4159. b1 = code[i];
  4160. b2 = code[i + 1];
  4161. b3 = code[i + 2];
  4162. b4 = code[i + 3];
  4163. i += 4;
  4164. stack.push(((b1 << 24) | (b2 << 16) | (b3 << 8) | b4) / 65536);
  4165. }
  4166. }
  4167. }
  4168. }
  4169. parse(code);
  4170. glyph.advanceWidth = width;
  4171. return p;
  4172. }
  4173. function parseCFFFDSelect(data, start, nGlyphs, fdArrayCount) {
  4174. var fdSelect = [];
  4175. var fdIndex;
  4176. var parser = new parse.Parser(data, start);
  4177. var format = parser.parseCard8();
  4178. if (format === 0) {
  4179. // Simple list of nGlyphs elements
  4180. for (var iGid = 0; iGid < nGlyphs; iGid++) {
  4181. fdIndex = parser.parseCard8();
  4182. if (fdIndex >= fdArrayCount) {
  4183. throw new Error('CFF table CID Font FDSelect has bad FD index value ' + fdIndex + ' (FD count ' + fdArrayCount + ')');
  4184. }
  4185. fdSelect.push(fdIndex);
  4186. }
  4187. } else if (format === 3) {
  4188. // Ranges
  4189. var nRanges = parser.parseCard16();
  4190. var first = parser.parseCard16();
  4191. if (first !== 0) {
  4192. throw new Error('CFF Table CID Font FDSelect format 3 range has bad initial GID ' + first);
  4193. }
  4194. var next;
  4195. for (var iRange = 0; iRange < nRanges; iRange++) {
  4196. fdIndex = parser.parseCard8();
  4197. next = parser.parseCard16();
  4198. if (fdIndex >= fdArrayCount) {
  4199. throw new Error('CFF table CID Font FDSelect has bad FD index value ' + fdIndex + ' (FD count ' + fdArrayCount + ')');
  4200. }
  4201. if (next > nGlyphs) {
  4202. throw new Error('CFF Table CID Font FDSelect format 3 range has bad GID ' + next);
  4203. }
  4204. for (; first < next; first++) {
  4205. fdSelect.push(fdIndex);
  4206. }
  4207. first = next;
  4208. }
  4209. if (next !== nGlyphs) {
  4210. throw new Error('CFF Table CID Font FDSelect format 3 range has bad final GID ' + next);
  4211. }
  4212. } else {
  4213. throw new Error('CFF Table CID Font FDSelect table has unsupported format ' + format);
  4214. }
  4215. return fdSelect;
  4216. }
  4217. // Parse the `CFF` table, which contains the glyph outlines in PostScript format.
  4218. function parseCFFTable(data, start, font, opt) {
  4219. font.tables.cff = {};
  4220. var header = parseCFFHeader(data, start);
  4221. var nameIndex = parseCFFIndex(data, header.endOffset, parse.bytesToString);
  4222. var topDictIndex = parseCFFIndex(data, nameIndex.endOffset);
  4223. var stringIndex = parseCFFIndex(data, topDictIndex.endOffset, parse.bytesToString);
  4224. var globalSubrIndex = parseCFFIndex(data, stringIndex.endOffset);
  4225. font.gsubrs = globalSubrIndex.objects;
  4226. font.gsubrsBias = calcCFFSubroutineBias(font.gsubrs);
  4227. var topDictArray = gatherCFFTopDicts(data, start, topDictIndex.objects, stringIndex.objects);
  4228. if (topDictArray.length !== 1) {
  4229. throw new Error('CFF table has too many fonts in \'FontSet\' - count of fonts NameIndex.length = ' + topDictArray.length);
  4230. }
  4231. var topDict = topDictArray[0];
  4232. font.tables.cff.topDict = topDict;
  4233. if (topDict._privateDict) {
  4234. font.defaultWidthX = topDict._privateDict.defaultWidthX;
  4235. font.nominalWidthX = topDict._privateDict.nominalWidthX;
  4236. }
  4237. if (topDict.ros[0] !== undefined && topDict.ros[1] !== undefined) {
  4238. font.isCIDFont = true;
  4239. }
  4240. if (font.isCIDFont) {
  4241. var fdArrayOffset = topDict.fdArray;
  4242. var fdSelectOffset = topDict.fdSelect;
  4243. if (fdArrayOffset === 0 || fdSelectOffset === 0) {
  4244. throw new Error('Font is marked as a CID font, but FDArray and/or FDSelect information is missing');
  4245. }
  4246. fdArrayOffset += start;
  4247. var fdArrayIndex = parseCFFIndex(data, fdArrayOffset);
  4248. var fdArray = gatherCFFTopDicts(data, start, fdArrayIndex.objects, stringIndex.objects);
  4249. topDict._fdArray = fdArray;
  4250. fdSelectOffset += start;
  4251. topDict._fdSelect = parseCFFFDSelect(data, fdSelectOffset, font.numGlyphs, fdArray.length);
  4252. }
  4253. var privateDictOffset = start + topDict.private[1];
  4254. var privateDict = parseCFFPrivateDict(data, privateDictOffset, topDict.private[0], stringIndex.objects);
  4255. font.defaultWidthX = privateDict.defaultWidthX;
  4256. font.nominalWidthX = privateDict.nominalWidthX;
  4257. if (privateDict.subrs !== 0) {
  4258. var subrOffset = privateDictOffset + privateDict.subrs;
  4259. var subrIndex = parseCFFIndex(data, subrOffset);
  4260. font.subrs = subrIndex.objects;
  4261. font.subrsBias = calcCFFSubroutineBias(font.subrs);
  4262. } else {
  4263. font.subrs = [];
  4264. font.subrsBias = 0;
  4265. }
  4266. // Offsets in the top dict are relative to the beginning of the CFF data, so add the CFF start offset.
  4267. var charStringsIndex;
  4268. if (opt.lowMemory) {
  4269. charStringsIndex = parseCFFIndexLowMemory(data, start + topDict.charStrings);
  4270. font.nGlyphs = charStringsIndex.offsets.length;
  4271. } else {
  4272. charStringsIndex = parseCFFIndex(data, start + topDict.charStrings);
  4273. font.nGlyphs = charStringsIndex.objects.length;
  4274. }
  4275. var charset = parseCFFCharset(data, start + topDict.charset, font.nGlyphs, stringIndex.objects);
  4276. if (topDict.encoding === 0) {
  4277. // Standard encoding
  4278. font.cffEncoding = new CffEncoding(cffStandardEncoding, charset);
  4279. } else if (topDict.encoding === 1) {
  4280. // Expert encoding
  4281. font.cffEncoding = new CffEncoding(cffExpertEncoding, charset);
  4282. } else {
  4283. font.cffEncoding = parseCFFEncoding(data, start + topDict.encoding, charset);
  4284. }
  4285. // Prefer the CMAP encoding to the CFF encoding.
  4286. font.encoding = font.encoding || font.cffEncoding;
  4287. font.glyphs = new glyphset.GlyphSet(font);
  4288. if (opt.lowMemory) {
  4289. font._push = function(i) {
  4290. var charString = getCffIndexObject(i, charStringsIndex.offsets, data, start + topDict.charStrings);
  4291. font.glyphs.push(i, glyphset.cffGlyphLoader(font, i, parseCFFCharstring, charString));
  4292. };
  4293. } else {
  4294. for (var i = 0; i < font.nGlyphs; i += 1) {
  4295. var charString = charStringsIndex.objects[i];
  4296. font.glyphs.push(i, glyphset.cffGlyphLoader(font, i, parseCFFCharstring, charString));
  4297. }
  4298. }
  4299. }
  4300. // Convert a string to a String ID (SID).
  4301. // The list of strings is modified in place.
  4302. function encodeString(s, strings) {
  4303. var sid;
  4304. // Is the string in the CFF standard strings?
  4305. var i = cffStandardStrings.indexOf(s);
  4306. if (i >= 0) {
  4307. sid = i;
  4308. }
  4309. // Is the string already in the string index?
  4310. i = strings.indexOf(s);
  4311. if (i >= 0) {
  4312. sid = i + cffStandardStrings.length;
  4313. } else {
  4314. sid = cffStandardStrings.length + strings.length;
  4315. strings.push(s);
  4316. }
  4317. return sid;
  4318. }
  4319. function makeHeader() {
  4320. return new table.Record('Header', [
  4321. {name: 'major', type: 'Card8', value: 1},
  4322. {name: 'minor', type: 'Card8', value: 0},
  4323. {name: 'hdrSize', type: 'Card8', value: 4},
  4324. {name: 'major', type: 'Card8', value: 1}
  4325. ]);
  4326. }
  4327. function makeNameIndex(fontNames) {
  4328. var t = new table.Record('Name INDEX', [
  4329. {name: 'names', type: 'INDEX', value: []}
  4330. ]);
  4331. t.names = [];
  4332. for (var i = 0; i < fontNames.length; i += 1) {
  4333. t.names.push({name: 'name_' + i, type: 'NAME', value: fontNames[i]});
  4334. }
  4335. return t;
  4336. }
  4337. // Given a dictionary's metadata, create a DICT structure.
  4338. function makeDict(meta, attrs, strings) {
  4339. var m = {};
  4340. for (var i = 0; i < meta.length; i += 1) {
  4341. var entry = meta[i];
  4342. var value = attrs[entry.name];
  4343. if (value !== undefined && !equals(value, entry.value)) {
  4344. if (entry.type === 'SID') {
  4345. value = encodeString(value, strings);
  4346. }
  4347. m[entry.op] = {name: entry.name, type: entry.type, value: value};
  4348. }
  4349. }
  4350. return m;
  4351. }
  4352. // The Top DICT houses the global font attributes.
  4353. function makeTopDict(attrs, strings) {
  4354. var t = new table.Record('Top DICT', [
  4355. {name: 'dict', type: 'DICT', value: {}}
  4356. ]);
  4357. t.dict = makeDict(TOP_DICT_META, attrs, strings);
  4358. return t;
  4359. }
  4360. function makeTopDictIndex(topDict) {
  4361. var t = new table.Record('Top DICT INDEX', [
  4362. {name: 'topDicts', type: 'INDEX', value: []}
  4363. ]);
  4364. t.topDicts = [{name: 'topDict_0', type: 'TABLE', value: topDict}];
  4365. return t;
  4366. }
  4367. function makeStringIndex(strings) {
  4368. var t = new table.Record('String INDEX', [
  4369. {name: 'strings', type: 'INDEX', value: []}
  4370. ]);
  4371. t.strings = [];
  4372. for (var i = 0; i < strings.length; i += 1) {
  4373. t.strings.push({name: 'string_' + i, type: 'STRING', value: strings[i]});
  4374. }
  4375. return t;
  4376. }
  4377. function makeGlobalSubrIndex() {
  4378. // Currently we don't use subroutines.
  4379. return new table.Record('Global Subr INDEX', [
  4380. {name: 'subrs', type: 'INDEX', value: []}
  4381. ]);
  4382. }
  4383. function makeCharsets(glyphNames, strings) {
  4384. var t = new table.Record('Charsets', [
  4385. {name: 'format', type: 'Card8', value: 0}
  4386. ]);
  4387. for (var i = 0; i < glyphNames.length; i += 1) {
  4388. var glyphName = glyphNames[i];
  4389. var glyphSID = encodeString(glyphName, strings);
  4390. t.fields.push({name: 'glyph_' + i, type: 'SID', value: glyphSID});
  4391. }
  4392. return t;
  4393. }
  4394. function glyphToOps(glyph) {
  4395. var ops = [];
  4396. var path = glyph.path;
  4397. ops.push({name: 'width', type: 'NUMBER', value: glyph.advanceWidth});
  4398. var x = 0;
  4399. var y = 0;
  4400. for (var i = 0; i < path.commands.length; i += 1) {
  4401. var dx = (void 0);
  4402. var dy = (void 0);
  4403. var cmd = path.commands[i];
  4404. if (cmd.type === 'Q') {
  4405. // CFF only supports bézier curves, so convert the quad to a bézier.
  4406. var _13 = 1 / 3;
  4407. var _23 = 2 / 3;
  4408. // We're going to create a new command so we don't change the original path.
  4409. // Since all coordinates are relative, we round() them ASAP to avoid propagating errors.
  4410. cmd = {
  4411. type: 'C',
  4412. x: cmd.x,
  4413. y: cmd.y,
  4414. x1: Math.round(_13 * x + _23 * cmd.x1),
  4415. y1: Math.round(_13 * y + _23 * cmd.y1),
  4416. x2: Math.round(_13 * cmd.x + _23 * cmd.x1),
  4417. y2: Math.round(_13 * cmd.y + _23 * cmd.y1)
  4418. };
  4419. }
  4420. if (cmd.type === 'M') {
  4421. dx = Math.round(cmd.x - x);
  4422. dy = Math.round(cmd.y - y);
  4423. ops.push({name: 'dx', type: 'NUMBER', value: dx});
  4424. ops.push({name: 'dy', type: 'NUMBER', value: dy});
  4425. ops.push({name: 'rmoveto', type: 'OP', value: 21});
  4426. x = Math.round(cmd.x);
  4427. y = Math.round(cmd.y);
  4428. } else if (cmd.type === 'L') {
  4429. dx = Math.round(cmd.x - x);
  4430. dy = Math.round(cmd.y - y);
  4431. ops.push({name: 'dx', type: 'NUMBER', value: dx});
  4432. ops.push({name: 'dy', type: 'NUMBER', value: dy});
  4433. ops.push({name: 'rlineto', type: 'OP', value: 5});
  4434. x = Math.round(cmd.x);
  4435. y = Math.round(cmd.y);
  4436. } else if (cmd.type === 'C') {
  4437. var dx1 = Math.round(cmd.x1 - x);
  4438. var dy1 = Math.round(cmd.y1 - y);
  4439. var dx2 = Math.round(cmd.x2 - cmd.x1);
  4440. var dy2 = Math.round(cmd.y2 - cmd.y1);
  4441. dx = Math.round(cmd.x - cmd.x2);
  4442. dy = Math.round(cmd.y - cmd.y2);
  4443. ops.push({name: 'dx1', type: 'NUMBER', value: dx1});
  4444. ops.push({name: 'dy1', type: 'NUMBER', value: dy1});
  4445. ops.push({name: 'dx2', type: 'NUMBER', value: dx2});
  4446. ops.push({name: 'dy2', type: 'NUMBER', value: dy2});
  4447. ops.push({name: 'dx', type: 'NUMBER', value: dx});
  4448. ops.push({name: 'dy', type: 'NUMBER', value: dy});
  4449. ops.push({name: 'rrcurveto', type: 'OP', value: 8});
  4450. x = Math.round(cmd.x);
  4451. y = Math.round(cmd.y);
  4452. }
  4453. // Contours are closed automatically.
  4454. }
  4455. ops.push({name: 'endchar', type: 'OP', value: 14});
  4456. return ops;
  4457. }
  4458. function makeCharStringsIndex(glyphs) {
  4459. var t = new table.Record('CharStrings INDEX', [
  4460. {name: 'charStrings', type: 'INDEX', value: []}
  4461. ]);
  4462. for (var i = 0; i < glyphs.length; i += 1) {
  4463. var glyph = glyphs.get(i);
  4464. var ops = glyphToOps(glyph);
  4465. t.charStrings.push({name: glyph.name, type: 'CHARSTRING', value: ops});
  4466. }
  4467. return t;
  4468. }
  4469. function makePrivateDict(attrs, strings) {
  4470. var t = new table.Record('Private DICT', [
  4471. {name: 'dict', type: 'DICT', value: {}}
  4472. ]);
  4473. t.dict = makeDict(PRIVATE_DICT_META, attrs, strings);
  4474. return t;
  4475. }
  4476. function makeCFFTable(glyphs, options) {
  4477. var t = new table.Table('CFF ', [
  4478. {name: 'header', type: 'RECORD'},
  4479. {name: 'nameIndex', type: 'RECORD'},
  4480. {name: 'topDictIndex', type: 'RECORD'},
  4481. {name: 'stringIndex', type: 'RECORD'},
  4482. {name: 'globalSubrIndex', type: 'RECORD'},
  4483. {name: 'charsets', type: 'RECORD'},
  4484. {name: 'charStringsIndex', type: 'RECORD'},
  4485. {name: 'privateDict', type: 'RECORD'}
  4486. ]);
  4487. var fontScale = 1 / options.unitsPerEm;
  4488. // We use non-zero values for the offsets so that the DICT encodes them.
  4489. // This is important because the size of the Top DICT plays a role in offset calculation,
  4490. // and the size shouldn't change after we've written correct offsets.
  4491. var attrs = {
  4492. version: options.version,
  4493. fullName: options.fullName,
  4494. familyName: options.familyName,
  4495. weight: options.weightName,
  4496. fontBBox: options.fontBBox || [0, 0, 0, 0],
  4497. fontMatrix: [fontScale, 0, 0, fontScale, 0, 0],
  4498. charset: 999,
  4499. encoding: 0,
  4500. charStrings: 999,
  4501. private: [0, 999]
  4502. };
  4503. var privateAttrs = {};
  4504. var glyphNames = [];
  4505. var glyph;
  4506. // Skip first glyph (.notdef)
  4507. for (var i = 1; i < glyphs.length; i += 1) {
  4508. glyph = glyphs.get(i);
  4509. glyphNames.push(glyph.name);
  4510. }
  4511. var strings = [];
  4512. t.header = makeHeader();
  4513. t.nameIndex = makeNameIndex([options.postScriptName]);
  4514. var topDict = makeTopDict(attrs, strings);
  4515. t.topDictIndex = makeTopDictIndex(topDict);
  4516. t.globalSubrIndex = makeGlobalSubrIndex();
  4517. t.charsets = makeCharsets(glyphNames, strings);
  4518. t.charStringsIndex = makeCharStringsIndex(glyphs);
  4519. t.privateDict = makePrivateDict(privateAttrs, strings);
  4520. // Needs to come at the end, to encode all custom strings used in the font.
  4521. t.stringIndex = makeStringIndex(strings);
  4522. var startOffset = t.header.sizeOf() +
  4523. t.nameIndex.sizeOf() +
  4524. t.topDictIndex.sizeOf() +
  4525. t.stringIndex.sizeOf() +
  4526. t.globalSubrIndex.sizeOf();
  4527. attrs.charset = startOffset;
  4528. // We use the CFF standard encoding; proper encoding will be handled in cmap.
  4529. attrs.encoding = 0;
  4530. attrs.charStrings = attrs.charset + t.charsets.sizeOf();
  4531. attrs.private[1] = attrs.charStrings + t.charStringsIndex.sizeOf();
  4532. // Recreate the Top DICT INDEX with the correct offsets.
  4533. topDict = makeTopDict(attrs, strings);
  4534. t.topDictIndex = makeTopDictIndex(topDict);
  4535. return t;
  4536. }
  4537. var cff = { parse: parseCFFTable, make: makeCFFTable };
  4538. // The `head` table contains global information about the font.
  4539. // Parse the header `head` table
  4540. function parseHeadTable(data, start) {
  4541. var head = {};
  4542. var p = new parse.Parser(data, start);
  4543. head.version = p.parseVersion();
  4544. head.fontRevision = Math.round(p.parseFixed() * 1000) / 1000;
  4545. head.checkSumAdjustment = p.parseULong();
  4546. head.magicNumber = p.parseULong();
  4547. check.argument(head.magicNumber === 0x5F0F3CF5, 'Font header has wrong magic number.');
  4548. head.flags = p.parseUShort();
  4549. head.unitsPerEm = p.parseUShort();
  4550. head.created = p.parseLongDateTime();
  4551. head.modified = p.parseLongDateTime();
  4552. head.xMin = p.parseShort();
  4553. head.yMin = p.parseShort();
  4554. head.xMax = p.parseShort();
  4555. head.yMax = p.parseShort();
  4556. head.macStyle = p.parseUShort();
  4557. head.lowestRecPPEM = p.parseUShort();
  4558. head.fontDirectionHint = p.parseShort();
  4559. head.indexToLocFormat = p.parseShort();
  4560. head.glyphDataFormat = p.parseShort();
  4561. return head;
  4562. }
  4563. function makeHeadTable(options) {
  4564. // Apple Mac timestamp epoch is 01/01/1904 not 01/01/1970
  4565. var timestamp = Math.round(new Date().getTime() / 1000) + 2082844800;
  4566. var createdTimestamp = timestamp;
  4567. if (options.createdTimestamp) {
  4568. createdTimestamp = options.createdTimestamp + 2082844800;
  4569. }
  4570. return new table.Table('head', [
  4571. {name: 'version', type: 'FIXED', value: 0x00010000},
  4572. {name: 'fontRevision', type: 'FIXED', value: 0x00010000},
  4573. {name: 'checkSumAdjustment', type: 'ULONG', value: 0},
  4574. {name: 'magicNumber', type: 'ULONG', value: 0x5F0F3CF5},
  4575. {name: 'flags', type: 'USHORT', value: 0},
  4576. {name: 'unitsPerEm', type: 'USHORT', value: 1000},
  4577. {name: 'created', type: 'LONGDATETIME', value: createdTimestamp},
  4578. {name: 'modified', type: 'LONGDATETIME', value: timestamp},
  4579. {name: 'xMin', type: 'SHORT', value: 0},
  4580. {name: 'yMin', type: 'SHORT', value: 0},
  4581. {name: 'xMax', type: 'SHORT', value: 0},
  4582. {name: 'yMax', type: 'SHORT', value: 0},
  4583. {name: 'macStyle', type: 'USHORT', value: 0},
  4584. {name: 'lowestRecPPEM', type: 'USHORT', value: 0},
  4585. {name: 'fontDirectionHint', type: 'SHORT', value: 2},
  4586. {name: 'indexToLocFormat', type: 'SHORT', value: 0},
  4587. {name: 'glyphDataFormat', type: 'SHORT', value: 0}
  4588. ], options);
  4589. }
  4590. var head = { parse: parseHeadTable, make: makeHeadTable };
  4591. // The `hhea` table contains information for horizontal layout.
  4592. // Parse the horizontal header `hhea` table
  4593. function parseHheaTable(data, start) {
  4594. var hhea = {};
  4595. var p = new parse.Parser(data, start);
  4596. hhea.version = p.parseVersion();
  4597. hhea.ascender = p.parseShort();
  4598. hhea.descender = p.parseShort();
  4599. hhea.lineGap = p.parseShort();
  4600. hhea.advanceWidthMax = p.parseUShort();
  4601. hhea.minLeftSideBearing = p.parseShort();
  4602. hhea.minRightSideBearing = p.parseShort();
  4603. hhea.xMaxExtent = p.parseShort();
  4604. hhea.caretSlopeRise = p.parseShort();
  4605. hhea.caretSlopeRun = p.parseShort();
  4606. hhea.caretOffset = p.parseShort();
  4607. p.relativeOffset += 8;
  4608. hhea.metricDataFormat = p.parseShort();
  4609. hhea.numberOfHMetrics = p.parseUShort();
  4610. return hhea;
  4611. }
  4612. function makeHheaTable(options) {
  4613. return new table.Table('hhea', [
  4614. {name: 'version', type: 'FIXED', value: 0x00010000},
  4615. {name: 'ascender', type: 'FWORD', value: 0},
  4616. {name: 'descender', type: 'FWORD', value: 0},
  4617. {name: 'lineGap', type: 'FWORD', value: 0},
  4618. {name: 'advanceWidthMax', type: 'UFWORD', value: 0},
  4619. {name: 'minLeftSideBearing', type: 'FWORD', value: 0},
  4620. {name: 'minRightSideBearing', type: 'FWORD', value: 0},
  4621. {name: 'xMaxExtent', type: 'FWORD', value: 0},
  4622. {name: 'caretSlopeRise', type: 'SHORT', value: 1},
  4623. {name: 'caretSlopeRun', type: 'SHORT', value: 0},
  4624. {name: 'caretOffset', type: 'SHORT', value: 0},
  4625. {name: 'reserved1', type: 'SHORT', value: 0},
  4626. {name: 'reserved2', type: 'SHORT', value: 0},
  4627. {name: 'reserved3', type: 'SHORT', value: 0},
  4628. {name: 'reserved4', type: 'SHORT', value: 0},
  4629. {name: 'metricDataFormat', type: 'SHORT', value: 0},
  4630. {name: 'numberOfHMetrics', type: 'USHORT', value: 0}
  4631. ], options);
  4632. }
  4633. var hhea = { parse: parseHheaTable, make: makeHheaTable };
  4634. // The `hmtx` table contains the horizontal metrics for all glyphs.
  4635. function parseHmtxTableAll(data, start, numMetrics, numGlyphs, glyphs) {
  4636. var advanceWidth;
  4637. var leftSideBearing;
  4638. var p = new parse.Parser(data, start);
  4639. for (var i = 0; i < numGlyphs; i += 1) {
  4640. // If the font is monospaced, only one entry is needed. This last entry applies to all subsequent glyphs.
  4641. if (i < numMetrics) {
  4642. advanceWidth = p.parseUShort();
  4643. leftSideBearing = p.parseShort();
  4644. }
  4645. var glyph = glyphs.get(i);
  4646. glyph.advanceWidth = advanceWidth;
  4647. glyph.leftSideBearing = leftSideBearing;
  4648. }
  4649. }
  4650. function parseHmtxTableOnLowMemory(font, data, start, numMetrics, numGlyphs) {
  4651. font._hmtxTableData = {};
  4652. var advanceWidth;
  4653. var leftSideBearing;
  4654. var p = new parse.Parser(data, start);
  4655. for (var i = 0; i < numGlyphs; i += 1) {
  4656. // If the font is monospaced, only one entry is needed. This last entry applies to all subsequent glyphs.
  4657. if (i < numMetrics) {
  4658. advanceWidth = p.parseUShort();
  4659. leftSideBearing = p.parseShort();
  4660. }
  4661. font._hmtxTableData[i] = {
  4662. advanceWidth: advanceWidth,
  4663. leftSideBearing: leftSideBearing
  4664. };
  4665. }
  4666. }
  4667. // Parse the `hmtx` table, which contains the horizontal metrics for all glyphs.
  4668. // This function augments the glyph array, adding the advanceWidth and leftSideBearing to each glyph.
  4669. function parseHmtxTable(font, data, start, numMetrics, numGlyphs, glyphs, opt) {
  4670. if (opt.lowMemory)
  4671. { parseHmtxTableOnLowMemory(font, data, start, numMetrics, numGlyphs); }
  4672. else
  4673. { parseHmtxTableAll(data, start, numMetrics, numGlyphs, glyphs); }
  4674. }
  4675. function makeHmtxTable(glyphs) {
  4676. var t = new table.Table('hmtx', []);
  4677. for (var i = 0; i < glyphs.length; i += 1) {
  4678. var glyph = glyphs.get(i);
  4679. var advanceWidth = glyph.advanceWidth || 0;
  4680. var leftSideBearing = glyph.leftSideBearing || 0;
  4681. t.fields.push({name: 'advanceWidth_' + i, type: 'USHORT', value: advanceWidth});
  4682. t.fields.push({name: 'leftSideBearing_' + i, type: 'SHORT', value: leftSideBearing});
  4683. }
  4684. return t;
  4685. }
  4686. var hmtx = { parse: parseHmtxTable, make: makeHmtxTable };
  4687. // The `ltag` table stores IETF BCP-47 language tags. It allows supporting
  4688. function makeLtagTable(tags) {
  4689. var result = new table.Table('ltag', [
  4690. {name: 'version', type: 'ULONG', value: 1},
  4691. {name: 'flags', type: 'ULONG', value: 0},
  4692. {name: 'numTags', type: 'ULONG', value: tags.length}
  4693. ]);
  4694. var stringPool = '';
  4695. var stringPoolOffset = 12 + tags.length * 4;
  4696. for (var i = 0; i < tags.length; ++i) {
  4697. var pos = stringPool.indexOf(tags[i]);
  4698. if (pos < 0) {
  4699. pos = stringPool.length;
  4700. stringPool += tags[i];
  4701. }
  4702. result.fields.push({name: 'offset ' + i, type: 'USHORT', value: stringPoolOffset + pos});
  4703. result.fields.push({name: 'length ' + i, type: 'USHORT', value: tags[i].length});
  4704. }
  4705. result.fields.push({name: 'stringPool', type: 'CHARARRAY', value: stringPool});
  4706. return result;
  4707. }
  4708. function parseLtagTable(data, start) {
  4709. var p = new parse.Parser(data, start);
  4710. var tableVersion = p.parseULong();
  4711. check.argument(tableVersion === 1, 'Unsupported ltag table version.');
  4712. // The 'ltag' specification does not define any flags; skip the field.
  4713. p.skip('uLong', 1);
  4714. var numTags = p.parseULong();
  4715. var tags = [];
  4716. for (var i = 0; i < numTags; i++) {
  4717. var tag = '';
  4718. var offset = start + p.parseUShort();
  4719. var length = p.parseUShort();
  4720. for (var j = offset; j < offset + length; ++j) {
  4721. tag += String.fromCharCode(data.getInt8(j));
  4722. }
  4723. tags.push(tag);
  4724. }
  4725. return tags;
  4726. }
  4727. var ltag = { make: makeLtagTable, parse: parseLtagTable };
  4728. // The `maxp` table establishes the memory requirements for the font.
  4729. // Parse the maximum profile `maxp` table.
  4730. function parseMaxpTable(data, start) {
  4731. var maxp = {};
  4732. var p = new parse.Parser(data, start);
  4733. maxp.version = p.parseVersion();
  4734. maxp.numGlyphs = p.parseUShort();
  4735. if (maxp.version === 1.0) {
  4736. maxp.maxPoints = p.parseUShort();
  4737. maxp.maxContours = p.parseUShort();
  4738. maxp.maxCompositePoints = p.parseUShort();
  4739. maxp.maxCompositeContours = p.parseUShort();
  4740. maxp.maxZones = p.parseUShort();
  4741. maxp.maxTwilightPoints = p.parseUShort();
  4742. maxp.maxStorage = p.parseUShort();
  4743. maxp.maxFunctionDefs = p.parseUShort();
  4744. maxp.maxInstructionDefs = p.parseUShort();
  4745. maxp.maxStackElements = p.parseUShort();
  4746. maxp.maxSizeOfInstructions = p.parseUShort();
  4747. maxp.maxComponentElements = p.parseUShort();
  4748. maxp.maxComponentDepth = p.parseUShort();
  4749. }
  4750. return maxp;
  4751. }
  4752. function makeMaxpTable(numGlyphs) {
  4753. return new table.Table('maxp', [
  4754. {name: 'version', type: 'FIXED', value: 0x00005000},
  4755. {name: 'numGlyphs', type: 'USHORT', value: numGlyphs}
  4756. ]);
  4757. }
  4758. var maxp = { parse: parseMaxpTable, make: makeMaxpTable };
  4759. // The `name` naming table.
  4760. // NameIDs for the name table.
  4761. var nameTableNames = [
  4762. 'copyright', // 0
  4763. 'fontFamily', // 1
  4764. 'fontSubfamily', // 2
  4765. 'uniqueID', // 3
  4766. 'fullName', // 4
  4767. 'version', // 5
  4768. 'postScriptName', // 6
  4769. 'trademark', // 7
  4770. 'manufacturer', // 8
  4771. 'designer', // 9
  4772. 'description', // 10
  4773. 'manufacturerURL', // 11
  4774. 'designerURL', // 12
  4775. 'license', // 13
  4776. 'licenseURL', // 14
  4777. 'reserved', // 15
  4778. 'preferredFamily', // 16
  4779. 'preferredSubfamily', // 17
  4780. 'compatibleFullName', // 18
  4781. 'sampleText', // 19
  4782. 'postScriptFindFontName', // 20
  4783. 'wwsFamily', // 21
  4784. 'wwsSubfamily' // 22
  4785. ];
  4786. var macLanguages = {
  4787. 0: 'en',
  4788. 1: 'fr',
  4789. 2: 'de',
  4790. 3: 'it',
  4791. 4: 'nl',
  4792. 5: 'sv',
  4793. 6: 'es',
  4794. 7: 'da',
  4795. 8: 'pt',
  4796. 9: 'no',
  4797. 10: 'he',
  4798. 11: 'ja',
  4799. 12: 'ar',
  4800. 13: 'fi',
  4801. 14: 'el',
  4802. 15: 'is',
  4803. 16: 'mt',
  4804. 17: 'tr',
  4805. 18: 'hr',
  4806. 19: 'zh-Hant',
  4807. 20: 'ur',
  4808. 21: 'hi',
  4809. 22: 'th',
  4810. 23: 'ko',
  4811. 24: 'lt',
  4812. 25: 'pl',
  4813. 26: 'hu',
  4814. 27: 'es',
  4815. 28: 'lv',
  4816. 29: 'se',
  4817. 30: 'fo',
  4818. 31: 'fa',
  4819. 32: 'ru',
  4820. 33: 'zh',
  4821. 34: 'nl-BE',
  4822. 35: 'ga',
  4823. 36: 'sq',
  4824. 37: 'ro',
  4825. 38: 'cz',
  4826. 39: 'sk',
  4827. 40: 'si',
  4828. 41: 'yi',
  4829. 42: 'sr',
  4830. 43: 'mk',
  4831. 44: 'bg',
  4832. 45: 'uk',
  4833. 46: 'be',
  4834. 47: 'uz',
  4835. 48: 'kk',
  4836. 49: 'az-Cyrl',
  4837. 50: 'az-Arab',
  4838. 51: 'hy',
  4839. 52: 'ka',
  4840. 53: 'mo',
  4841. 54: 'ky',
  4842. 55: 'tg',
  4843. 56: 'tk',
  4844. 57: 'mn-CN',
  4845. 58: 'mn',
  4846. 59: 'ps',
  4847. 60: 'ks',
  4848. 61: 'ku',
  4849. 62: 'sd',
  4850. 63: 'bo',
  4851. 64: 'ne',
  4852. 65: 'sa',
  4853. 66: 'mr',
  4854. 67: 'bn',
  4855. 68: 'as',
  4856. 69: 'gu',
  4857. 70: 'pa',
  4858. 71: 'or',
  4859. 72: 'ml',
  4860. 73: 'kn',
  4861. 74: 'ta',
  4862. 75: 'te',
  4863. 76: 'si',
  4864. 77: 'my',
  4865. 78: 'km',
  4866. 79: 'lo',
  4867. 80: 'vi',
  4868. 81: 'id',
  4869. 82: 'tl',
  4870. 83: 'ms',
  4871. 84: 'ms-Arab',
  4872. 85: 'am',
  4873. 86: 'ti',
  4874. 87: 'om',
  4875. 88: 'so',
  4876. 89: 'sw',
  4877. 90: 'rw',
  4878. 91: 'rn',
  4879. 92: 'ny',
  4880. 93: 'mg',
  4881. 94: 'eo',
  4882. 128: 'cy',
  4883. 129: 'eu',
  4884. 130: 'ca',
  4885. 131: 'la',
  4886. 132: 'qu',
  4887. 133: 'gn',
  4888. 134: 'ay',
  4889. 135: 'tt',
  4890. 136: 'ug',
  4891. 137: 'dz',
  4892. 138: 'jv',
  4893. 139: 'su',
  4894. 140: 'gl',
  4895. 141: 'af',
  4896. 142: 'br',
  4897. 143: 'iu',
  4898. 144: 'gd',
  4899. 145: 'gv',
  4900. 146: 'ga',
  4901. 147: 'to',
  4902. 148: 'el-polyton',
  4903. 149: 'kl',
  4904. 150: 'az',
  4905. 151: 'nn'
  4906. };
  4907. // MacOS language ID → MacOS script ID
  4908. //
  4909. // Note that the script ID is not sufficient to determine what encoding
  4910. // to use in TrueType files. For some languages, MacOS used a modification
  4911. // of a mainstream script. For example, an Icelandic name would be stored
  4912. // with smRoman in the TrueType naming table, but the actual encoding
  4913. // is a special Icelandic version of the normal Macintosh Roman encoding.
  4914. // As another example, Inuktitut uses an 8-bit encoding for Canadian Aboriginal
  4915. // Syllables but MacOS had run out of available script codes, so this was
  4916. // done as a (pretty radical) "modification" of Ethiopic.
  4917. //
  4918. // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/Readme.txt
  4919. var macLanguageToScript = {
  4920. 0: 0, // langEnglish → smRoman
  4921. 1: 0, // langFrench → smRoman
  4922. 2: 0, // langGerman → smRoman
  4923. 3: 0, // langItalian → smRoman
  4924. 4: 0, // langDutch → smRoman
  4925. 5: 0, // langSwedish → smRoman
  4926. 6: 0, // langSpanish → smRoman
  4927. 7: 0, // langDanish → smRoman
  4928. 8: 0, // langPortuguese → smRoman
  4929. 9: 0, // langNorwegian → smRoman
  4930. 10: 5, // langHebrew → smHebrew
  4931. 11: 1, // langJapanese → smJapanese
  4932. 12: 4, // langArabic → smArabic
  4933. 13: 0, // langFinnish → smRoman
  4934. 14: 6, // langGreek → smGreek
  4935. 15: 0, // langIcelandic → smRoman (modified)
  4936. 16: 0, // langMaltese → smRoman
  4937. 17: 0, // langTurkish → smRoman (modified)
  4938. 18: 0, // langCroatian → smRoman (modified)
  4939. 19: 2, // langTradChinese → smTradChinese
  4940. 20: 4, // langUrdu → smArabic
  4941. 21: 9, // langHindi → smDevanagari
  4942. 22: 21, // langThai → smThai
  4943. 23: 3, // langKorean → smKorean
  4944. 24: 29, // langLithuanian → smCentralEuroRoman
  4945. 25: 29, // langPolish → smCentralEuroRoman
  4946. 26: 29, // langHungarian → smCentralEuroRoman
  4947. 27: 29, // langEstonian → smCentralEuroRoman
  4948. 28: 29, // langLatvian → smCentralEuroRoman
  4949. 29: 0, // langSami → smRoman
  4950. 30: 0, // langFaroese → smRoman (modified)
  4951. 31: 4, // langFarsi → smArabic (modified)
  4952. 32: 7, // langRussian → smCyrillic
  4953. 33: 25, // langSimpChinese → smSimpChinese
  4954. 34: 0, // langFlemish → smRoman
  4955. 35: 0, // langIrishGaelic → smRoman (modified)
  4956. 36: 0, // langAlbanian → smRoman
  4957. 37: 0, // langRomanian → smRoman (modified)
  4958. 38: 29, // langCzech → smCentralEuroRoman
  4959. 39: 29, // langSlovak → smCentralEuroRoman
  4960. 40: 0, // langSlovenian → smRoman (modified)
  4961. 41: 5, // langYiddish → smHebrew
  4962. 42: 7, // langSerbian → smCyrillic
  4963. 43: 7, // langMacedonian → smCyrillic
  4964. 44: 7, // langBulgarian → smCyrillic
  4965. 45: 7, // langUkrainian → smCyrillic (modified)
  4966. 46: 7, // langByelorussian → smCyrillic
  4967. 47: 7, // langUzbek → smCyrillic
  4968. 48: 7, // langKazakh → smCyrillic
  4969. 49: 7, // langAzerbaijani → smCyrillic
  4970. 50: 4, // langAzerbaijanAr → smArabic
  4971. 51: 24, // langArmenian → smArmenian
  4972. 52: 23, // langGeorgian → smGeorgian
  4973. 53: 7, // langMoldavian → smCyrillic
  4974. 54: 7, // langKirghiz → smCyrillic
  4975. 55: 7, // langTajiki → smCyrillic
  4976. 56: 7, // langTurkmen → smCyrillic
  4977. 57: 27, // langMongolian → smMongolian
  4978. 58: 7, // langMongolianCyr → smCyrillic
  4979. 59: 4, // langPashto → smArabic
  4980. 60: 4, // langKurdish → smArabic
  4981. 61: 4, // langKashmiri → smArabic
  4982. 62: 4, // langSindhi → smArabic
  4983. 63: 26, // langTibetan → smTibetan
  4984. 64: 9, // langNepali → smDevanagari
  4985. 65: 9, // langSanskrit → smDevanagari
  4986. 66: 9, // langMarathi → smDevanagari
  4987. 67: 13, // langBengali → smBengali
  4988. 68: 13, // langAssamese → smBengali
  4989. 69: 11, // langGujarati → smGujarati
  4990. 70: 10, // langPunjabi → smGurmukhi
  4991. 71: 12, // langOriya → smOriya
  4992. 72: 17, // langMalayalam → smMalayalam
  4993. 73: 16, // langKannada → smKannada
  4994. 74: 14, // langTamil → smTamil
  4995. 75: 15, // langTelugu → smTelugu
  4996. 76: 18, // langSinhalese → smSinhalese
  4997. 77: 19, // langBurmese → smBurmese
  4998. 78: 20, // langKhmer → smKhmer
  4999. 79: 22, // langLao → smLao
  5000. 80: 30, // langVietnamese → smVietnamese
  5001. 81: 0, // langIndonesian → smRoman
  5002. 82: 0, // langTagalog → smRoman
  5003. 83: 0, // langMalayRoman → smRoman
  5004. 84: 4, // langMalayArabic → smArabic
  5005. 85: 28, // langAmharic → smEthiopic
  5006. 86: 28, // langTigrinya → smEthiopic
  5007. 87: 28, // langOromo → smEthiopic
  5008. 88: 0, // langSomali → smRoman
  5009. 89: 0, // langSwahili → smRoman
  5010. 90: 0, // langKinyarwanda → smRoman
  5011. 91: 0, // langRundi → smRoman
  5012. 92: 0, // langNyanja → smRoman
  5013. 93: 0, // langMalagasy → smRoman
  5014. 94: 0, // langEsperanto → smRoman
  5015. 128: 0, // langWelsh → smRoman (modified)
  5016. 129: 0, // langBasque → smRoman
  5017. 130: 0, // langCatalan → smRoman
  5018. 131: 0, // langLatin → smRoman
  5019. 132: 0, // langQuechua → smRoman
  5020. 133: 0, // langGuarani → smRoman
  5021. 134: 0, // langAymara → smRoman
  5022. 135: 7, // langTatar → smCyrillic
  5023. 136: 4, // langUighur → smArabic
  5024. 137: 26, // langDzongkha → smTibetan
  5025. 138: 0, // langJavaneseRom → smRoman
  5026. 139: 0, // langSundaneseRom → smRoman
  5027. 140: 0, // langGalician → smRoman
  5028. 141: 0, // langAfrikaans → smRoman
  5029. 142: 0, // langBreton → smRoman (modified)
  5030. 143: 28, // langInuktitut → smEthiopic (modified)
  5031. 144: 0, // langScottishGaelic → smRoman (modified)
  5032. 145: 0, // langManxGaelic → smRoman (modified)
  5033. 146: 0, // langIrishGaelicScript → smRoman (modified)
  5034. 147: 0, // langTongan → smRoman
  5035. 148: 6, // langGreekAncient → smRoman
  5036. 149: 0, // langGreenlandic → smRoman
  5037. 150: 0, // langAzerbaijanRoman → smRoman
  5038. 151: 0 // langNynorsk → smRoman
  5039. };
  5040. // While Microsoft indicates a region/country for all its language
  5041. // IDs, we omit the region code if it's equal to the "most likely
  5042. // region subtag" according to Unicode CLDR. For scripts, we omit
  5043. // the subtag if it is equal to the Suppress-Script entry in the
  5044. // IANA language subtag registry for IETF BCP 47.
  5045. //
  5046. // For example, Microsoft states that its language code 0x041A is
  5047. // Croatian in Croatia. We transform this to the BCP 47 language code 'hr'
  5048. // and not 'hr-HR' because Croatia is the default country for Croatian,
  5049. // according to Unicode CLDR. As another example, Microsoft states
  5050. // that 0x101A is Croatian (Latin) in Bosnia-Herzegovina. We transform
  5051. // this to 'hr-BA' and not 'hr-Latn-BA' because Latin is the default script
  5052. // for the Croatian language, according to IANA.
  5053. //
  5054. // http://www.unicode.org/cldr/charts/latest/supplemental/likely_subtags.html
  5055. // http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry
  5056. var windowsLanguages = {
  5057. 0x0436: 'af',
  5058. 0x041C: 'sq',
  5059. 0x0484: 'gsw',
  5060. 0x045E: 'am',
  5061. 0x1401: 'ar-DZ',
  5062. 0x3C01: 'ar-BH',
  5063. 0x0C01: 'ar',
  5064. 0x0801: 'ar-IQ',
  5065. 0x2C01: 'ar-JO',
  5066. 0x3401: 'ar-KW',
  5067. 0x3001: 'ar-LB',
  5068. 0x1001: 'ar-LY',
  5069. 0x1801: 'ary',
  5070. 0x2001: 'ar-OM',
  5071. 0x4001: 'ar-QA',
  5072. 0x0401: 'ar-SA',
  5073. 0x2801: 'ar-SY',
  5074. 0x1C01: 'aeb',
  5075. 0x3801: 'ar-AE',
  5076. 0x2401: 'ar-YE',
  5077. 0x042B: 'hy',
  5078. 0x044D: 'as',
  5079. 0x082C: 'az-Cyrl',
  5080. 0x042C: 'az',
  5081. 0x046D: 'ba',
  5082. 0x042D: 'eu',
  5083. 0x0423: 'be',
  5084. 0x0845: 'bn',
  5085. 0x0445: 'bn-IN',
  5086. 0x201A: 'bs-Cyrl',
  5087. 0x141A: 'bs',
  5088. 0x047E: 'br',
  5089. 0x0402: 'bg',
  5090. 0x0403: 'ca',
  5091. 0x0C04: 'zh-HK',
  5092. 0x1404: 'zh-MO',
  5093. 0x0804: 'zh',
  5094. 0x1004: 'zh-SG',
  5095. 0x0404: 'zh-TW',
  5096. 0x0483: 'co',
  5097. 0x041A: 'hr',
  5098. 0x101A: 'hr-BA',
  5099. 0x0405: 'cs',
  5100. 0x0406: 'da',
  5101. 0x048C: 'prs',
  5102. 0x0465: 'dv',
  5103. 0x0813: 'nl-BE',
  5104. 0x0413: 'nl',
  5105. 0x0C09: 'en-AU',
  5106. 0x2809: 'en-BZ',
  5107. 0x1009: 'en-CA',
  5108. 0x2409: 'en-029',
  5109. 0x4009: 'en-IN',
  5110. 0x1809: 'en-IE',
  5111. 0x2009: 'en-JM',
  5112. 0x4409: 'en-MY',
  5113. 0x1409: 'en-NZ',
  5114. 0x3409: 'en-PH',
  5115. 0x4809: 'en-SG',
  5116. 0x1C09: 'en-ZA',
  5117. 0x2C09: 'en-TT',
  5118. 0x0809: 'en-GB',
  5119. 0x0409: 'en',
  5120. 0x3009: 'en-ZW',
  5121. 0x0425: 'et',
  5122. 0x0438: 'fo',
  5123. 0x0464: 'fil',
  5124. 0x040B: 'fi',
  5125. 0x080C: 'fr-BE',
  5126. 0x0C0C: 'fr-CA',
  5127. 0x040C: 'fr',
  5128. 0x140C: 'fr-LU',
  5129. 0x180C: 'fr-MC',
  5130. 0x100C: 'fr-CH',
  5131. 0x0462: 'fy',
  5132. 0x0456: 'gl',
  5133. 0x0437: 'ka',
  5134. 0x0C07: 'de-AT',
  5135. 0x0407: 'de',
  5136. 0x1407: 'de-LI',
  5137. 0x1007: 'de-LU',
  5138. 0x0807: 'de-CH',
  5139. 0x0408: 'el',
  5140. 0x046F: 'kl',
  5141. 0x0447: 'gu',
  5142. 0x0468: 'ha',
  5143. 0x040D: 'he',
  5144. 0x0439: 'hi',
  5145. 0x040E: 'hu',
  5146. 0x040F: 'is',
  5147. 0x0470: 'ig',
  5148. 0x0421: 'id',
  5149. 0x045D: 'iu',
  5150. 0x085D: 'iu-Latn',
  5151. 0x083C: 'ga',
  5152. 0x0434: 'xh',
  5153. 0x0435: 'zu',
  5154. 0x0410: 'it',
  5155. 0x0810: 'it-CH',
  5156. 0x0411: 'ja',
  5157. 0x044B: 'kn',
  5158. 0x043F: 'kk',
  5159. 0x0453: 'km',
  5160. 0x0486: 'quc',
  5161. 0x0487: 'rw',
  5162. 0x0441: 'sw',
  5163. 0x0457: 'kok',
  5164. 0x0412: 'ko',
  5165. 0x0440: 'ky',
  5166. 0x0454: 'lo',
  5167. 0x0426: 'lv',
  5168. 0x0427: 'lt',
  5169. 0x082E: 'dsb',
  5170. 0x046E: 'lb',
  5171. 0x042F: 'mk',
  5172. 0x083E: 'ms-BN',
  5173. 0x043E: 'ms',
  5174. 0x044C: 'ml',
  5175. 0x043A: 'mt',
  5176. 0x0481: 'mi',
  5177. 0x047A: 'arn',
  5178. 0x044E: 'mr',
  5179. 0x047C: 'moh',
  5180. 0x0450: 'mn',
  5181. 0x0850: 'mn-CN',
  5182. 0x0461: 'ne',
  5183. 0x0414: 'nb',
  5184. 0x0814: 'nn',
  5185. 0x0482: 'oc',
  5186. 0x0448: 'or',
  5187. 0x0463: 'ps',
  5188. 0x0415: 'pl',
  5189. 0x0416: 'pt',
  5190. 0x0816: 'pt-PT',
  5191. 0x0446: 'pa',
  5192. 0x046B: 'qu-BO',
  5193. 0x086B: 'qu-EC',
  5194. 0x0C6B: 'qu',
  5195. 0x0418: 'ro',
  5196. 0x0417: 'rm',
  5197. 0x0419: 'ru',
  5198. 0x243B: 'smn',
  5199. 0x103B: 'smj-NO',
  5200. 0x143B: 'smj',
  5201. 0x0C3B: 'se-FI',
  5202. 0x043B: 'se',
  5203. 0x083B: 'se-SE',
  5204. 0x203B: 'sms',
  5205. 0x183B: 'sma-NO',
  5206. 0x1C3B: 'sms',
  5207. 0x044F: 'sa',
  5208. 0x1C1A: 'sr-Cyrl-BA',
  5209. 0x0C1A: 'sr',
  5210. 0x181A: 'sr-Latn-BA',
  5211. 0x081A: 'sr-Latn',
  5212. 0x046C: 'nso',
  5213. 0x0432: 'tn',
  5214. 0x045B: 'si',
  5215. 0x041B: 'sk',
  5216. 0x0424: 'sl',
  5217. 0x2C0A: 'es-AR',
  5218. 0x400A: 'es-BO',
  5219. 0x340A: 'es-CL',
  5220. 0x240A: 'es-CO',
  5221. 0x140A: 'es-CR',
  5222. 0x1C0A: 'es-DO',
  5223. 0x300A: 'es-EC',
  5224. 0x440A: 'es-SV',
  5225. 0x100A: 'es-GT',
  5226. 0x480A: 'es-HN',
  5227. 0x080A: 'es-MX',
  5228. 0x4C0A: 'es-NI',
  5229. 0x180A: 'es-PA',
  5230. 0x3C0A: 'es-PY',
  5231. 0x280A: 'es-PE',
  5232. 0x500A: 'es-PR',
  5233. // Microsoft has defined two different language codes for
  5234. // “Spanish with modern sorting” and “Spanish with traditional
  5235. // sorting”. This makes sense for collation APIs, and it would be
  5236. // possible to express this in BCP 47 language tags via Unicode
  5237. // extensions (eg., es-u-co-trad is Spanish with traditional
  5238. // sorting). However, for storing names in fonts, the distinction
  5239. // does not make sense, so we give “es” in both cases.
  5240. 0x0C0A: 'es',
  5241. 0x040A: 'es',
  5242. 0x540A: 'es-US',
  5243. 0x380A: 'es-UY',
  5244. 0x200A: 'es-VE',
  5245. 0x081D: 'sv-FI',
  5246. 0x041D: 'sv',
  5247. 0x045A: 'syr',
  5248. 0x0428: 'tg',
  5249. 0x085F: 'tzm',
  5250. 0x0449: 'ta',
  5251. 0x0444: 'tt',
  5252. 0x044A: 'te',
  5253. 0x041E: 'th',
  5254. 0x0451: 'bo',
  5255. 0x041F: 'tr',
  5256. 0x0442: 'tk',
  5257. 0x0480: 'ug',
  5258. 0x0422: 'uk',
  5259. 0x042E: 'hsb',
  5260. 0x0420: 'ur',
  5261. 0x0843: 'uz-Cyrl',
  5262. 0x0443: 'uz',
  5263. 0x042A: 'vi',
  5264. 0x0452: 'cy',
  5265. 0x0488: 'wo',
  5266. 0x0485: 'sah',
  5267. 0x0478: 'ii',
  5268. 0x046A: 'yo'
  5269. };
  5270. // Returns a IETF BCP 47 language code, for example 'zh-Hant'
  5271. // for 'Chinese in the traditional script'.
  5272. function getLanguageCode(platformID, languageID, ltag) {
  5273. switch (platformID) {
  5274. case 0: // Unicode
  5275. if (languageID === 0xFFFF) {
  5276. return 'und';
  5277. } else if (ltag) {
  5278. return ltag[languageID];
  5279. }
  5280. break;
  5281. case 1: // Macintosh
  5282. return macLanguages[languageID];
  5283. case 3: // Windows
  5284. return windowsLanguages[languageID];
  5285. }
  5286. return undefined;
  5287. }
  5288. var utf16 = 'utf-16';
  5289. // MacOS script ID → encoding. This table stores the default case,
  5290. // which can be overridden by macLanguageEncodings.
  5291. var macScriptEncodings = {
  5292. 0: 'macintosh', // smRoman
  5293. 1: 'x-mac-japanese', // smJapanese
  5294. 2: 'x-mac-chinesetrad', // smTradChinese
  5295. 3: 'x-mac-korean', // smKorean
  5296. 6: 'x-mac-greek', // smGreek
  5297. 7: 'x-mac-cyrillic', // smCyrillic
  5298. 9: 'x-mac-devanagai', // smDevanagari
  5299. 10: 'x-mac-gurmukhi', // smGurmukhi
  5300. 11: 'x-mac-gujarati', // smGujarati
  5301. 12: 'x-mac-oriya', // smOriya
  5302. 13: 'x-mac-bengali', // smBengali
  5303. 14: 'x-mac-tamil', // smTamil
  5304. 15: 'x-mac-telugu', // smTelugu
  5305. 16: 'x-mac-kannada', // smKannada
  5306. 17: 'x-mac-malayalam', // smMalayalam
  5307. 18: 'x-mac-sinhalese', // smSinhalese
  5308. 19: 'x-mac-burmese', // smBurmese
  5309. 20: 'x-mac-khmer', // smKhmer
  5310. 21: 'x-mac-thai', // smThai
  5311. 22: 'x-mac-lao', // smLao
  5312. 23: 'x-mac-georgian', // smGeorgian
  5313. 24: 'x-mac-armenian', // smArmenian
  5314. 25: 'x-mac-chinesesimp', // smSimpChinese
  5315. 26: 'x-mac-tibetan', // smTibetan
  5316. 27: 'x-mac-mongolian', // smMongolian
  5317. 28: 'x-mac-ethiopic', // smEthiopic
  5318. 29: 'x-mac-ce', // smCentralEuroRoman
  5319. 30: 'x-mac-vietnamese', // smVietnamese
  5320. 31: 'x-mac-extarabic' // smExtArabic
  5321. };
  5322. // MacOS language ID → encoding. This table stores the exceptional
  5323. // cases, which override macScriptEncodings. For writing MacOS naming
  5324. // tables, we need to emit a MacOS script ID. Therefore, we cannot
  5325. // merge macScriptEncodings into macLanguageEncodings.
  5326. //
  5327. // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/Readme.txt
  5328. var macLanguageEncodings = {
  5329. 15: 'x-mac-icelandic', // langIcelandic
  5330. 17: 'x-mac-turkish', // langTurkish
  5331. 18: 'x-mac-croatian', // langCroatian
  5332. 24: 'x-mac-ce', // langLithuanian
  5333. 25: 'x-mac-ce', // langPolish
  5334. 26: 'x-mac-ce', // langHungarian
  5335. 27: 'x-mac-ce', // langEstonian
  5336. 28: 'x-mac-ce', // langLatvian
  5337. 30: 'x-mac-icelandic', // langFaroese
  5338. 37: 'x-mac-romanian', // langRomanian
  5339. 38: 'x-mac-ce', // langCzech
  5340. 39: 'x-mac-ce', // langSlovak
  5341. 40: 'x-mac-ce', // langSlovenian
  5342. 143: 'x-mac-inuit', // langInuktitut
  5343. 146: 'x-mac-gaelic' // langIrishGaelicScript
  5344. };
  5345. function getEncoding(platformID, encodingID, languageID) {
  5346. switch (platformID) {
  5347. case 0: // Unicode
  5348. return utf16;
  5349. case 1: // Apple Macintosh
  5350. return macLanguageEncodings[languageID] || macScriptEncodings[encodingID];
  5351. case 3: // Microsoft Windows
  5352. if (encodingID === 1 || encodingID === 10) {
  5353. return utf16;
  5354. }
  5355. break;
  5356. }
  5357. return undefined;
  5358. }
  5359. // Parse the naming `name` table.
  5360. // FIXME: Format 1 additional fields are not supported yet.
  5361. // ltag is the content of the `ltag' table, such as ['en', 'zh-Hans', 'de-CH-1904'].
  5362. function parseNameTable(data, start, ltag) {
  5363. var name = {};
  5364. var p = new parse.Parser(data, start);
  5365. var format = p.parseUShort();
  5366. var count = p.parseUShort();
  5367. var stringOffset = p.offset + p.parseUShort();
  5368. for (var i = 0; i < count; i++) {
  5369. var platformID = p.parseUShort();
  5370. var encodingID = p.parseUShort();
  5371. var languageID = p.parseUShort();
  5372. var nameID = p.parseUShort();
  5373. var property = nameTableNames[nameID] || nameID;
  5374. var byteLength = p.parseUShort();
  5375. var offset = p.parseUShort();
  5376. var language = getLanguageCode(platformID, languageID, ltag);
  5377. var encoding = getEncoding(platformID, encodingID, languageID);
  5378. if (encoding !== undefined && language !== undefined) {
  5379. var text = (void 0);
  5380. if (encoding === utf16) {
  5381. text = decode.UTF16(data, stringOffset + offset, byteLength);
  5382. } else {
  5383. text = decode.MACSTRING(data, stringOffset + offset, byteLength, encoding);
  5384. }
  5385. if (text) {
  5386. var translations = name[property];
  5387. if (translations === undefined) {
  5388. translations = name[property] = {};
  5389. }
  5390. translations[language] = text;
  5391. }
  5392. }
  5393. }
  5394. var langTagCount = 0;
  5395. if (format === 1) {
  5396. // FIXME: Also handle Microsoft's 'name' table 1.
  5397. langTagCount = p.parseUShort();
  5398. }
  5399. return name;
  5400. }
  5401. // {23: 'foo'} → {'foo': 23}
  5402. // ['bar', 'baz'] → {'bar': 0, 'baz': 1}
  5403. function reverseDict(dict) {
  5404. var result = {};
  5405. for (var key in dict) {
  5406. result[dict[key]] = parseInt(key);
  5407. }
  5408. return result;
  5409. }
  5410. function makeNameRecord(platformID, encodingID, languageID, nameID, length, offset) {
  5411. return new table.Record('NameRecord', [
  5412. {name: 'platformID', type: 'USHORT', value: platformID},
  5413. {name: 'encodingID', type: 'USHORT', value: encodingID},
  5414. {name: 'languageID', type: 'USHORT', value: languageID},
  5415. {name: 'nameID', type: 'USHORT', value: nameID},
  5416. {name: 'length', type: 'USHORT', value: length},
  5417. {name: 'offset', type: 'USHORT', value: offset}
  5418. ]);
  5419. }
  5420. // Finds the position of needle in haystack, or -1 if not there.
  5421. // Like String.indexOf(), but for arrays.
  5422. function findSubArray(needle, haystack) {
  5423. var needleLength = needle.length;
  5424. var limit = haystack.length - needleLength + 1;
  5425. loop:
  5426. for (var pos = 0; pos < limit; pos++) {
  5427. for (; pos < limit; pos++) {
  5428. for (var k = 0; k < needleLength; k++) {
  5429. if (haystack[pos + k] !== needle[k]) {
  5430. continue loop;
  5431. }
  5432. }
  5433. return pos;
  5434. }
  5435. }
  5436. return -1;
  5437. }
  5438. function addStringToPool(s, pool) {
  5439. var offset = findSubArray(s, pool);
  5440. if (offset < 0) {
  5441. offset = pool.length;
  5442. var i = 0;
  5443. var len = s.length;
  5444. for (; i < len; ++i) {
  5445. pool.push(s[i]);
  5446. }
  5447. }
  5448. return offset;
  5449. }
  5450. function makeNameTable(names, ltag) {
  5451. var nameID;
  5452. var nameIDs = [];
  5453. var namesWithNumericKeys = {};
  5454. var nameTableIds = reverseDict(nameTableNames);
  5455. for (var key in names) {
  5456. var id = nameTableIds[key];
  5457. if (id === undefined) {
  5458. id = key;
  5459. }
  5460. nameID = parseInt(id);
  5461. if (isNaN(nameID)) {
  5462. throw new Error('Name table entry "' + key + '" does not exist, see nameTableNames for complete list.');
  5463. }
  5464. namesWithNumericKeys[nameID] = names[key];
  5465. nameIDs.push(nameID);
  5466. }
  5467. var macLanguageIds = reverseDict(macLanguages);
  5468. var windowsLanguageIds = reverseDict(windowsLanguages);
  5469. var nameRecords = [];
  5470. var stringPool = [];
  5471. for (var i = 0; i < nameIDs.length; i++) {
  5472. nameID = nameIDs[i];
  5473. var translations = namesWithNumericKeys[nameID];
  5474. for (var lang in translations) {
  5475. var text = translations[lang];
  5476. // For MacOS, we try to emit the name in the form that was introduced
  5477. // in the initial version of the TrueType spec (in the late 1980s).
  5478. // However, this can fail for various reasons: the requested BCP 47
  5479. // language code might not have an old-style Mac equivalent;
  5480. // we might not have a codec for the needed character encoding;
  5481. // or the name might contain characters that cannot be expressed
  5482. // in the old-style Macintosh encoding. In case of failure, we emit
  5483. // the name in a more modern fashion (Unicode encoding with BCP 47
  5484. // language tags) that is recognized by MacOS 10.5, released in 2009.
  5485. // If fonts were only read by operating systems, we could simply
  5486. // emit all names in the modern form; this would be much easier.
  5487. // However, there are many applications and libraries that read
  5488. // 'name' tables directly, and these will usually only recognize
  5489. // the ancient form (silently skipping the unrecognized names).
  5490. var macPlatform = 1; // Macintosh
  5491. var macLanguage = macLanguageIds[lang];
  5492. var macScript = macLanguageToScript[macLanguage];
  5493. var macEncoding = getEncoding(macPlatform, macScript, macLanguage);
  5494. var macName = encode.MACSTRING(text, macEncoding);
  5495. if (macName === undefined) {
  5496. macPlatform = 0; // Unicode
  5497. macLanguage = ltag.indexOf(lang);
  5498. if (macLanguage < 0) {
  5499. macLanguage = ltag.length;
  5500. ltag.push(lang);
  5501. }
  5502. macScript = 4; // Unicode 2.0 and later
  5503. macName = encode.UTF16(text);
  5504. }
  5505. var macNameOffset = addStringToPool(macName, stringPool);
  5506. nameRecords.push(makeNameRecord(macPlatform, macScript, macLanguage,
  5507. nameID, macName.length, macNameOffset));
  5508. var winLanguage = windowsLanguageIds[lang];
  5509. if (winLanguage !== undefined) {
  5510. var winName = encode.UTF16(text);
  5511. var winNameOffset = addStringToPool(winName, stringPool);
  5512. nameRecords.push(makeNameRecord(3, 1, winLanguage,
  5513. nameID, winName.length, winNameOffset));
  5514. }
  5515. }
  5516. }
  5517. nameRecords.sort(function(a, b) {
  5518. return ((a.platformID - b.platformID) ||
  5519. (a.encodingID - b.encodingID) ||
  5520. (a.languageID - b.languageID) ||
  5521. (a.nameID - b.nameID));
  5522. });
  5523. var t = new table.Table('name', [
  5524. {name: 'format', type: 'USHORT', value: 0},
  5525. {name: 'count', type: 'USHORT', value: nameRecords.length},
  5526. {name: 'stringOffset', type: 'USHORT', value: 6 + nameRecords.length * 12}
  5527. ]);
  5528. for (var r = 0; r < nameRecords.length; r++) {
  5529. t.fields.push({name: 'record_' + r, type: 'RECORD', value: nameRecords[r]});
  5530. }
  5531. t.fields.push({name: 'strings', type: 'LITERAL', value: stringPool});
  5532. return t;
  5533. }
  5534. var _name = { parse: parseNameTable, make: makeNameTable };
  5535. // The `OS/2` table contains metrics required in OpenType fonts.
  5536. var unicodeRanges = [
  5537. {begin: 0x0000, end: 0x007F}, // Basic Latin
  5538. {begin: 0x0080, end: 0x00FF}, // Latin-1 Supplement
  5539. {begin: 0x0100, end: 0x017F}, // Latin Extended-A
  5540. {begin: 0x0180, end: 0x024F}, // Latin Extended-B
  5541. {begin: 0x0250, end: 0x02AF}, // IPA Extensions
  5542. {begin: 0x02B0, end: 0x02FF}, // Spacing Modifier Letters
  5543. {begin: 0x0300, end: 0x036F}, // Combining Diacritical Marks
  5544. {begin: 0x0370, end: 0x03FF}, // Greek and Coptic
  5545. {begin: 0x2C80, end: 0x2CFF}, // Coptic
  5546. {begin: 0x0400, end: 0x04FF}, // Cyrillic
  5547. {begin: 0x0530, end: 0x058F}, // Armenian
  5548. {begin: 0x0590, end: 0x05FF}, // Hebrew
  5549. {begin: 0xA500, end: 0xA63F}, // Vai
  5550. {begin: 0x0600, end: 0x06FF}, // Arabic
  5551. {begin: 0x07C0, end: 0x07FF}, // NKo
  5552. {begin: 0x0900, end: 0x097F}, // Devanagari
  5553. {begin: 0x0980, end: 0x09FF}, // Bengali
  5554. {begin: 0x0A00, end: 0x0A7F}, // Gurmukhi
  5555. {begin: 0x0A80, end: 0x0AFF}, // Gujarati
  5556. {begin: 0x0B00, end: 0x0B7F}, // Oriya
  5557. {begin: 0x0B80, end: 0x0BFF}, // Tamil
  5558. {begin: 0x0C00, end: 0x0C7F}, // Telugu
  5559. {begin: 0x0C80, end: 0x0CFF}, // Kannada
  5560. {begin: 0x0D00, end: 0x0D7F}, // Malayalam
  5561. {begin: 0x0E00, end: 0x0E7F}, // Thai
  5562. {begin: 0x0E80, end: 0x0EFF}, // Lao
  5563. {begin: 0x10A0, end: 0x10FF}, // Georgian
  5564. {begin: 0x1B00, end: 0x1B7F}, // Balinese
  5565. {begin: 0x1100, end: 0x11FF}, // Hangul Jamo
  5566. {begin: 0x1E00, end: 0x1EFF}, // Latin Extended Additional
  5567. {begin: 0x1F00, end: 0x1FFF}, // Greek Extended
  5568. {begin: 0x2000, end: 0x206F}, // General Punctuation
  5569. {begin: 0x2070, end: 0x209F}, // Superscripts And Subscripts
  5570. {begin: 0x20A0, end: 0x20CF}, // Currency Symbol
  5571. {begin: 0x20D0, end: 0x20FF}, // Combining Diacritical Marks For Symbols
  5572. {begin: 0x2100, end: 0x214F}, // Letterlike Symbols
  5573. {begin: 0x2150, end: 0x218F}, // Number Forms
  5574. {begin: 0x2190, end: 0x21FF}, // Arrows
  5575. {begin: 0x2200, end: 0x22FF}, // Mathematical Operators
  5576. {begin: 0x2300, end: 0x23FF}, // Miscellaneous Technical
  5577. {begin: 0x2400, end: 0x243F}, // Control Pictures
  5578. {begin: 0x2440, end: 0x245F}, // Optical Character Recognition
  5579. {begin: 0x2460, end: 0x24FF}, // Enclosed Alphanumerics
  5580. {begin: 0x2500, end: 0x257F}, // Box Drawing
  5581. {begin: 0x2580, end: 0x259F}, // Block Elements
  5582. {begin: 0x25A0, end: 0x25FF}, // Geometric Shapes
  5583. {begin: 0x2600, end: 0x26FF}, // Miscellaneous Symbols
  5584. {begin: 0x2700, end: 0x27BF}, // Dingbats
  5585. {begin: 0x3000, end: 0x303F}, // CJK Symbols And Punctuation
  5586. {begin: 0x3040, end: 0x309F}, // Hiragana
  5587. {begin: 0x30A0, end: 0x30FF}, // Katakana
  5588. {begin: 0x3100, end: 0x312F}, // Bopomofo
  5589. {begin: 0x3130, end: 0x318F}, // Hangul Compatibility Jamo
  5590. {begin: 0xA840, end: 0xA87F}, // Phags-pa
  5591. {begin: 0x3200, end: 0x32FF}, // Enclosed CJK Letters And Months
  5592. {begin: 0x3300, end: 0x33FF}, // CJK Compatibility
  5593. {begin: 0xAC00, end: 0xD7AF}, // Hangul Syllables
  5594. {begin: 0xD800, end: 0xDFFF}, // Non-Plane 0 *
  5595. {begin: 0x10900, end: 0x1091F}, // Phoenicia
  5596. {begin: 0x4E00, end: 0x9FFF}, // CJK Unified Ideographs
  5597. {begin: 0xE000, end: 0xF8FF}, // Private Use Area (plane 0)
  5598. {begin: 0x31C0, end: 0x31EF}, // CJK Strokes
  5599. {begin: 0xFB00, end: 0xFB4F}, // Alphabetic Presentation Forms
  5600. {begin: 0xFB50, end: 0xFDFF}, // Arabic Presentation Forms-A
  5601. {begin: 0xFE20, end: 0xFE2F}, // Combining Half Marks
  5602. {begin: 0xFE10, end: 0xFE1F}, // Vertical Forms
  5603. {begin: 0xFE50, end: 0xFE6F}, // Small Form Variants
  5604. {begin: 0xFE70, end: 0xFEFF}, // Arabic Presentation Forms-B
  5605. {begin: 0xFF00, end: 0xFFEF}, // Halfwidth And Fullwidth Forms
  5606. {begin: 0xFFF0, end: 0xFFFF}, // Specials
  5607. {begin: 0x0F00, end: 0x0FFF}, // Tibetan
  5608. {begin: 0x0700, end: 0x074F}, // Syriac
  5609. {begin: 0x0780, end: 0x07BF}, // Thaana
  5610. {begin: 0x0D80, end: 0x0DFF}, // Sinhala
  5611. {begin: 0x1000, end: 0x109F}, // Myanmar
  5612. {begin: 0x1200, end: 0x137F}, // Ethiopic
  5613. {begin: 0x13A0, end: 0x13FF}, // Cherokee
  5614. {begin: 0x1400, end: 0x167F}, // Unified Canadian Aboriginal Syllabics
  5615. {begin: 0x1680, end: 0x169F}, // Ogham
  5616. {begin: 0x16A0, end: 0x16FF}, // Runic
  5617. {begin: 0x1780, end: 0x17FF}, // Khmer
  5618. {begin: 0x1800, end: 0x18AF}, // Mongolian
  5619. {begin: 0x2800, end: 0x28FF}, // Braille Patterns
  5620. {begin: 0xA000, end: 0xA48F}, // Yi Syllables
  5621. {begin: 0x1700, end: 0x171F}, // Tagalog
  5622. {begin: 0x10300, end: 0x1032F}, // Old Italic
  5623. {begin: 0x10330, end: 0x1034F}, // Gothic
  5624. {begin: 0x10400, end: 0x1044F}, // Deseret
  5625. {begin: 0x1D000, end: 0x1D0FF}, // Byzantine Musical Symbols
  5626. {begin: 0x1D400, end: 0x1D7FF}, // Mathematical Alphanumeric Symbols
  5627. {begin: 0xFF000, end: 0xFFFFD}, // Private Use (plane 15)
  5628. {begin: 0xFE00, end: 0xFE0F}, // Variation Selectors
  5629. {begin: 0xE0000, end: 0xE007F}, // Tags
  5630. {begin: 0x1900, end: 0x194F}, // Limbu
  5631. {begin: 0x1950, end: 0x197F}, // Tai Le
  5632. {begin: 0x1980, end: 0x19DF}, // New Tai Lue
  5633. {begin: 0x1A00, end: 0x1A1F}, // Buginese
  5634. {begin: 0x2C00, end: 0x2C5F}, // Glagolitic
  5635. {begin: 0x2D30, end: 0x2D7F}, // Tifinagh
  5636. {begin: 0x4DC0, end: 0x4DFF}, // Yijing Hexagram Symbols
  5637. {begin: 0xA800, end: 0xA82F}, // Syloti Nagri
  5638. {begin: 0x10000, end: 0x1007F}, // Linear B Syllabary
  5639. {begin: 0x10140, end: 0x1018F}, // Ancient Greek Numbers
  5640. {begin: 0x10380, end: 0x1039F}, // Ugaritic
  5641. {begin: 0x103A0, end: 0x103DF}, // Old Persian
  5642. {begin: 0x10450, end: 0x1047F}, // Shavian
  5643. {begin: 0x10480, end: 0x104AF}, // Osmanya
  5644. {begin: 0x10800, end: 0x1083F}, // Cypriot Syllabary
  5645. {begin: 0x10A00, end: 0x10A5F}, // Kharoshthi
  5646. {begin: 0x1D300, end: 0x1D35F}, // Tai Xuan Jing Symbols
  5647. {begin: 0x12000, end: 0x123FF}, // Cuneiform
  5648. {begin: 0x1D360, end: 0x1D37F}, // Counting Rod Numerals
  5649. {begin: 0x1B80, end: 0x1BBF}, // Sundanese
  5650. {begin: 0x1C00, end: 0x1C4F}, // Lepcha
  5651. {begin: 0x1C50, end: 0x1C7F}, // Ol Chiki
  5652. {begin: 0xA880, end: 0xA8DF}, // Saurashtra
  5653. {begin: 0xA900, end: 0xA92F}, // Kayah Li
  5654. {begin: 0xA930, end: 0xA95F}, // Rejang
  5655. {begin: 0xAA00, end: 0xAA5F}, // Cham
  5656. {begin: 0x10190, end: 0x101CF}, // Ancient Symbols
  5657. {begin: 0x101D0, end: 0x101FF}, // Phaistos Disc
  5658. {begin: 0x102A0, end: 0x102DF}, // Carian
  5659. {begin: 0x1F030, end: 0x1F09F} // Domino Tiles
  5660. ];
  5661. function getUnicodeRange(unicode) {
  5662. for (var i = 0; i < unicodeRanges.length; i += 1) {
  5663. var range = unicodeRanges[i];
  5664. if (unicode >= range.begin && unicode < range.end) {
  5665. return i;
  5666. }
  5667. }
  5668. return -1;
  5669. }
  5670. // Parse the OS/2 and Windows metrics `OS/2` table
  5671. function parseOS2Table(data, start) {
  5672. var os2 = {};
  5673. var p = new parse.Parser(data, start);
  5674. os2.version = p.parseUShort();
  5675. os2.xAvgCharWidth = p.parseShort();
  5676. os2.usWeightClass = p.parseUShort();
  5677. os2.usWidthClass = p.parseUShort();
  5678. os2.fsType = p.parseUShort();
  5679. os2.ySubscriptXSize = p.parseShort();
  5680. os2.ySubscriptYSize = p.parseShort();
  5681. os2.ySubscriptXOffset = p.parseShort();
  5682. os2.ySubscriptYOffset = p.parseShort();
  5683. os2.ySuperscriptXSize = p.parseShort();
  5684. os2.ySuperscriptYSize = p.parseShort();
  5685. os2.ySuperscriptXOffset = p.parseShort();
  5686. os2.ySuperscriptYOffset = p.parseShort();
  5687. os2.yStrikeoutSize = p.parseShort();
  5688. os2.yStrikeoutPosition = p.parseShort();
  5689. os2.sFamilyClass = p.parseShort();
  5690. os2.panose = [];
  5691. for (var i = 0; i < 10; i++) {
  5692. os2.panose[i] = p.parseByte();
  5693. }
  5694. os2.ulUnicodeRange1 = p.parseULong();
  5695. os2.ulUnicodeRange2 = p.parseULong();
  5696. os2.ulUnicodeRange3 = p.parseULong();
  5697. os2.ulUnicodeRange4 = p.parseULong();
  5698. os2.achVendID = String.fromCharCode(p.parseByte(), p.parseByte(), p.parseByte(), p.parseByte());
  5699. os2.fsSelection = p.parseUShort();
  5700. os2.usFirstCharIndex = p.parseUShort();
  5701. os2.usLastCharIndex = p.parseUShort();
  5702. os2.sTypoAscender = p.parseShort();
  5703. os2.sTypoDescender = p.parseShort();
  5704. os2.sTypoLineGap = p.parseShort();
  5705. os2.usWinAscent = p.parseUShort();
  5706. os2.usWinDescent = p.parseUShort();
  5707. if (os2.version >= 1) {
  5708. os2.ulCodePageRange1 = p.parseULong();
  5709. os2.ulCodePageRange2 = p.parseULong();
  5710. }
  5711. if (os2.version >= 2) {
  5712. os2.sxHeight = p.parseShort();
  5713. os2.sCapHeight = p.parseShort();
  5714. os2.usDefaultChar = p.parseUShort();
  5715. os2.usBreakChar = p.parseUShort();
  5716. os2.usMaxContent = p.parseUShort();
  5717. }
  5718. return os2;
  5719. }
  5720. function makeOS2Table(options) {
  5721. return new table.Table('OS/2', [
  5722. {name: 'version', type: 'USHORT', value: 0x0003},
  5723. {name: 'xAvgCharWidth', type: 'SHORT', value: 0},
  5724. {name: 'usWeightClass', type: 'USHORT', value: 0},
  5725. {name: 'usWidthClass', type: 'USHORT', value: 0},
  5726. {name: 'fsType', type: 'USHORT', value: 0},
  5727. {name: 'ySubscriptXSize', type: 'SHORT', value: 650},
  5728. {name: 'ySubscriptYSize', type: 'SHORT', value: 699},
  5729. {name: 'ySubscriptXOffset', type: 'SHORT', value: 0},
  5730. {name: 'ySubscriptYOffset', type: 'SHORT', value: 140},
  5731. {name: 'ySuperscriptXSize', type: 'SHORT', value: 650},
  5732. {name: 'ySuperscriptYSize', type: 'SHORT', value: 699},
  5733. {name: 'ySuperscriptXOffset', type: 'SHORT', value: 0},
  5734. {name: 'ySuperscriptYOffset', type: 'SHORT', value: 479},
  5735. {name: 'yStrikeoutSize', type: 'SHORT', value: 49},
  5736. {name: 'yStrikeoutPosition', type: 'SHORT', value: 258},
  5737. {name: 'sFamilyClass', type: 'SHORT', value: 0},
  5738. {name: 'bFamilyType', type: 'BYTE', value: 0},
  5739. {name: 'bSerifStyle', type: 'BYTE', value: 0},
  5740. {name: 'bWeight', type: 'BYTE', value: 0},
  5741. {name: 'bProportion', type: 'BYTE', value: 0},
  5742. {name: 'bContrast', type: 'BYTE', value: 0},
  5743. {name: 'bStrokeVariation', type: 'BYTE', value: 0},
  5744. {name: 'bArmStyle', type: 'BYTE', value: 0},
  5745. {name: 'bLetterform', type: 'BYTE', value: 0},
  5746. {name: 'bMidline', type: 'BYTE', value: 0},
  5747. {name: 'bXHeight', type: 'BYTE', value: 0},
  5748. {name: 'ulUnicodeRange1', type: 'ULONG', value: 0},
  5749. {name: 'ulUnicodeRange2', type: 'ULONG', value: 0},
  5750. {name: 'ulUnicodeRange3', type: 'ULONG', value: 0},
  5751. {name: 'ulUnicodeRange4', type: 'ULONG', value: 0},
  5752. {name: 'achVendID', type: 'CHARARRAY', value: 'XXXX'},
  5753. {name: 'fsSelection', type: 'USHORT', value: 0},
  5754. {name: 'usFirstCharIndex', type: 'USHORT', value: 0},
  5755. {name: 'usLastCharIndex', type: 'USHORT', value: 0},
  5756. {name: 'sTypoAscender', type: 'SHORT', value: 0},
  5757. {name: 'sTypoDescender', type: 'SHORT', value: 0},
  5758. {name: 'sTypoLineGap', type: 'SHORT', value: 0},
  5759. {name: 'usWinAscent', type: 'USHORT', value: 0},
  5760. {name: 'usWinDescent', type: 'USHORT', value: 0},
  5761. {name: 'ulCodePageRange1', type: 'ULONG', value: 0},
  5762. {name: 'ulCodePageRange2', type: 'ULONG', value: 0},
  5763. {name: 'sxHeight', type: 'SHORT', value: 0},
  5764. {name: 'sCapHeight', type: 'SHORT', value: 0},
  5765. {name: 'usDefaultChar', type: 'USHORT', value: 0},
  5766. {name: 'usBreakChar', type: 'USHORT', value: 0},
  5767. {name: 'usMaxContext', type: 'USHORT', value: 0}
  5768. ], options);
  5769. }
  5770. var os2 = { parse: parseOS2Table, make: makeOS2Table, unicodeRanges: unicodeRanges, getUnicodeRange: getUnicodeRange };
  5771. // The `post` table stores additional PostScript information, such as glyph names.
  5772. // Parse the PostScript `post` table
  5773. function parsePostTable(data, start) {
  5774. var post = {};
  5775. var p = new parse.Parser(data, start);
  5776. post.version = p.parseVersion();
  5777. post.italicAngle = p.parseFixed();
  5778. post.underlinePosition = p.parseShort();
  5779. post.underlineThickness = p.parseShort();
  5780. post.isFixedPitch = p.parseULong();
  5781. post.minMemType42 = p.parseULong();
  5782. post.maxMemType42 = p.parseULong();
  5783. post.minMemType1 = p.parseULong();
  5784. post.maxMemType1 = p.parseULong();
  5785. switch (post.version) {
  5786. case 1:
  5787. post.names = standardNames.slice();
  5788. break;
  5789. case 2:
  5790. post.numberOfGlyphs = p.parseUShort();
  5791. post.glyphNameIndex = new Array(post.numberOfGlyphs);
  5792. for (var i = 0; i < post.numberOfGlyphs; i++) {
  5793. post.glyphNameIndex[i] = p.parseUShort();
  5794. }
  5795. post.names = [];
  5796. for (var i$1 = 0; i$1 < post.numberOfGlyphs; i$1++) {
  5797. if (post.glyphNameIndex[i$1] >= standardNames.length) {
  5798. var nameLength = p.parseChar();
  5799. post.names.push(p.parseString(nameLength));
  5800. }
  5801. }
  5802. break;
  5803. case 2.5:
  5804. post.numberOfGlyphs = p.parseUShort();
  5805. post.offset = new Array(post.numberOfGlyphs);
  5806. for (var i$2 = 0; i$2 < post.numberOfGlyphs; i$2++) {
  5807. post.offset[i$2] = p.parseChar();
  5808. }
  5809. break;
  5810. }
  5811. return post;
  5812. }
  5813. function makePostTable() {
  5814. return new table.Table('post', [
  5815. {name: 'version', type: 'FIXED', value: 0x00030000},
  5816. {name: 'italicAngle', type: 'FIXED', value: 0},
  5817. {name: 'underlinePosition', type: 'FWORD', value: 0},
  5818. {name: 'underlineThickness', type: 'FWORD', value: 0},
  5819. {name: 'isFixedPitch', type: 'ULONG', value: 0},
  5820. {name: 'minMemType42', type: 'ULONG', value: 0},
  5821. {name: 'maxMemType42', type: 'ULONG', value: 0},
  5822. {name: 'minMemType1', type: 'ULONG', value: 0},
  5823. {name: 'maxMemType1', type: 'ULONG', value: 0}
  5824. ]);
  5825. }
  5826. var post = { parse: parsePostTable, make: makePostTable };
  5827. // The `GSUB` table contains ligatures, among other things.
  5828. var subtableParsers = new Array(9); // subtableParsers[0] is unused
  5829. // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#SS
  5830. subtableParsers[1] = function parseLookup1() {
  5831. var start = this.offset + this.relativeOffset;
  5832. var substFormat = this.parseUShort();
  5833. if (substFormat === 1) {
  5834. return {
  5835. substFormat: 1,
  5836. coverage: this.parsePointer(Parser.coverage),
  5837. deltaGlyphId: this.parseUShort()
  5838. };
  5839. } else if (substFormat === 2) {
  5840. return {
  5841. substFormat: 2,
  5842. coverage: this.parsePointer(Parser.coverage),
  5843. substitute: this.parseOffset16List()
  5844. };
  5845. }
  5846. check.assert(false, '0x' + start.toString(16) + ': lookup type 1 format must be 1 or 2.');
  5847. };
  5848. // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#MS
  5849. subtableParsers[2] = function parseLookup2() {
  5850. var substFormat = this.parseUShort();
  5851. check.argument(substFormat === 1, 'GSUB Multiple Substitution Subtable identifier-format must be 1');
  5852. return {
  5853. substFormat: substFormat,
  5854. coverage: this.parsePointer(Parser.coverage),
  5855. sequences: this.parseListOfLists()
  5856. };
  5857. };
  5858. // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#AS
  5859. subtableParsers[3] = function parseLookup3() {
  5860. var substFormat = this.parseUShort();
  5861. check.argument(substFormat === 1, 'GSUB Alternate Substitution Subtable identifier-format must be 1');
  5862. return {
  5863. substFormat: substFormat,
  5864. coverage: this.parsePointer(Parser.coverage),
  5865. alternateSets: this.parseListOfLists()
  5866. };
  5867. };
  5868. // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#LS
  5869. subtableParsers[4] = function parseLookup4() {
  5870. var substFormat = this.parseUShort();
  5871. check.argument(substFormat === 1, 'GSUB ligature table identifier-format must be 1');
  5872. return {
  5873. substFormat: substFormat,
  5874. coverage: this.parsePointer(Parser.coverage),
  5875. ligatureSets: this.parseListOfLists(function() {
  5876. return {
  5877. ligGlyph: this.parseUShort(),
  5878. components: this.parseUShortList(this.parseUShort() - 1)
  5879. };
  5880. })
  5881. };
  5882. };
  5883. var lookupRecordDesc = {
  5884. sequenceIndex: Parser.uShort,
  5885. lookupListIndex: Parser.uShort
  5886. };
  5887. // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#CSF
  5888. subtableParsers[5] = function parseLookup5() {
  5889. var start = this.offset + this.relativeOffset;
  5890. var substFormat = this.parseUShort();
  5891. if (substFormat === 1) {
  5892. return {
  5893. substFormat: substFormat,
  5894. coverage: this.parsePointer(Parser.coverage),
  5895. ruleSets: this.parseListOfLists(function() {
  5896. var glyphCount = this.parseUShort();
  5897. var substCount = this.parseUShort();
  5898. return {
  5899. input: this.parseUShortList(glyphCount - 1),
  5900. lookupRecords: this.parseRecordList(substCount, lookupRecordDesc)
  5901. };
  5902. })
  5903. };
  5904. } else if (substFormat === 2) {
  5905. return {
  5906. substFormat: substFormat,
  5907. coverage: this.parsePointer(Parser.coverage),
  5908. classDef: this.parsePointer(Parser.classDef),
  5909. classSets: this.parseListOfLists(function() {
  5910. var glyphCount = this.parseUShort();
  5911. var substCount = this.parseUShort();
  5912. return {
  5913. classes: this.parseUShortList(glyphCount - 1),
  5914. lookupRecords: this.parseRecordList(substCount, lookupRecordDesc)
  5915. };
  5916. })
  5917. };
  5918. } else if (substFormat === 3) {
  5919. var glyphCount = this.parseUShort();
  5920. var substCount = this.parseUShort();
  5921. return {
  5922. substFormat: substFormat,
  5923. coverages: this.parseList(glyphCount, Parser.pointer(Parser.coverage)),
  5924. lookupRecords: this.parseRecordList(substCount, lookupRecordDesc)
  5925. };
  5926. }
  5927. check.assert(false, '0x' + start.toString(16) + ': lookup type 5 format must be 1, 2 or 3.');
  5928. };
  5929. // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#CC
  5930. subtableParsers[6] = function parseLookup6() {
  5931. var start = this.offset + this.relativeOffset;
  5932. var substFormat = this.parseUShort();
  5933. if (substFormat === 1) {
  5934. return {
  5935. substFormat: 1,
  5936. coverage: this.parsePointer(Parser.coverage),
  5937. chainRuleSets: this.parseListOfLists(function() {
  5938. return {
  5939. backtrack: this.parseUShortList(),
  5940. input: this.parseUShortList(this.parseShort() - 1),
  5941. lookahead: this.parseUShortList(),
  5942. lookupRecords: this.parseRecordList(lookupRecordDesc)
  5943. };
  5944. })
  5945. };
  5946. } else if (substFormat === 2) {
  5947. return {
  5948. substFormat: 2,
  5949. coverage: this.parsePointer(Parser.coverage),
  5950. backtrackClassDef: this.parsePointer(Parser.classDef),
  5951. inputClassDef: this.parsePointer(Parser.classDef),
  5952. lookaheadClassDef: this.parsePointer(Parser.classDef),
  5953. chainClassSet: this.parseListOfLists(function() {
  5954. return {
  5955. backtrack: this.parseUShortList(),
  5956. input: this.parseUShortList(this.parseShort() - 1),
  5957. lookahead: this.parseUShortList(),
  5958. lookupRecords: this.parseRecordList(lookupRecordDesc)
  5959. };
  5960. })
  5961. };
  5962. } else if (substFormat === 3) {
  5963. return {
  5964. substFormat: 3,
  5965. backtrackCoverage: this.parseList(Parser.pointer(Parser.coverage)),
  5966. inputCoverage: this.parseList(Parser.pointer(Parser.coverage)),
  5967. lookaheadCoverage: this.parseList(Parser.pointer(Parser.coverage)),
  5968. lookupRecords: this.parseRecordList(lookupRecordDesc)
  5969. };
  5970. }
  5971. check.assert(false, '0x' + start.toString(16) + ': lookup type 6 format must be 1, 2 or 3.');
  5972. };
  5973. // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#ES
  5974. subtableParsers[7] = function parseLookup7() {
  5975. // Extension Substitution subtable
  5976. var substFormat = this.parseUShort();
  5977. check.argument(substFormat === 1, 'GSUB Extension Substitution subtable identifier-format must be 1');
  5978. var extensionLookupType = this.parseUShort();
  5979. var extensionParser = new Parser(this.data, this.offset + this.parseULong());
  5980. return {
  5981. substFormat: 1,
  5982. lookupType: extensionLookupType,
  5983. extension: subtableParsers[extensionLookupType].call(extensionParser)
  5984. };
  5985. };
  5986. // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#RCCS
  5987. subtableParsers[8] = function parseLookup8() {
  5988. var substFormat = this.parseUShort();
  5989. check.argument(substFormat === 1, 'GSUB Reverse Chaining Contextual Single Substitution Subtable identifier-format must be 1');
  5990. return {
  5991. substFormat: substFormat,
  5992. coverage: this.parsePointer(Parser.coverage),
  5993. backtrackCoverage: this.parseList(Parser.pointer(Parser.coverage)),
  5994. lookaheadCoverage: this.parseList(Parser.pointer(Parser.coverage)),
  5995. substitutes: this.parseUShortList()
  5996. };
  5997. };
  5998. // https://www.microsoft.com/typography/OTSPEC/gsub.htm
  5999. function parseGsubTable(data, start) {
  6000. start = start || 0;
  6001. var p = new Parser(data, start);
  6002. var tableVersion = p.parseVersion(1);
  6003. check.argument(tableVersion === 1 || tableVersion === 1.1, 'Unsupported GSUB table version.');
  6004. if (tableVersion === 1) {
  6005. return {
  6006. version: tableVersion,
  6007. scripts: p.parseScriptList(),
  6008. features: p.parseFeatureList(),
  6009. lookups: p.parseLookupList(subtableParsers)
  6010. };
  6011. } else {
  6012. return {
  6013. version: tableVersion,
  6014. scripts: p.parseScriptList(),
  6015. features: p.parseFeatureList(),
  6016. lookups: p.parseLookupList(subtableParsers),
  6017. variations: p.parseFeatureVariationsList()
  6018. };
  6019. }
  6020. }
  6021. // GSUB Writing //////////////////////////////////////////////
  6022. var subtableMakers = new Array(9);
  6023. subtableMakers[1] = function makeLookup1(subtable) {
  6024. if (subtable.substFormat === 1) {
  6025. return new table.Table('substitutionTable', [
  6026. {name: 'substFormat', type: 'USHORT', value: 1},
  6027. {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)},
  6028. {name: 'deltaGlyphID', type: 'USHORT', value: subtable.deltaGlyphId}
  6029. ]);
  6030. } else {
  6031. return new table.Table('substitutionTable', [
  6032. {name: 'substFormat', type: 'USHORT', value: 2},
  6033. {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)}
  6034. ].concat(table.ushortList('substitute', subtable.substitute)));
  6035. }
  6036. };
  6037. subtableMakers[2] = function makeLookup2(subtable) {
  6038. check.assert(subtable.substFormat === 1, 'Lookup type 2 substFormat must be 1.');
  6039. return new table.Table('substitutionTable', [
  6040. {name: 'substFormat', type: 'USHORT', value: 1},
  6041. {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)}
  6042. ].concat(table.tableList('seqSet', subtable.sequences, function(sequenceSet) {
  6043. return new table.Table('sequenceSetTable', table.ushortList('sequence', sequenceSet));
  6044. })));
  6045. };
  6046. subtableMakers[3] = function makeLookup3(subtable) {
  6047. check.assert(subtable.substFormat === 1, 'Lookup type 3 substFormat must be 1.');
  6048. return new table.Table('substitutionTable', [
  6049. {name: 'substFormat', type: 'USHORT', value: 1},
  6050. {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)}
  6051. ].concat(table.tableList('altSet', subtable.alternateSets, function(alternateSet) {
  6052. return new table.Table('alternateSetTable', table.ushortList('alternate', alternateSet));
  6053. })));
  6054. };
  6055. subtableMakers[4] = function makeLookup4(subtable) {
  6056. check.assert(subtable.substFormat === 1, 'Lookup type 4 substFormat must be 1.');
  6057. return new table.Table('substitutionTable', [
  6058. {name: 'substFormat', type: 'USHORT', value: 1},
  6059. {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)}
  6060. ].concat(table.tableList('ligSet', subtable.ligatureSets, function(ligatureSet) {
  6061. return new table.Table('ligatureSetTable', table.tableList('ligature', ligatureSet, function(ligature) {
  6062. return new table.Table('ligatureTable',
  6063. [{name: 'ligGlyph', type: 'USHORT', value: ligature.ligGlyph}]
  6064. .concat(table.ushortList('component', ligature.components, ligature.components.length + 1))
  6065. );
  6066. }));
  6067. })));
  6068. };
  6069. subtableMakers[6] = function makeLookup6(subtable) {
  6070. if (subtable.substFormat === 1) {
  6071. var returnTable = new table.Table('chainContextTable', [
  6072. {name: 'substFormat', type: 'USHORT', value: subtable.substFormat},
  6073. {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)}
  6074. ].concat(table.tableList('chainRuleSet', subtable.chainRuleSets, function(chainRuleSet) {
  6075. return new table.Table('chainRuleSetTable', table.tableList('chainRule', chainRuleSet, function(chainRule) {
  6076. var tableData = table.ushortList('backtrackGlyph', chainRule.backtrack, chainRule.backtrack.length)
  6077. .concat(table.ushortList('inputGlyph', chainRule.input, chainRule.input.length + 1))
  6078. .concat(table.ushortList('lookaheadGlyph', chainRule.lookahead, chainRule.lookahead.length))
  6079. .concat(table.ushortList('substitution', [], chainRule.lookupRecords.length));
  6080. chainRule.lookupRecords.forEach(function (record, i) {
  6081. tableData = tableData
  6082. .concat({name: 'sequenceIndex' + i, type: 'USHORT', value: record.sequenceIndex})
  6083. .concat({name: 'lookupListIndex' + i, type: 'USHORT', value: record.lookupListIndex});
  6084. });
  6085. return new table.Table('chainRuleTable', tableData);
  6086. }));
  6087. })));
  6088. return returnTable;
  6089. } else if (subtable.substFormat === 2) {
  6090. check.assert(false, 'lookup type 6 format 2 is not yet supported.');
  6091. } else if (subtable.substFormat === 3) {
  6092. var tableData = [
  6093. {name: 'substFormat', type: 'USHORT', value: subtable.substFormat} ];
  6094. tableData.push({name: 'backtrackGlyphCount', type: 'USHORT', value: subtable.backtrackCoverage.length});
  6095. subtable.backtrackCoverage.forEach(function (coverage, i) {
  6096. tableData.push({name: 'backtrackCoverage' + i, type: 'TABLE', value: new table.Coverage(coverage)});
  6097. });
  6098. tableData.push({name: 'inputGlyphCount', type: 'USHORT', value: subtable.inputCoverage.length});
  6099. subtable.inputCoverage.forEach(function (coverage, i) {
  6100. tableData.push({name: 'inputCoverage' + i, type: 'TABLE', value: new table.Coverage(coverage)});
  6101. });
  6102. tableData.push({name: 'lookaheadGlyphCount', type: 'USHORT', value: subtable.lookaheadCoverage.length});
  6103. subtable.lookaheadCoverage.forEach(function (coverage, i) {
  6104. tableData.push({name: 'lookaheadCoverage' + i, type: 'TABLE', value: new table.Coverage(coverage)});
  6105. });
  6106. tableData.push({name: 'substitutionCount', type: 'USHORT', value: subtable.lookupRecords.length});
  6107. subtable.lookupRecords.forEach(function (record, i) {
  6108. tableData = tableData
  6109. .concat({name: 'sequenceIndex' + i, type: 'USHORT', value: record.sequenceIndex})
  6110. .concat({name: 'lookupListIndex' + i, type: 'USHORT', value: record.lookupListIndex});
  6111. });
  6112. var returnTable$1 = new table.Table('chainContextTable', tableData);
  6113. return returnTable$1;
  6114. }
  6115. check.assert(false, 'lookup type 6 format must be 1, 2 or 3.');
  6116. };
  6117. function makeGsubTable(gsub) {
  6118. return new table.Table('GSUB', [
  6119. {name: 'version', type: 'ULONG', value: 0x10000},
  6120. {name: 'scripts', type: 'TABLE', value: new table.ScriptList(gsub.scripts)},
  6121. {name: 'features', type: 'TABLE', value: new table.FeatureList(gsub.features)},
  6122. {name: 'lookups', type: 'TABLE', value: new table.LookupList(gsub.lookups, subtableMakers)}
  6123. ]);
  6124. }
  6125. var gsub = { parse: parseGsubTable, make: makeGsubTable };
  6126. // The `GPOS` table contains kerning pairs, among other things.
  6127. // Parse the metadata `meta` table.
  6128. // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6meta.html
  6129. function parseMetaTable(data, start) {
  6130. var p = new parse.Parser(data, start);
  6131. var tableVersion = p.parseULong();
  6132. check.argument(tableVersion === 1, 'Unsupported META table version.');
  6133. p.parseULong(); // flags - currently unused and set to 0
  6134. p.parseULong(); // tableOffset
  6135. var numDataMaps = p.parseULong();
  6136. var tags = {};
  6137. for (var i = 0; i < numDataMaps; i++) {
  6138. var tag = p.parseTag();
  6139. var dataOffset = p.parseULong();
  6140. var dataLength = p.parseULong();
  6141. var text = decode.UTF8(data, start + dataOffset, dataLength);
  6142. tags[tag] = text;
  6143. }
  6144. return tags;
  6145. }
  6146. function makeMetaTable(tags) {
  6147. var numTags = Object.keys(tags).length;
  6148. var stringPool = '';
  6149. var stringPoolOffset = 16 + numTags * 12;
  6150. var result = new table.Table('meta', [
  6151. {name: 'version', type: 'ULONG', value: 1},
  6152. {name: 'flags', type: 'ULONG', value: 0},
  6153. {name: 'offset', type: 'ULONG', value: stringPoolOffset},
  6154. {name: 'numTags', type: 'ULONG', value: numTags}
  6155. ]);
  6156. for (var tag in tags) {
  6157. var pos = stringPool.length;
  6158. stringPool += tags[tag];
  6159. result.fields.push({name: 'tag ' + tag, type: 'TAG', value: tag});
  6160. result.fields.push({name: 'offset ' + tag, type: 'ULONG', value: stringPoolOffset + pos});
  6161. result.fields.push({name: 'length ' + tag, type: 'ULONG', value: tags[tag].length});
  6162. }
  6163. result.fields.push({name: 'stringPool', type: 'CHARARRAY', value: stringPool});
  6164. return result;
  6165. }
  6166. var meta = { parse: parseMetaTable, make: makeMetaTable };
  6167. // The `COLR` table adds support for multi-colored glyphs
  6168. function parseColrTable(data, start) {
  6169. var p = new Parser(data, start);
  6170. var version = p.parseUShort();
  6171. check.argument(version === 0x0000, 'Only COLRv0 supported.');
  6172. var numBaseGlyphRecords = p.parseUShort();
  6173. var baseGlyphRecordsOffset = p.parseOffset32();
  6174. var layerRecordsOffset = p.parseOffset32();
  6175. var numLayerRecords = p.parseUShort();
  6176. p.relativeOffset = baseGlyphRecordsOffset;
  6177. var baseGlyphRecords = p.parseRecordList(numBaseGlyphRecords, {
  6178. glyphID: Parser.uShort,
  6179. firstLayerIndex: Parser.uShort,
  6180. numLayers: Parser.uShort,
  6181. });
  6182. p.relativeOffset = layerRecordsOffset;
  6183. var layerRecords = p.parseRecordList(numLayerRecords, {
  6184. glyphID: Parser.uShort,
  6185. paletteIndex: Parser.uShort
  6186. });
  6187. return {
  6188. version: version,
  6189. baseGlyphRecords: baseGlyphRecords,
  6190. layerRecords: layerRecords,
  6191. };
  6192. }
  6193. function makeColrTable(ref) {
  6194. var version = ref.version; if ( version === void 0 ) version = 0x0000;
  6195. var baseGlyphRecords = ref.baseGlyphRecords; if ( baseGlyphRecords === void 0 ) baseGlyphRecords = [];
  6196. var layerRecords = ref.layerRecords; if ( layerRecords === void 0 ) layerRecords = [];
  6197. check.argument(version === 0x0000, 'Only COLRv0 supported.');
  6198. var baseGlyphRecordsOffset = 14;
  6199. var layerRecordsOffset = baseGlyphRecordsOffset + (baseGlyphRecords.length * 6);
  6200. return new table.Table('COLR', [
  6201. { name: 'version', type: 'USHORT', value: version },
  6202. { name: 'numBaseGlyphRecords', type: 'USHORT', value: baseGlyphRecords.length },
  6203. { name: 'baseGlyphRecordsOffset', type: 'ULONG', value: baseGlyphRecordsOffset },
  6204. { name: 'layerRecordsOffset', type: 'ULONG', value: layerRecordsOffset },
  6205. { name: 'numLayerRecords', type: 'USHORT', value: layerRecords.length } ].concat( baseGlyphRecords.map(function (glyph, i) { return [
  6206. { name: 'glyphID_' + i, type: 'USHORT', value: glyph.glyphID },
  6207. { name: 'firstLayerIndex_' + i, type: 'USHORT', value: glyph.firstLayerIndex },
  6208. { name: 'numLayers_' + i, type: 'USHORT', value: glyph.numLayers } ]; }).flat(),
  6209. layerRecords.map(function (layer, i) { return [
  6210. { name: 'LayerGlyphID_' + i, type: 'USHORT', value: layer.glyphID },
  6211. { name: 'paletteIndex_' + i, type: 'USHORT', value: layer.paletteIndex } ]; }).flat() ));
  6212. }
  6213. var colr = { parse: parseColrTable, make: makeColrTable };
  6214. // The `CPAL` define a contiguous list of colors (colorRecords)
  6215. // Parse the header `head` table
  6216. function parseCpalTable(data, start) {
  6217. var p = new Parser(data, start);
  6218. var version = p.parseShort();
  6219. var numPaletteEntries = p.parseShort();
  6220. var numPalettes = p.parseShort();
  6221. var numColorRecords = p.parseShort();
  6222. var colorRecordsArrayOffset = p.parseOffset32();
  6223. var colorRecordIndices = p.parseUShortList(numPalettes);
  6224. p.relativeOffset = colorRecordsArrayOffset;
  6225. var colorRecords = p.parseULongList(numColorRecords);
  6226. return {
  6227. version: version,
  6228. numPaletteEntries: numPaletteEntries,
  6229. colorRecords: colorRecords,
  6230. colorRecordIndices: colorRecordIndices,
  6231. };
  6232. }
  6233. function makeCpalTable(ref) {
  6234. var version = ref.version; if ( version === void 0 ) version = 0;
  6235. var numPaletteEntries = ref.numPaletteEntries; if ( numPaletteEntries === void 0 ) numPaletteEntries = 0;
  6236. var colorRecords = ref.colorRecords; if ( colorRecords === void 0 ) colorRecords = [];
  6237. var colorRecordIndices = ref.colorRecordIndices; if ( colorRecordIndices === void 0 ) colorRecordIndices = [0];
  6238. check.argument(version === 0, 'Only CPALv0 are supported.');
  6239. check.argument(colorRecords.length, 'No colorRecords given.');
  6240. check.argument(colorRecordIndices.length, 'No colorRecordIndices given.');
  6241. check.argument(!numPaletteEntries && colorRecordIndices.length == 1, 'Can\'t infer numPaletteEntries on multiple colorRecordIndices');
  6242. return new table.Table('CPAL', [
  6243. { name: 'version', type: 'USHORT', value: version },
  6244. { name: 'numPaletteEntries', type: 'USHORT', value: numPaletteEntries || colorRecords.length },
  6245. { name: 'numPalettes', type: 'USHORT', value: colorRecordIndices.length },
  6246. { name: 'numColorRecords', type: 'USHORT', value: colorRecords.length },
  6247. { name: 'colorRecordsArrayOffset', type: 'ULONG', value: 12 + 2 * colorRecordIndices.length } ].concat( colorRecordIndices.map(function (palette, i) { return ({ name: 'colorRecordIndices_' + i, type: 'USHORT', value: palette }); }),
  6248. colorRecords.map(function (color, i) { return ({ name: 'colorRecords_' + i, type: 'ULONG', value: color }); }) ));
  6249. }
  6250. var cpal = { parse: parseCpalTable, make: makeCpalTable };
  6251. // The `sfnt` wrapper provides organization for the tables in the font.
  6252. function log2(v) {
  6253. return Math.log(v) / Math.log(2) | 0;
  6254. }
  6255. function computeCheckSum(bytes) {
  6256. while (bytes.length % 4 !== 0) {
  6257. bytes.push(0);
  6258. }
  6259. var sum = 0;
  6260. for (var i = 0; i < bytes.length; i += 4) {
  6261. sum += (bytes[i] << 24) +
  6262. (bytes[i + 1] << 16) +
  6263. (bytes[i + 2] << 8) +
  6264. (bytes[i + 3]);
  6265. }
  6266. sum %= Math.pow(2, 32);
  6267. return sum;
  6268. }
  6269. function makeTableRecord(tag, checkSum, offset, length) {
  6270. return new table.Record('Table Record', [
  6271. {name: 'tag', type: 'TAG', value: tag !== undefined ? tag : ''},
  6272. {name: 'checkSum', type: 'ULONG', value: checkSum !== undefined ? checkSum : 0},
  6273. {name: 'offset', type: 'ULONG', value: offset !== undefined ? offset : 0},
  6274. {name: 'length', type: 'ULONG', value: length !== undefined ? length : 0}
  6275. ]);
  6276. }
  6277. function makeSfntTable(tables) {
  6278. var sfnt = new table.Table('sfnt', [
  6279. {name: 'version', type: 'TAG', value: 'OTTO'},
  6280. {name: 'numTables', type: 'USHORT', value: 0},
  6281. {name: 'searchRange', type: 'USHORT', value: 0},
  6282. {name: 'entrySelector', type: 'USHORT', value: 0},
  6283. {name: 'rangeShift', type: 'USHORT', value: 0}
  6284. ]);
  6285. sfnt.tables = tables;
  6286. sfnt.numTables = tables.length;
  6287. var highestPowerOf2 = Math.pow(2, log2(sfnt.numTables));
  6288. sfnt.searchRange = 16 * highestPowerOf2;
  6289. sfnt.entrySelector = log2(highestPowerOf2);
  6290. sfnt.rangeShift = sfnt.numTables * 16 - sfnt.searchRange;
  6291. var recordFields = [];
  6292. var tableFields = [];
  6293. var offset = sfnt.sizeOf() + (makeTableRecord().sizeOf() * sfnt.numTables);
  6294. while (offset % 4 !== 0) {
  6295. offset += 1;
  6296. tableFields.push({name: 'padding', type: 'BYTE', value: 0});
  6297. }
  6298. for (var i = 0; i < tables.length; i += 1) {
  6299. var t = tables[i];
  6300. check.argument(t.tableName.length === 4, 'Table name' + t.tableName + ' is invalid.');
  6301. var tableLength = t.sizeOf();
  6302. var tableRecord = makeTableRecord(t.tableName, computeCheckSum(t.encode()), offset, tableLength);
  6303. recordFields.push({name: tableRecord.tag + ' Table Record', type: 'RECORD', value: tableRecord});
  6304. tableFields.push({name: t.tableName + ' table', type: 'RECORD', value: t});
  6305. offset += tableLength;
  6306. check.argument(!isNaN(offset), 'Something went wrong calculating the offset.');
  6307. while (offset % 4 !== 0) {
  6308. offset += 1;
  6309. tableFields.push({name: 'padding', type: 'BYTE', value: 0});
  6310. }
  6311. }
  6312. // Table records need to be sorted alphabetically.
  6313. recordFields.sort(function(r1, r2) {
  6314. if (r1.value.tag > r2.value.tag) {
  6315. return 1;
  6316. } else {
  6317. return -1;
  6318. }
  6319. });
  6320. sfnt.fields = sfnt.fields.concat(recordFields);
  6321. sfnt.fields = sfnt.fields.concat(tableFields);
  6322. return sfnt;
  6323. }
  6324. // Get the metrics for a character. If the string has more than one character
  6325. // this function returns metrics for the first available character.
  6326. // You can provide optional fallback metrics if no characters are available.
  6327. function metricsForChar(font, chars, notFoundMetrics) {
  6328. for (var i = 0; i < chars.length; i += 1) {
  6329. var glyphIndex = font.charToGlyphIndex(chars[i]);
  6330. if (glyphIndex > 0) {
  6331. var glyph = font.glyphs.get(glyphIndex);
  6332. return glyph.getMetrics();
  6333. }
  6334. }
  6335. return notFoundMetrics;
  6336. }
  6337. function average(vs) {
  6338. var sum = 0;
  6339. for (var i = 0; i < vs.length; i += 1) {
  6340. sum += vs[i];
  6341. }
  6342. return sum / vs.length;
  6343. }
  6344. // Convert the font object to a SFNT data structure.
  6345. // This structure contains all the necessary tables and metadata to create a binary OTF file.
  6346. function fontToSfntTable(font) {
  6347. var xMins = [];
  6348. var yMins = [];
  6349. var xMaxs = [];
  6350. var yMaxs = [];
  6351. var advanceWidths = [];
  6352. var leftSideBearings = [];
  6353. var rightSideBearings = [];
  6354. var firstCharIndex;
  6355. var lastCharIndex = 0;
  6356. var ulUnicodeRange1 = 0;
  6357. var ulUnicodeRange2 = 0;
  6358. var ulUnicodeRange3 = 0;
  6359. var ulUnicodeRange4 = 0;
  6360. for (var i = 0; i < font.glyphs.length; i += 1) {
  6361. var glyph = font.glyphs.get(i);
  6362. var unicode = glyph.unicode | 0;
  6363. if (isNaN(glyph.advanceWidth)) {
  6364. throw new Error('Glyph ' + glyph.name + ' (' + i + '): advanceWidth is not a number.');
  6365. }
  6366. if (firstCharIndex > unicode || firstCharIndex === undefined) {
  6367. // ignore .notdef char
  6368. if (unicode > 0) {
  6369. firstCharIndex = unicode;
  6370. }
  6371. }
  6372. if (lastCharIndex < unicode) {
  6373. lastCharIndex = unicode;
  6374. }
  6375. var position = os2.getUnicodeRange(unicode);
  6376. if (position < 32) {
  6377. ulUnicodeRange1 |= 1 << position;
  6378. } else if (position < 64) {
  6379. ulUnicodeRange2 |= 1 << position - 32;
  6380. } else if (position < 96) {
  6381. ulUnicodeRange3 |= 1 << position - 64;
  6382. } else if (position < 123) {
  6383. ulUnicodeRange4 |= 1 << position - 96;
  6384. } else {
  6385. throw new Error('Unicode ranges bits > 123 are reserved for internal usage');
  6386. }
  6387. // Skip non-important characters.
  6388. if (glyph.name === '.notdef') { continue; }
  6389. var metrics = glyph.getMetrics();
  6390. xMins.push(metrics.xMin);
  6391. yMins.push(metrics.yMin);
  6392. xMaxs.push(metrics.xMax);
  6393. yMaxs.push(metrics.yMax);
  6394. leftSideBearings.push(metrics.leftSideBearing);
  6395. rightSideBearings.push(metrics.rightSideBearing);
  6396. advanceWidths.push(glyph.advanceWidth);
  6397. }
  6398. var globals = {
  6399. xMin: Math.min.apply(null, xMins),
  6400. yMin: Math.min.apply(null, yMins),
  6401. xMax: Math.max.apply(null, xMaxs),
  6402. yMax: Math.max.apply(null, yMaxs),
  6403. advanceWidthMax: Math.max.apply(null, advanceWidths),
  6404. advanceWidthAvg: average(advanceWidths),
  6405. minLeftSideBearing: Math.min.apply(null, leftSideBearings),
  6406. maxLeftSideBearing: Math.max.apply(null, leftSideBearings),
  6407. minRightSideBearing: Math.min.apply(null, rightSideBearings)
  6408. };
  6409. globals.ascender = font.ascender;
  6410. globals.descender = font.descender;
  6411. var headTable = head.make({
  6412. flags: 3, // 00000011 (baseline for font at y=0; left sidebearing point at x=0)
  6413. unitsPerEm: font.unitsPerEm,
  6414. xMin: globals.xMin,
  6415. yMin: globals.yMin,
  6416. xMax: globals.xMax,
  6417. yMax: globals.yMax,
  6418. lowestRecPPEM: 3,
  6419. createdTimestamp: font.createdTimestamp
  6420. });
  6421. var hheaTable = hhea.make({
  6422. ascender: globals.ascender,
  6423. descender: globals.descender,
  6424. advanceWidthMax: globals.advanceWidthMax,
  6425. minLeftSideBearing: globals.minLeftSideBearing,
  6426. minRightSideBearing: globals.minRightSideBearing,
  6427. xMaxExtent: globals.maxLeftSideBearing + (globals.xMax - globals.xMin),
  6428. numberOfHMetrics: font.glyphs.length
  6429. });
  6430. var maxpTable = maxp.make(font.glyphs.length);
  6431. var os2Table = os2.make(Object.assign({
  6432. xAvgCharWidth: Math.round(globals.advanceWidthAvg),
  6433. usFirstCharIndex: firstCharIndex,
  6434. usLastCharIndex: lastCharIndex,
  6435. ulUnicodeRange1: ulUnicodeRange1,
  6436. ulUnicodeRange2: ulUnicodeRange2,
  6437. ulUnicodeRange3: ulUnicodeRange3,
  6438. ulUnicodeRange4: ulUnicodeRange4,
  6439. // See http://typophile.com/node/13081 for more info on vertical metrics.
  6440. // We get metrics for typical characters (such as "x" for xHeight).
  6441. // We provide some fallback characters if characters are unavailable: their
  6442. // ordering was chosen experimentally.
  6443. sTypoAscender: globals.ascender,
  6444. sTypoDescender: globals.descender,
  6445. sTypoLineGap: 0,
  6446. usWinAscent: globals.yMax,
  6447. usWinDescent: Math.abs(globals.yMin),
  6448. ulCodePageRange1: 1, // FIXME: hard-code Latin 1 support for now
  6449. sxHeight: metricsForChar(font, 'xyvw', {yMax: Math.round(globals.ascender / 2)}).yMax,
  6450. sCapHeight: metricsForChar(font, 'HIKLEFJMNTZBDPRAGOQSUVWXY', globals).yMax,
  6451. usDefaultChar: font.hasChar(' ') ? 32 : 0, // Use space as the default character, if available.
  6452. usBreakChar: font.hasChar(' ') ? 32 : 0, // Use space as the break character, if available.
  6453. }, font.tables.os2));
  6454. var hmtxTable = hmtx.make(font.glyphs);
  6455. var cmapTable = cmap.make(font.glyphs);
  6456. var englishFamilyName = font.getEnglishName('fontFamily');
  6457. var englishStyleName = font.getEnglishName('fontSubfamily');
  6458. var englishFullName = englishFamilyName + ' ' + englishStyleName;
  6459. var postScriptName = font.getEnglishName('postScriptName');
  6460. if (!postScriptName) {
  6461. postScriptName = englishFamilyName.replace(/\s/g, '') + '-' + englishStyleName;
  6462. }
  6463. var names = {};
  6464. for (var n in font.names) {
  6465. names[n] = font.names[n];
  6466. }
  6467. if (!names.uniqueID) {
  6468. names.uniqueID = {en: font.getEnglishName('manufacturer') + ':' + englishFullName};
  6469. }
  6470. if (!names.postScriptName) {
  6471. names.postScriptName = {en: postScriptName};
  6472. }
  6473. if (!names.preferredFamily) {
  6474. names.preferredFamily = font.names.fontFamily;
  6475. }
  6476. if (!names.preferredSubfamily) {
  6477. names.preferredSubfamily = font.names.fontSubfamily;
  6478. }
  6479. var languageTags = [];
  6480. var nameTable = _name.make(names, languageTags);
  6481. var ltagTable = (languageTags.length > 0 ? ltag.make(languageTags) : undefined);
  6482. var postTable = post.make();
  6483. var cffTable = cff.make(font.glyphs, {
  6484. version: font.getEnglishName('version'),
  6485. fullName: englishFullName,
  6486. familyName: englishFamilyName,
  6487. weightName: englishStyleName,
  6488. postScriptName: postScriptName,
  6489. unitsPerEm: font.unitsPerEm,
  6490. fontBBox: [0, globals.yMin, globals.ascender, globals.advanceWidthMax]
  6491. });
  6492. var metaTable = (font.metas && Object.keys(font.metas).length > 0) ? meta.make(font.metas) : undefined;
  6493. // The order does not matter because makeSfntTable() will sort them.
  6494. var tables = [headTable, hheaTable, maxpTable, os2Table, nameTable, cmapTable, postTable, cffTable, hmtxTable];
  6495. if (ltagTable) {
  6496. tables.push(ltagTable);
  6497. }
  6498. // Optional tables
  6499. if (font.tables.gsub) {
  6500. tables.push(gsub.make(font.tables.gsub));
  6501. }
  6502. if (font.tables.cpal) {
  6503. tables.push(cpal.make(font.tables.cpal));
  6504. }
  6505. if (font.tables.colr) {
  6506. tables.push(colr.make(font.tables.colr));
  6507. }
  6508. if (metaTable) {
  6509. tables.push(metaTable);
  6510. }
  6511. var sfntTable = makeSfntTable(tables);
  6512. // Compute the font's checkSum and store it in head.checkSumAdjustment.
  6513. var bytes = sfntTable.encode();
  6514. var checkSum = computeCheckSum(bytes);
  6515. var tableFields = sfntTable.fields;
  6516. var checkSumAdjusted = false;
  6517. for (var i$1 = 0; i$1 < tableFields.length; i$1 += 1) {
  6518. if (tableFields[i$1].name === 'head table') {
  6519. tableFields[i$1].value.checkSumAdjustment = 0xB1B0AFBA - checkSum;
  6520. checkSumAdjusted = true;
  6521. break;
  6522. }
  6523. }
  6524. if (!checkSumAdjusted) {
  6525. throw new Error('Could not find head table with checkSum to adjust.');
  6526. }
  6527. return sfntTable;
  6528. }
  6529. var sfnt = { make: makeSfntTable, fontToTable: fontToSfntTable, computeCheckSum: computeCheckSum };
  6530. // The Layout object is the prototype of Substitution objects, and provides
  6531. function searchTag(arr, tag) {
  6532. /* jshint bitwise: false */
  6533. var imin = 0;
  6534. var imax = arr.length - 1;
  6535. while (imin <= imax) {
  6536. var imid = (imin + imax) >>> 1;
  6537. var val = arr[imid].tag;
  6538. if (val === tag) {
  6539. return imid;
  6540. } else if (val < tag) {
  6541. imin = imid + 1;
  6542. } else { imax = imid - 1; }
  6543. }
  6544. // Not found: return -1-insertion point
  6545. return -imin - 1;
  6546. }
  6547. function binSearch(arr, value) {
  6548. /* jshint bitwise: false */
  6549. var imin = 0;
  6550. var imax = arr.length - 1;
  6551. while (imin <= imax) {
  6552. var imid = (imin + imax) >>> 1;
  6553. var val = arr[imid];
  6554. if (val === value) {
  6555. return imid;
  6556. } else if (val < value) {
  6557. imin = imid + 1;
  6558. } else { imax = imid - 1; }
  6559. }
  6560. // Not found: return -1-insertion point
  6561. return -imin - 1;
  6562. }
  6563. // binary search in a list of ranges (coverage, class definition)
  6564. function searchRange(ranges, value) {
  6565. // jshint bitwise: false
  6566. var range;
  6567. var imin = 0;
  6568. var imax = ranges.length - 1;
  6569. while (imin <= imax) {
  6570. var imid = (imin + imax) >>> 1;
  6571. range = ranges[imid];
  6572. var start = range.start;
  6573. if (start === value) {
  6574. return range;
  6575. } else if (start < value) {
  6576. imin = imid + 1;
  6577. } else { imax = imid - 1; }
  6578. }
  6579. if (imin > 0) {
  6580. range = ranges[imin - 1];
  6581. if (value > range.end) { return 0; }
  6582. return range;
  6583. }
  6584. }
  6585. /**
  6586. * @exports opentype.Layout
  6587. * @class
  6588. */
  6589. function Layout(font, tableName) {
  6590. this.font = font;
  6591. this.tableName = tableName;
  6592. }
  6593. Layout.prototype = {
  6594. /**
  6595. * Binary search an object by "tag" property
  6596. * @instance
  6597. * @function searchTag
  6598. * @memberof opentype.Layout
  6599. * @param {Array} arr
  6600. * @param {string} tag
  6601. * @return {number}
  6602. */
  6603. searchTag: searchTag,
  6604. /**
  6605. * Binary search in a list of numbers
  6606. * @instance
  6607. * @function binSearch
  6608. * @memberof opentype.Layout
  6609. * @param {Array} arr
  6610. * @param {number} value
  6611. * @return {number}
  6612. */
  6613. binSearch: binSearch,
  6614. /**
  6615. * Get or create the Layout table (GSUB, GPOS etc).
  6616. * @param {boolean} create - Whether to create a new one.
  6617. * @return {Object} The GSUB or GPOS table.
  6618. */
  6619. getTable: function(create) {
  6620. var layout = this.font.tables[this.tableName];
  6621. if (!layout && create) {
  6622. layout = this.font.tables[this.tableName] = this.createDefaultTable();
  6623. }
  6624. return layout;
  6625. },
  6626. /**
  6627. * Returns all scripts in the substitution table.
  6628. * @instance
  6629. * @return {Array}
  6630. */
  6631. getScriptNames: function() {
  6632. var layout = this.getTable();
  6633. if (!layout) { return []; }
  6634. return layout.scripts.map(function(script) {
  6635. return script.tag;
  6636. });
  6637. },
  6638. /**
  6639. * Returns the best bet for a script name.
  6640. * Returns 'DFLT' if it exists.
  6641. * If not, returns 'latn' if it exists.
  6642. * If neither exist, returns undefined.
  6643. */
  6644. getDefaultScriptName: function() {
  6645. var layout = this.getTable();
  6646. if (!layout) { return; }
  6647. var hasLatn = false;
  6648. for (var i = 0; i < layout.scripts.length; i++) {
  6649. var name = layout.scripts[i].tag;
  6650. if (name === 'DFLT') { return name; }
  6651. if (name === 'latn') { hasLatn = true; }
  6652. }
  6653. if (hasLatn) { return 'latn'; }
  6654. },
  6655. /**
  6656. * Returns all LangSysRecords in the given script.
  6657. * @instance
  6658. * @param {string} [script='DFLT']
  6659. * @param {boolean} create - forces the creation of this script table if it doesn't exist.
  6660. * @return {Object} An object with tag and script properties.
  6661. */
  6662. getScriptTable: function(script, create) {
  6663. var layout = this.getTable(create);
  6664. if (layout) {
  6665. script = script || 'DFLT';
  6666. var scripts = layout.scripts;
  6667. var pos = searchTag(layout.scripts, script);
  6668. if (pos >= 0) {
  6669. return scripts[pos].script;
  6670. } else if (create) {
  6671. var scr = {
  6672. tag: script,
  6673. script: {
  6674. defaultLangSys: {reserved: 0, reqFeatureIndex: 0xffff, featureIndexes: []},
  6675. langSysRecords: []
  6676. }
  6677. };
  6678. scripts.splice(-1 - pos, 0, scr);
  6679. return scr.script;
  6680. }
  6681. }
  6682. },
  6683. /**
  6684. * Returns a language system table
  6685. * @instance
  6686. * @param {string} [script='DFLT']
  6687. * @param {string} [language='dlft']
  6688. * @param {boolean} create - forces the creation of this langSysTable if it doesn't exist.
  6689. * @return {Object}
  6690. */
  6691. getLangSysTable: function(script, language, create) {
  6692. var scriptTable = this.getScriptTable(script, create);
  6693. if (scriptTable) {
  6694. if (!language || language === 'dflt' || language === 'DFLT') {
  6695. return scriptTable.defaultLangSys;
  6696. }
  6697. var pos = searchTag(scriptTable.langSysRecords, language);
  6698. if (pos >= 0) {
  6699. return scriptTable.langSysRecords[pos].langSys;
  6700. } else if (create) {
  6701. var langSysRecord = {
  6702. tag: language,
  6703. langSys: {reserved: 0, reqFeatureIndex: 0xffff, featureIndexes: []}
  6704. };
  6705. scriptTable.langSysRecords.splice(-1 - pos, 0, langSysRecord);
  6706. return langSysRecord.langSys;
  6707. }
  6708. }
  6709. },
  6710. /**
  6711. * Get a specific feature table.
  6712. * @instance
  6713. * @param {string} [script='DFLT']
  6714. * @param {string} [language='dlft']
  6715. * @param {string} feature - One of the codes listed at https://www.microsoft.com/typography/OTSPEC/featurelist.htm
  6716. * @param {boolean} create - forces the creation of the feature table if it doesn't exist.
  6717. * @return {Object}
  6718. */
  6719. getFeatureTable: function(script, language, feature, create) {
  6720. var langSysTable = this.getLangSysTable(script, language, create);
  6721. if (langSysTable) {
  6722. var featureRecord;
  6723. var featIndexes = langSysTable.featureIndexes;
  6724. var allFeatures = this.font.tables[this.tableName].features;
  6725. // The FeatureIndex array of indices is in arbitrary order,
  6726. // even if allFeatures is sorted alphabetically by feature tag.
  6727. for (var i = 0; i < featIndexes.length; i++) {
  6728. featureRecord = allFeatures[featIndexes[i]];
  6729. if (featureRecord.tag === feature) {
  6730. return featureRecord.feature;
  6731. }
  6732. }
  6733. if (create) {
  6734. var index = allFeatures.length;
  6735. // Automatic ordering of features would require to shift feature indexes in the script list.
  6736. check.assert(index === 0 || feature >= allFeatures[index - 1].tag, 'Features must be added in alphabetical order.');
  6737. featureRecord = {
  6738. tag: feature,
  6739. feature: { params: 0, lookupListIndexes: [] }
  6740. };
  6741. allFeatures.push(featureRecord);
  6742. featIndexes.push(index);
  6743. return featureRecord.feature;
  6744. }
  6745. }
  6746. },
  6747. /**
  6748. * Get the lookup tables of a given type for a script/language/feature.
  6749. * @instance
  6750. * @param {string} [script='DFLT']
  6751. * @param {string} [language='dlft']
  6752. * @param {string} feature - 4-letter feature code
  6753. * @param {number} lookupType - 1 to 9
  6754. * @param {boolean} create - forces the creation of the lookup table if it doesn't exist, with no subtables.
  6755. * @return {Object[]}
  6756. */
  6757. getLookupTables: function(script, language, feature, lookupType, create) {
  6758. var featureTable = this.getFeatureTable(script, language, feature, create);
  6759. var tables = [];
  6760. if (featureTable) {
  6761. var lookupTable;
  6762. var lookupListIndexes = featureTable.lookupListIndexes;
  6763. var allLookups = this.font.tables[this.tableName].lookups;
  6764. // lookupListIndexes are in no particular order, so use naive search.
  6765. for (var i = 0; i < lookupListIndexes.length; i++) {
  6766. lookupTable = allLookups[lookupListIndexes[i]];
  6767. if (lookupTable.lookupType === lookupType) {
  6768. tables.push(lookupTable);
  6769. }
  6770. }
  6771. if (tables.length === 0 && create) {
  6772. lookupTable = {
  6773. lookupType: lookupType,
  6774. lookupFlag: 0,
  6775. subtables: [],
  6776. markFilteringSet: undefined
  6777. };
  6778. var index = allLookups.length;
  6779. allLookups.push(lookupTable);
  6780. lookupListIndexes.push(index);
  6781. return [lookupTable];
  6782. }
  6783. }
  6784. return tables;
  6785. },
  6786. /**
  6787. * Find a glyph in a class definition table
  6788. * https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#class-definition-table
  6789. * @param {object} classDefTable - an OpenType Layout class definition table
  6790. * @param {number} glyphIndex - the index of the glyph to find
  6791. * @returns {number} -1 if not found
  6792. */
  6793. getGlyphClass: function(classDefTable, glyphIndex) {
  6794. switch (classDefTable.format) {
  6795. case 1:
  6796. if (classDefTable.startGlyph <= glyphIndex && glyphIndex < classDefTable.startGlyph + classDefTable.classes.length) {
  6797. return classDefTable.classes[glyphIndex - classDefTable.startGlyph];
  6798. }
  6799. return 0;
  6800. case 2:
  6801. var range = searchRange(classDefTable.ranges, glyphIndex);
  6802. return range ? range.classId : 0;
  6803. }
  6804. },
  6805. /**
  6806. * Find a glyph in a coverage table
  6807. * https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#coverage-table
  6808. * @param {object} coverageTable - an OpenType Layout coverage table
  6809. * @param {number} glyphIndex - the index of the glyph to find
  6810. * @returns {number} -1 if not found
  6811. */
  6812. getCoverageIndex: function(coverageTable, glyphIndex) {
  6813. switch (coverageTable.format) {
  6814. case 1:
  6815. var index = binSearch(coverageTable.glyphs, glyphIndex);
  6816. return index >= 0 ? index : -1;
  6817. case 2:
  6818. var range = searchRange(coverageTable.ranges, glyphIndex);
  6819. return range ? range.index + glyphIndex - range.start : -1;
  6820. }
  6821. },
  6822. /**
  6823. * Returns the list of glyph indexes of a coverage table.
  6824. * Format 1: the list is stored raw
  6825. * Format 2: compact list as range records.
  6826. * @instance
  6827. * @param {Object} coverageTable
  6828. * @return {Array}
  6829. */
  6830. expandCoverage: function(coverageTable) {
  6831. if (coverageTable.format === 1) {
  6832. return coverageTable.glyphs;
  6833. } else {
  6834. var glyphs = [];
  6835. var ranges = coverageTable.ranges;
  6836. for (var i = 0; i < ranges.length; i++) {
  6837. var range = ranges[i];
  6838. var start = range.start;
  6839. var end = range.end;
  6840. for (var j = start; j <= end; j++) {
  6841. glyphs.push(j);
  6842. }
  6843. }
  6844. return glyphs;
  6845. }
  6846. }
  6847. };
  6848. // The Position object provides utility methods to manipulate
  6849. /**
  6850. * @exports opentype.Position
  6851. * @class
  6852. * @extends opentype.Layout
  6853. * @param {opentype.Font}
  6854. * @constructor
  6855. */
  6856. function Position(font) {
  6857. Layout.call(this, font, 'gpos');
  6858. }
  6859. Position.prototype = Layout.prototype;
  6860. /**
  6861. * Init some data for faster and easier access later.
  6862. */
  6863. Position.prototype.init = function() {
  6864. var script = this.getDefaultScriptName();
  6865. this.defaultKerningTables = this.getKerningTables(script);
  6866. };
  6867. /**
  6868. * Find a glyph pair in a list of lookup tables of type 2 and retrieve the xAdvance kerning value.
  6869. *
  6870. * @param {integer} leftIndex - left glyph index
  6871. * @param {integer} rightIndex - right glyph index
  6872. * @returns {integer}
  6873. */
  6874. Position.prototype.getKerningValue = function(kerningLookups, leftIndex, rightIndex) {
  6875. for (var i = 0; i < kerningLookups.length; i++) {
  6876. var subtables = kerningLookups[i].subtables;
  6877. for (var j = 0; j < subtables.length; j++) {
  6878. var subtable = subtables[j];
  6879. var covIndex = this.getCoverageIndex(subtable.coverage, leftIndex);
  6880. if (covIndex < 0) { continue; }
  6881. switch (subtable.posFormat) {
  6882. case 1:
  6883. // Search Pair Adjustment Positioning Format 1
  6884. var pairSet = subtable.pairSets[covIndex];
  6885. for (var k = 0; k < pairSet.length; k++) {
  6886. var pair = pairSet[k];
  6887. if (pair.secondGlyph === rightIndex) {
  6888. return pair.value1 && pair.value1.xAdvance || 0;
  6889. }
  6890. }
  6891. break; // left glyph found, not right glyph - try next subtable
  6892. case 2:
  6893. // Search Pair Adjustment Positioning Format 2
  6894. var class1 = this.getGlyphClass(subtable.classDef1, leftIndex);
  6895. var class2 = this.getGlyphClass(subtable.classDef2, rightIndex);
  6896. var pair$1 = subtable.classRecords[class1][class2];
  6897. return pair$1.value1 && pair$1.value1.xAdvance || 0;
  6898. }
  6899. }
  6900. }
  6901. return 0;
  6902. };
  6903. /**
  6904. * List all kerning lookup tables.
  6905. *
  6906. * @param {string} [script='DFLT'] - use font.position.getDefaultScriptName() for a better default value
  6907. * @param {string} [language='dflt']
  6908. * @return {object[]} The list of kerning lookup tables (may be empty), or undefined if there is no GPOS table (and we should use the kern table)
  6909. */
  6910. Position.prototype.getKerningTables = function(script, language) {
  6911. if (this.font.tables.gpos) {
  6912. return this.getLookupTables(script, language, 'kern', 2);
  6913. }
  6914. };
  6915. // The Substitution object provides utility methods to manipulate
  6916. /**
  6917. * @exports opentype.Substitution
  6918. * @class
  6919. * @extends opentype.Layout
  6920. * @param {opentype.Font}
  6921. * @constructor
  6922. */
  6923. function Substitution(font) {
  6924. Layout.call(this, font, 'gsub');
  6925. }
  6926. // Check if 2 arrays of primitives are equal.
  6927. function arraysEqual(ar1, ar2) {
  6928. var n = ar1.length;
  6929. if (n !== ar2.length) { return false; }
  6930. for (var i = 0; i < n; i++) {
  6931. if (ar1[i] !== ar2[i]) { return false; }
  6932. }
  6933. return true;
  6934. }
  6935. // Find the first subtable of a lookup table in a particular format.
  6936. function getSubstFormat(lookupTable, format, defaultSubtable) {
  6937. var subtables = lookupTable.subtables;
  6938. for (var i = 0; i < subtables.length; i++) {
  6939. var subtable = subtables[i];
  6940. if (subtable.substFormat === format) {
  6941. return subtable;
  6942. }
  6943. }
  6944. if (defaultSubtable) {
  6945. subtables.push(defaultSubtable);
  6946. return defaultSubtable;
  6947. }
  6948. return undefined;
  6949. }
  6950. Substitution.prototype = Layout.prototype;
  6951. /**
  6952. * Create a default GSUB table.
  6953. * @return {Object} gsub - The GSUB table.
  6954. */
  6955. Substitution.prototype.createDefaultTable = function() {
  6956. // Generate a default empty GSUB table with just a DFLT script and dflt lang sys.
  6957. return {
  6958. version: 1,
  6959. scripts: [{
  6960. tag: 'DFLT',
  6961. script: {
  6962. defaultLangSys: { reserved: 0, reqFeatureIndex: 0xffff, featureIndexes: [] },
  6963. langSysRecords: []
  6964. }
  6965. }],
  6966. features: [],
  6967. lookups: []
  6968. };
  6969. };
  6970. /**
  6971. * List all single substitutions (lookup type 1) for a given script, language, and feature.
  6972. * @param {string} [script='DFLT']
  6973. * @param {string} [language='dflt']
  6974. * @param {string} feature - 4-character feature name ('aalt', 'salt', 'ss01'...)
  6975. * @return {Array} substitutions - The list of substitutions.
  6976. */
  6977. Substitution.prototype.getSingle = function(feature, script, language) {
  6978. var substitutions = [];
  6979. var lookupTables = this.getLookupTables(script, language, feature, 1);
  6980. for (var idx = 0; idx < lookupTables.length; idx++) {
  6981. var subtables = lookupTables[idx].subtables;
  6982. for (var i = 0; i < subtables.length; i++) {
  6983. var subtable = subtables[i];
  6984. var glyphs = this.expandCoverage(subtable.coverage);
  6985. var j = (void 0);
  6986. if (subtable.substFormat === 1) {
  6987. var delta = subtable.deltaGlyphId;
  6988. for (j = 0; j < glyphs.length; j++) {
  6989. var glyph = glyphs[j];
  6990. substitutions.push({ sub: glyph, by: glyph + delta });
  6991. }
  6992. } else {
  6993. var substitute = subtable.substitute;
  6994. for (j = 0; j < glyphs.length; j++) {
  6995. substitutions.push({ sub: glyphs[j], by: substitute[j] });
  6996. }
  6997. }
  6998. }
  6999. }
  7000. return substitutions;
  7001. };
  7002. /**
  7003. * List all multiple substitutions (lookup type 2) for a given script, language, and feature.
  7004. * @param {string} [script='DFLT']
  7005. * @param {string} [language='dflt']
  7006. * @param {string} feature - 4-character feature name ('ccmp', 'stch')
  7007. * @return {Array} substitutions - The list of substitutions.
  7008. */
  7009. Substitution.prototype.getMultiple = function(feature, script, language) {
  7010. var substitutions = [];
  7011. var lookupTables = this.getLookupTables(script, language, feature, 2);
  7012. for (var idx = 0; idx < lookupTables.length; idx++) {
  7013. var subtables = lookupTables[idx].subtables;
  7014. for (var i = 0; i < subtables.length; i++) {
  7015. var subtable = subtables[i];
  7016. var glyphs = this.expandCoverage(subtable.coverage);
  7017. var j = (void 0);
  7018. for (j = 0; j < glyphs.length; j++) {
  7019. var glyph = glyphs[j];
  7020. var replacements = subtable.sequences[j];
  7021. substitutions.push({ sub: glyph, by: replacements });
  7022. }
  7023. }
  7024. }
  7025. return substitutions;
  7026. };
  7027. /**
  7028. * List all alternates (lookup type 3) for a given script, language, and feature.
  7029. * @param {string} [script='DFLT']
  7030. * @param {string} [language='dflt']
  7031. * @param {string} feature - 4-character feature name ('aalt', 'salt'...)
  7032. * @return {Array} alternates - The list of alternates
  7033. */
  7034. Substitution.prototype.getAlternates = function(feature, script, language) {
  7035. var alternates = [];
  7036. var lookupTables = this.getLookupTables(script, language, feature, 3);
  7037. for (var idx = 0; idx < lookupTables.length; idx++) {
  7038. var subtables = lookupTables[idx].subtables;
  7039. for (var i = 0; i < subtables.length; i++) {
  7040. var subtable = subtables[i];
  7041. var glyphs = this.expandCoverage(subtable.coverage);
  7042. var alternateSets = subtable.alternateSets;
  7043. for (var j = 0; j < glyphs.length; j++) {
  7044. alternates.push({ sub: glyphs[j], by: alternateSets[j] });
  7045. }
  7046. }
  7047. }
  7048. return alternates;
  7049. };
  7050. /**
  7051. * List all ligatures (lookup type 4) for a given script, language, and feature.
  7052. * The result is an array of ligature objects like { sub: [ids], by: id }
  7053. * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...)
  7054. * @param {string} [script='DFLT']
  7055. * @param {string} [language='dflt']
  7056. * @return {Array} ligatures - The list of ligatures.
  7057. */
  7058. Substitution.prototype.getLigatures = function(feature, script, language) {
  7059. var ligatures = [];
  7060. var lookupTables = this.getLookupTables(script, language, feature, 4);
  7061. for (var idx = 0; idx < lookupTables.length; idx++) {
  7062. var subtables = lookupTables[idx].subtables;
  7063. for (var i = 0; i < subtables.length; i++) {
  7064. var subtable = subtables[i];
  7065. var glyphs = this.expandCoverage(subtable.coverage);
  7066. var ligatureSets = subtable.ligatureSets;
  7067. for (var j = 0; j < glyphs.length; j++) {
  7068. var startGlyph = glyphs[j];
  7069. var ligSet = ligatureSets[j];
  7070. for (var k = 0; k < ligSet.length; k++) {
  7071. var lig = ligSet[k];
  7072. ligatures.push({
  7073. sub: [startGlyph].concat(lig.components),
  7074. by: lig.ligGlyph
  7075. });
  7076. }
  7077. }
  7078. }
  7079. }
  7080. return ligatures;
  7081. };
  7082. /**
  7083. * Add or modify a single substitution (lookup type 1)
  7084. * Format 2, more flexible, is always used.
  7085. * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...)
  7086. * @param {Object} substitution - { sub: id, by: id } (format 1 is not supported)
  7087. * @param {string} [script='DFLT']
  7088. * @param {string} [language='dflt']
  7089. */
  7090. Substitution.prototype.addSingle = function(feature, substitution, script, language) {
  7091. var lookupTable = this.getLookupTables(script, language, feature, 1, true)[0];
  7092. var subtable = getSubstFormat(lookupTable, 2, { // lookup type 1 subtable, format 2, coverage format 1
  7093. substFormat: 2,
  7094. coverage: {format: 1, glyphs: []},
  7095. substitute: []
  7096. });
  7097. check.assert(subtable.coverage.format === 1, 'Single: unable to modify coverage table format ' + subtable.coverage.format);
  7098. var coverageGlyph = substitution.sub;
  7099. var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph);
  7100. if (pos < 0) {
  7101. pos = -1 - pos;
  7102. subtable.coverage.glyphs.splice(pos, 0, coverageGlyph);
  7103. subtable.substitute.splice(pos, 0, 0);
  7104. }
  7105. subtable.substitute[pos] = substitution.by;
  7106. };
  7107. /**
  7108. * Add or modify a multiple substitution (lookup type 2)
  7109. * @param {string} feature - 4-letter feature name ('ccmp', 'stch')
  7110. * @param {Object} substitution - { sub: id, by: [id] } for format 2.
  7111. * @param {string} [script='DFLT']
  7112. * @param {string} [language='dflt']
  7113. */
  7114. Substitution.prototype.addMultiple = function(feature, substitution, script, language) {
  7115. check.assert(substitution.by instanceof Array && substitution.by.length > 1, 'Multiple: "by" must be an array of two or more ids');
  7116. var lookupTable = this.getLookupTables(script, language, feature, 2, true)[0];
  7117. var subtable = getSubstFormat(lookupTable, 1, { // lookup type 2 subtable, format 1, coverage format 1
  7118. substFormat: 1,
  7119. coverage: {format: 1, glyphs: []},
  7120. sequences: []
  7121. });
  7122. check.assert(subtable.coverage.format === 1, 'Multiple: unable to modify coverage table format ' + subtable.coverage.format);
  7123. var coverageGlyph = substitution.sub;
  7124. var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph);
  7125. if (pos < 0) {
  7126. pos = -1 - pos;
  7127. subtable.coverage.glyphs.splice(pos, 0, coverageGlyph);
  7128. subtable.sequences.splice(pos, 0, 0);
  7129. }
  7130. subtable.sequences[pos] = substitution.by;
  7131. };
  7132. /**
  7133. * Add or modify an alternate substitution (lookup type 3)
  7134. * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...)
  7135. * @param {Object} substitution - { sub: id, by: [ids] }
  7136. * @param {string} [script='DFLT']
  7137. * @param {string} [language='dflt']
  7138. */
  7139. Substitution.prototype.addAlternate = function(feature, substitution, script, language) {
  7140. var lookupTable = this.getLookupTables(script, language, feature, 3, true)[0];
  7141. var subtable = getSubstFormat(lookupTable, 1, { // lookup type 3 subtable, format 1, coverage format 1
  7142. substFormat: 1,
  7143. coverage: {format: 1, glyphs: []},
  7144. alternateSets: []
  7145. });
  7146. check.assert(subtable.coverage.format === 1, 'Alternate: unable to modify coverage table format ' + subtable.coverage.format);
  7147. var coverageGlyph = substitution.sub;
  7148. var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph);
  7149. if (pos < 0) {
  7150. pos = -1 - pos;
  7151. subtable.coverage.glyphs.splice(pos, 0, coverageGlyph);
  7152. subtable.alternateSets.splice(pos, 0, 0);
  7153. }
  7154. subtable.alternateSets[pos] = substitution.by;
  7155. };
  7156. /**
  7157. * Add a ligature (lookup type 4)
  7158. * Ligatures with more components must be stored ahead of those with fewer components in order to be found
  7159. * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...)
  7160. * @param {Object} ligature - { sub: [ids], by: id }
  7161. * @param {string} [script='DFLT']
  7162. * @param {string} [language='dflt']
  7163. */
  7164. Substitution.prototype.addLigature = function(feature, ligature, script, language) {
  7165. var lookupTable = this.getLookupTables(script, language, feature, 4, true)[0];
  7166. var subtable = lookupTable.subtables[0];
  7167. if (!subtable) {
  7168. subtable = { // lookup type 4 subtable, format 1, coverage format 1
  7169. substFormat: 1,
  7170. coverage: { format: 1, glyphs: [] },
  7171. ligatureSets: []
  7172. };
  7173. lookupTable.subtables[0] = subtable;
  7174. }
  7175. check.assert(subtable.coverage.format === 1, 'Ligature: unable to modify coverage table format ' + subtable.coverage.format);
  7176. var coverageGlyph = ligature.sub[0];
  7177. var ligComponents = ligature.sub.slice(1);
  7178. var ligatureTable = {
  7179. ligGlyph: ligature.by,
  7180. components: ligComponents
  7181. };
  7182. var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph);
  7183. if (pos >= 0) {
  7184. // ligatureSet already exists
  7185. var ligatureSet = subtable.ligatureSets[pos];
  7186. for (var i = 0; i < ligatureSet.length; i++) {
  7187. // If ligature already exists, return.
  7188. if (arraysEqual(ligatureSet[i].components, ligComponents)) {
  7189. return;
  7190. }
  7191. }
  7192. // ligature does not exist: add it.
  7193. ligatureSet.push(ligatureTable);
  7194. } else {
  7195. // Create a new ligatureSet and add coverage for the first glyph.
  7196. pos = -1 - pos;
  7197. subtable.coverage.glyphs.splice(pos, 0, coverageGlyph);
  7198. subtable.ligatureSets.splice(pos, 0, [ligatureTable]);
  7199. }
  7200. };
  7201. /**
  7202. * List all feature data for a given script and language.
  7203. * @param {string} feature - 4-letter feature name
  7204. * @param {string} [script='DFLT']
  7205. * @param {string} [language='dflt']
  7206. * @return {Array} substitutions - The list of substitutions.
  7207. */
  7208. Substitution.prototype.getFeature = function(feature, script, language) {
  7209. if (/ss\d\d/.test(feature)) {
  7210. // ss01 - ss20
  7211. return this.getSingle(feature, script, language);
  7212. }
  7213. switch (feature) {
  7214. case 'aalt':
  7215. case 'salt':
  7216. return this.getSingle(feature, script, language)
  7217. .concat(this.getAlternates(feature, script, language));
  7218. case 'dlig':
  7219. case 'liga':
  7220. case 'rlig':
  7221. return this.getLigatures(feature, script, language);
  7222. case 'ccmp':
  7223. return this.getMultiple(feature, script, language)
  7224. .concat(this.getLigatures(feature, script, language));
  7225. case 'stch':
  7226. return this.getMultiple(feature, script, language);
  7227. }
  7228. return undefined;
  7229. };
  7230. /**
  7231. * Add a substitution to a feature for a given script and language.
  7232. * @param {string} feature - 4-letter feature name
  7233. * @param {Object} sub - the substitution to add (an object like { sub: id or [ids], by: id or [ids] })
  7234. * @param {string} [script='DFLT']
  7235. * @param {string} [language='dflt']
  7236. */
  7237. Substitution.prototype.add = function(feature, sub, script, language) {
  7238. if (/ss\d\d/.test(feature)) {
  7239. // ss01 - ss20
  7240. return this.addSingle(feature, sub, script, language);
  7241. }
  7242. switch (feature) {
  7243. case 'aalt':
  7244. case 'salt':
  7245. if (typeof sub.by === 'number') {
  7246. return this.addSingle(feature, sub, script, language);
  7247. }
  7248. return this.addAlternate(feature, sub, script, language);
  7249. case 'dlig':
  7250. case 'liga':
  7251. case 'rlig':
  7252. return this.addLigature(feature, sub, script, language);
  7253. case 'ccmp':
  7254. if (sub.by instanceof Array) {
  7255. return this.addMultiple(feature, sub, script, language);
  7256. }
  7257. return this.addLigature(feature, sub, script, language);
  7258. }
  7259. return undefined;
  7260. };
  7261. function isBrowser() {
  7262. return typeof window !== 'undefined';
  7263. }
  7264. function nodeBufferToArrayBuffer(buffer) {
  7265. var ab = new ArrayBuffer(buffer.length);
  7266. var view = new Uint8Array(ab);
  7267. for (var i = 0; i < buffer.length; ++i) {
  7268. view[i] = buffer[i];
  7269. }
  7270. return ab;
  7271. }
  7272. function arrayBufferToNodeBuffer(ab) {
  7273. var buffer = new Buffer(ab.byteLength);
  7274. var view = new Uint8Array(ab);
  7275. for (var i = 0; i < buffer.length; ++i) {
  7276. buffer[i] = view[i];
  7277. }
  7278. return buffer;
  7279. }
  7280. function checkArgument(expression, message) {
  7281. if (!expression) {
  7282. throw message;
  7283. }
  7284. }
  7285. // The `glyf` table describes the glyphs in TrueType outline format.
  7286. // Parse the coordinate data for a glyph.
  7287. function parseGlyphCoordinate(p, flag, previousValue, shortVectorBitMask, sameBitMask) {
  7288. var v;
  7289. if ((flag & shortVectorBitMask) > 0) {
  7290. // The coordinate is 1 byte long.
  7291. v = p.parseByte();
  7292. // The `same` bit is re-used for short values to signify the sign of the value.
  7293. if ((flag & sameBitMask) === 0) {
  7294. v = -v;
  7295. }
  7296. v = previousValue + v;
  7297. } else {
  7298. // The coordinate is 2 bytes long.
  7299. // If the `same` bit is set, the coordinate is the same as the previous coordinate.
  7300. if ((flag & sameBitMask) > 0) {
  7301. v = previousValue;
  7302. } else {
  7303. // Parse the coordinate as a signed 16-bit delta value.
  7304. v = previousValue + p.parseShort();
  7305. }
  7306. }
  7307. return v;
  7308. }
  7309. // Parse a TrueType glyph.
  7310. function parseGlyph(glyph, data, start) {
  7311. var p = new parse.Parser(data, start);
  7312. glyph.numberOfContours = p.parseShort();
  7313. glyph._xMin = p.parseShort();
  7314. glyph._yMin = p.parseShort();
  7315. glyph._xMax = p.parseShort();
  7316. glyph._yMax = p.parseShort();
  7317. var flags;
  7318. var flag;
  7319. if (glyph.numberOfContours > 0) {
  7320. // This glyph is not a composite.
  7321. var endPointIndices = glyph.endPointIndices = [];
  7322. for (var i = 0; i < glyph.numberOfContours; i += 1) {
  7323. endPointIndices.push(p.parseUShort());
  7324. }
  7325. glyph.instructionLength = p.parseUShort();
  7326. glyph.instructions = [];
  7327. for (var i$1 = 0; i$1 < glyph.instructionLength; i$1 += 1) {
  7328. glyph.instructions.push(p.parseByte());
  7329. }
  7330. var numberOfCoordinates = endPointIndices[endPointIndices.length - 1] + 1;
  7331. flags = [];
  7332. for (var i$2 = 0; i$2 < numberOfCoordinates; i$2 += 1) {
  7333. flag = p.parseByte();
  7334. flags.push(flag);
  7335. // If bit 3 is set, we repeat this flag n times, where n is the next byte.
  7336. if ((flag & 8) > 0) {
  7337. var repeatCount = p.parseByte();
  7338. for (var j = 0; j < repeatCount; j += 1) {
  7339. flags.push(flag);
  7340. i$2 += 1;
  7341. }
  7342. }
  7343. }
  7344. check.argument(flags.length === numberOfCoordinates, 'Bad flags.');
  7345. if (endPointIndices.length > 0) {
  7346. var points = [];
  7347. var point;
  7348. // X/Y coordinates are relative to the previous point, except for the first point which is relative to 0,0.
  7349. if (numberOfCoordinates > 0) {
  7350. for (var i$3 = 0; i$3 < numberOfCoordinates; i$3 += 1) {
  7351. flag = flags[i$3];
  7352. point = {};
  7353. point.onCurve = !!(flag & 1);
  7354. point.lastPointOfContour = endPointIndices.indexOf(i$3) >= 0;
  7355. points.push(point);
  7356. }
  7357. var px = 0;
  7358. for (var i$4 = 0; i$4 < numberOfCoordinates; i$4 += 1) {
  7359. flag = flags[i$4];
  7360. point = points[i$4];
  7361. point.x = parseGlyphCoordinate(p, flag, px, 2, 16);
  7362. px = point.x;
  7363. }
  7364. var py = 0;
  7365. for (var i$5 = 0; i$5 < numberOfCoordinates; i$5 += 1) {
  7366. flag = flags[i$5];
  7367. point = points[i$5];
  7368. point.y = parseGlyphCoordinate(p, flag, py, 4, 32);
  7369. py = point.y;
  7370. }
  7371. }
  7372. glyph.points = points;
  7373. } else {
  7374. glyph.points = [];
  7375. }
  7376. } else if (glyph.numberOfContours === 0) {
  7377. glyph.points = [];
  7378. } else {
  7379. glyph.isComposite = true;
  7380. glyph.points = [];
  7381. glyph.components = [];
  7382. var moreComponents = true;
  7383. while (moreComponents) {
  7384. flags = p.parseUShort();
  7385. var component = {
  7386. glyphIndex: p.parseUShort(),
  7387. xScale: 1,
  7388. scale01: 0,
  7389. scale10: 0,
  7390. yScale: 1,
  7391. dx: 0,
  7392. dy: 0
  7393. };
  7394. if ((flags & 1) > 0) {
  7395. // The arguments are words
  7396. if ((flags & 2) > 0) {
  7397. // values are offset
  7398. component.dx = p.parseShort();
  7399. component.dy = p.parseShort();
  7400. } else {
  7401. // values are matched points
  7402. component.matchedPoints = [p.parseUShort(), p.parseUShort()];
  7403. }
  7404. } else {
  7405. // The arguments are bytes
  7406. if ((flags & 2) > 0) {
  7407. // values are offset
  7408. component.dx = p.parseChar();
  7409. component.dy = p.parseChar();
  7410. } else {
  7411. // values are matched points
  7412. component.matchedPoints = [p.parseByte(), p.parseByte()];
  7413. }
  7414. }
  7415. if ((flags & 8) > 0) {
  7416. // We have a scale
  7417. component.xScale = component.yScale = p.parseF2Dot14();
  7418. } else if ((flags & 64) > 0) {
  7419. // We have an X / Y scale
  7420. component.xScale = p.parseF2Dot14();
  7421. component.yScale = p.parseF2Dot14();
  7422. } else if ((flags & 128) > 0) {
  7423. // We have a 2x2 transformation
  7424. component.xScale = p.parseF2Dot14();
  7425. component.scale01 = p.parseF2Dot14();
  7426. component.scale10 = p.parseF2Dot14();
  7427. component.yScale = p.parseF2Dot14();
  7428. }
  7429. glyph.components.push(component);
  7430. moreComponents = !!(flags & 32);
  7431. }
  7432. if (flags & 0x100) {
  7433. // We have instructions
  7434. glyph.instructionLength = p.parseUShort();
  7435. glyph.instructions = [];
  7436. for (var i$6 = 0; i$6 < glyph.instructionLength; i$6 += 1) {
  7437. glyph.instructions.push(p.parseByte());
  7438. }
  7439. }
  7440. }
  7441. }
  7442. // Transform an array of points and return a new array.
  7443. function transformPoints(points, transform) {
  7444. var newPoints = [];
  7445. for (var i = 0; i < points.length; i += 1) {
  7446. var pt = points[i];
  7447. var newPt = {
  7448. x: transform.xScale * pt.x + transform.scale01 * pt.y + transform.dx,
  7449. y: transform.scale10 * pt.x + transform.yScale * pt.y + transform.dy,
  7450. onCurve: pt.onCurve,
  7451. lastPointOfContour: pt.lastPointOfContour
  7452. };
  7453. newPoints.push(newPt);
  7454. }
  7455. return newPoints;
  7456. }
  7457. function getContours(points) {
  7458. var contours = [];
  7459. var currentContour = [];
  7460. for (var i = 0; i < points.length; i += 1) {
  7461. var pt = points[i];
  7462. currentContour.push(pt);
  7463. if (pt.lastPointOfContour) {
  7464. contours.push(currentContour);
  7465. currentContour = [];
  7466. }
  7467. }
  7468. check.argument(currentContour.length === 0, 'There are still points left in the current contour.');
  7469. return contours;
  7470. }
  7471. // Convert the TrueType glyph outline to a Path.
  7472. function getPath(points) {
  7473. var p = new Path();
  7474. if (!points) {
  7475. return p;
  7476. }
  7477. var contours = getContours(points);
  7478. for (var contourIndex = 0; contourIndex < contours.length; ++contourIndex) {
  7479. var contour = contours[contourIndex];
  7480. var prev = null;
  7481. var curr = contour[contour.length - 1];
  7482. var next = contour[0];
  7483. if (curr.onCurve) {
  7484. p.moveTo(curr.x, curr.y);
  7485. } else {
  7486. if (next.onCurve) {
  7487. p.moveTo(next.x, next.y);
  7488. } else {
  7489. // If both first and last points are off-curve, start at their middle.
  7490. var start = {x: (curr.x + next.x) * 0.5, y: (curr.y + next.y) * 0.5};
  7491. p.moveTo(start.x, start.y);
  7492. }
  7493. }
  7494. for (var i = 0; i < contour.length; ++i) {
  7495. prev = curr;
  7496. curr = next;
  7497. next = contour[(i + 1) % contour.length];
  7498. if (curr.onCurve) {
  7499. // This is a straight line.
  7500. p.lineTo(curr.x, curr.y);
  7501. } else {
  7502. var prev2 = prev;
  7503. var next2 = next;
  7504. if (!prev.onCurve) {
  7505. prev2 = { x: (curr.x + prev.x) * 0.5, y: (curr.y + prev.y) * 0.5 };
  7506. }
  7507. if (!next.onCurve) {
  7508. next2 = { x: (curr.x + next.x) * 0.5, y: (curr.y + next.y) * 0.5 };
  7509. }
  7510. p.quadraticCurveTo(curr.x, curr.y, next2.x, next2.y);
  7511. }
  7512. }
  7513. p.closePath();
  7514. }
  7515. return p;
  7516. }
  7517. function buildPath(glyphs, glyph) {
  7518. if (glyph.isComposite) {
  7519. for (var j = 0; j < glyph.components.length; j += 1) {
  7520. var component = glyph.components[j];
  7521. var componentGlyph = glyphs.get(component.glyphIndex);
  7522. // Force the ttfGlyphLoader to parse the glyph.
  7523. componentGlyph.getPath();
  7524. if (componentGlyph.points) {
  7525. var transformedPoints = (void 0);
  7526. if (component.matchedPoints === undefined) {
  7527. // component positioned by offset
  7528. transformedPoints = transformPoints(componentGlyph.points, component);
  7529. } else {
  7530. // component positioned by matched points
  7531. if ((component.matchedPoints[0] > glyph.points.length - 1) ||
  7532. (component.matchedPoints[1] > componentGlyph.points.length - 1)) {
  7533. throw Error('Matched points out of range in ' + glyph.name);
  7534. }
  7535. var firstPt = glyph.points[component.matchedPoints[0]];
  7536. var secondPt = componentGlyph.points[component.matchedPoints[1]];
  7537. var transform = {
  7538. xScale: component.xScale, scale01: component.scale01,
  7539. scale10: component.scale10, yScale: component.yScale,
  7540. dx: 0, dy: 0
  7541. };
  7542. secondPt = transformPoints([secondPt], transform)[0];
  7543. transform.dx = firstPt.x - secondPt.x;
  7544. transform.dy = firstPt.y - secondPt.y;
  7545. transformedPoints = transformPoints(componentGlyph.points, transform);
  7546. }
  7547. glyph.points = glyph.points.concat(transformedPoints);
  7548. }
  7549. }
  7550. }
  7551. return getPath(glyph.points);
  7552. }
  7553. function parseGlyfTableAll(data, start, loca, font) {
  7554. var glyphs = new glyphset.GlyphSet(font);
  7555. // The last element of the loca table is invalid.
  7556. for (var i = 0; i < loca.length - 1; i += 1) {
  7557. var offset = loca[i];
  7558. var nextOffset = loca[i + 1];
  7559. if (offset !== nextOffset) {
  7560. glyphs.push(i, glyphset.ttfGlyphLoader(font, i, parseGlyph, data, start + offset, buildPath));
  7561. } else {
  7562. glyphs.push(i, glyphset.glyphLoader(font, i));
  7563. }
  7564. }
  7565. return glyphs;
  7566. }
  7567. function parseGlyfTableOnLowMemory(data, start, loca, font) {
  7568. var glyphs = new glyphset.GlyphSet(font);
  7569. font._push = function(i) {
  7570. var offset = loca[i];
  7571. var nextOffset = loca[i + 1];
  7572. if (offset !== nextOffset) {
  7573. glyphs.push(i, glyphset.ttfGlyphLoader(font, i, parseGlyph, data, start + offset, buildPath));
  7574. } else {
  7575. glyphs.push(i, glyphset.glyphLoader(font, i));
  7576. }
  7577. };
  7578. return glyphs;
  7579. }
  7580. // Parse all the glyphs according to the offsets from the `loca` table.
  7581. function parseGlyfTable(data, start, loca, font, opt) {
  7582. if (opt.lowMemory)
  7583. { return parseGlyfTableOnLowMemory(data, start, loca, font); }
  7584. else
  7585. { return parseGlyfTableAll(data, start, loca, font); }
  7586. }
  7587. var glyf = { getPath: getPath, parse: parseGlyfTable};
  7588. /* A TrueType font hinting interpreter.
  7589. *
  7590. * (c) 2017 Axel Kittenberger
  7591. *
  7592. * This interpreter has been implemented according to this documentation:
  7593. * https://developer.apple.com/fonts/TrueType-Reference-Manual/RM05/Chap5.html
  7594. *
  7595. * According to the documentation F24DOT6 values are used for pixels.
  7596. * That means calculation is 1/64 pixel accurate and uses integer operations.
  7597. * However, Javascript has floating point operations by default and only
  7598. * those are available. One could make a case to simulate the 1/64 accuracy
  7599. * exactly by truncating after every division operation
  7600. * (for example with << 0) to get pixel exactly results as other TrueType
  7601. * implementations. It may make sense since some fonts are pixel optimized
  7602. * by hand using DELTAP instructions. The current implementation doesn't
  7603. * and rather uses full floating point precision.
  7604. *
  7605. * xScale, yScale and rotation is currently ignored.
  7606. *
  7607. * A few non-trivial instructions are missing as I didn't encounter yet
  7608. * a font that used them to test a possible implementation.
  7609. *
  7610. * Some fonts seem to use undocumented features regarding the twilight zone.
  7611. * Only some of them are implemented as they were encountered.
  7612. *
  7613. * The exports.DEBUG statements are removed on the minified distribution file.
  7614. */
  7615. var instructionTable;
  7616. var exec;
  7617. var execGlyph;
  7618. var execComponent;
  7619. /*
  7620. * Creates a hinting object.
  7621. *
  7622. * There ought to be exactly one
  7623. * for each truetype font that is used for hinting.
  7624. */
  7625. function Hinting(font) {
  7626. // the font this hinting object is for
  7627. this.font = font;
  7628. this.getCommands = function (hPoints) {
  7629. return glyf.getPath(hPoints).commands;
  7630. };
  7631. // cached states
  7632. this._fpgmState =
  7633. this._prepState =
  7634. undefined;
  7635. // errorState
  7636. // 0 ... all okay
  7637. // 1 ... had an error in a glyf,
  7638. // continue working but stop spamming
  7639. // the console
  7640. // 2 ... error at prep, stop hinting at this ppem
  7641. // 3 ... error at fpeg, stop hinting for this font at all
  7642. this._errorState = 0;
  7643. }
  7644. /*
  7645. * Not rounding.
  7646. */
  7647. function roundOff(v) {
  7648. return v;
  7649. }
  7650. /*
  7651. * Rounding to grid.
  7652. */
  7653. function roundToGrid(v) {
  7654. //Rounding in TT is supposed to "symmetrical around zero"
  7655. return Math.sign(v) * Math.round(Math.abs(v));
  7656. }
  7657. /*
  7658. * Rounding to double grid.
  7659. */
  7660. function roundToDoubleGrid(v) {
  7661. return Math.sign(v) * Math.round(Math.abs(v * 2)) / 2;
  7662. }
  7663. /*
  7664. * Rounding to half grid.
  7665. */
  7666. function roundToHalfGrid(v) {
  7667. return Math.sign(v) * (Math.round(Math.abs(v) + 0.5) - 0.5);
  7668. }
  7669. /*
  7670. * Rounding to up to grid.
  7671. */
  7672. function roundUpToGrid(v) {
  7673. return Math.sign(v) * Math.ceil(Math.abs(v));
  7674. }
  7675. /*
  7676. * Rounding to down to grid.
  7677. */
  7678. function roundDownToGrid(v) {
  7679. return Math.sign(v) * Math.floor(Math.abs(v));
  7680. }
  7681. /*
  7682. * Super rounding.
  7683. */
  7684. var roundSuper = function (v) {
  7685. var period = this.srPeriod;
  7686. var phase = this.srPhase;
  7687. var threshold = this.srThreshold;
  7688. var sign = 1;
  7689. if (v < 0) {
  7690. v = -v;
  7691. sign = -1;
  7692. }
  7693. v += threshold - phase;
  7694. v = Math.trunc(v / period) * period;
  7695. v += phase;
  7696. // according to http://xgridfit.sourceforge.net/round.html
  7697. if (v < 0) { return phase * sign; }
  7698. return v * sign;
  7699. };
  7700. /*
  7701. * Unit vector of x-axis.
  7702. */
  7703. var xUnitVector = {
  7704. x: 1,
  7705. y: 0,
  7706. axis: 'x',
  7707. // Gets the projected distance between two points.
  7708. // o1/o2 ... if true, respective original position is used.
  7709. distance: function (p1, p2, o1, o2) {
  7710. return (o1 ? p1.xo : p1.x) - (o2 ? p2.xo : p2.x);
  7711. },
  7712. // Moves point p so the moved position has the same relative
  7713. // position to the moved positions of rp1 and rp2 than the
  7714. // original positions had.
  7715. //
  7716. // See APPENDIX on INTERPOLATE at the bottom of this file.
  7717. interpolate: function (p, rp1, rp2, pv) {
  7718. var do1;
  7719. var do2;
  7720. var doa1;
  7721. var doa2;
  7722. var dm1;
  7723. var dm2;
  7724. var dt;
  7725. if (!pv || pv === this) {
  7726. do1 = p.xo - rp1.xo;
  7727. do2 = p.xo - rp2.xo;
  7728. dm1 = rp1.x - rp1.xo;
  7729. dm2 = rp2.x - rp2.xo;
  7730. doa1 = Math.abs(do1);
  7731. doa2 = Math.abs(do2);
  7732. dt = doa1 + doa2;
  7733. if (dt === 0) {
  7734. p.x = p.xo + (dm1 + dm2) / 2;
  7735. return;
  7736. }
  7737. p.x = p.xo + (dm1 * doa2 + dm2 * doa1) / dt;
  7738. return;
  7739. }
  7740. do1 = pv.distance(p, rp1, true, true);
  7741. do2 = pv.distance(p, rp2, true, true);
  7742. dm1 = pv.distance(rp1, rp1, false, true);
  7743. dm2 = pv.distance(rp2, rp2, false, true);
  7744. doa1 = Math.abs(do1);
  7745. doa2 = Math.abs(do2);
  7746. dt = doa1 + doa2;
  7747. if (dt === 0) {
  7748. xUnitVector.setRelative(p, p, (dm1 + dm2) / 2, pv, true);
  7749. return;
  7750. }
  7751. xUnitVector.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true);
  7752. },
  7753. // Slope of line normal to this
  7754. normalSlope: Number.NEGATIVE_INFINITY,
  7755. // Sets the point 'p' relative to point 'rp'
  7756. // by the distance 'd'.
  7757. //
  7758. // See APPENDIX on SETRELATIVE at the bottom of this file.
  7759. //
  7760. // p ... point to set
  7761. // rp ... reference point
  7762. // d ... distance on projection vector
  7763. // pv ... projection vector (undefined = this)
  7764. // org ... if true, uses the original position of rp as reference.
  7765. setRelative: function (p, rp, d, pv, org) {
  7766. if (!pv || pv === this) {
  7767. p.x = (org ? rp.xo : rp.x) + d;
  7768. return;
  7769. }
  7770. var rpx = org ? rp.xo : rp.x;
  7771. var rpy = org ? rp.yo : rp.y;
  7772. var rpdx = rpx + d * pv.x;
  7773. var rpdy = rpy + d * pv.y;
  7774. p.x = rpdx + (p.y - rpdy) / pv.normalSlope;
  7775. },
  7776. // Slope of vector line.
  7777. slope: 0,
  7778. // Touches the point p.
  7779. touch: function (p) {
  7780. p.xTouched = true;
  7781. },
  7782. // Tests if a point p is touched.
  7783. touched: function (p) {
  7784. return p.xTouched;
  7785. },
  7786. // Untouches the point p.
  7787. untouch: function (p) {
  7788. p.xTouched = false;
  7789. }
  7790. };
  7791. /*
  7792. * Unit vector of y-axis.
  7793. */
  7794. var yUnitVector = {
  7795. x: 0,
  7796. y: 1,
  7797. axis: 'y',
  7798. // Gets the projected distance between two points.
  7799. // o1/o2 ... if true, respective original position is used.
  7800. distance: function (p1, p2, o1, o2) {
  7801. return (o1 ? p1.yo : p1.y) - (o2 ? p2.yo : p2.y);
  7802. },
  7803. // Moves point p so the moved position has the same relative
  7804. // position to the moved positions of rp1 and rp2 than the
  7805. // original positions had.
  7806. //
  7807. // See APPENDIX on INTERPOLATE at the bottom of this file.
  7808. interpolate: function (p, rp1, rp2, pv) {
  7809. var do1;
  7810. var do2;
  7811. var doa1;
  7812. var doa2;
  7813. var dm1;
  7814. var dm2;
  7815. var dt;
  7816. if (!pv || pv === this) {
  7817. do1 = p.yo - rp1.yo;
  7818. do2 = p.yo - rp2.yo;
  7819. dm1 = rp1.y - rp1.yo;
  7820. dm2 = rp2.y - rp2.yo;
  7821. doa1 = Math.abs(do1);
  7822. doa2 = Math.abs(do2);
  7823. dt = doa1 + doa2;
  7824. if (dt === 0) {
  7825. p.y = p.yo + (dm1 + dm2) / 2;
  7826. return;
  7827. }
  7828. p.y = p.yo + (dm1 * doa2 + dm2 * doa1) / dt;
  7829. return;
  7830. }
  7831. do1 = pv.distance(p, rp1, true, true);
  7832. do2 = pv.distance(p, rp2, true, true);
  7833. dm1 = pv.distance(rp1, rp1, false, true);
  7834. dm2 = pv.distance(rp2, rp2, false, true);
  7835. doa1 = Math.abs(do1);
  7836. doa2 = Math.abs(do2);
  7837. dt = doa1 + doa2;
  7838. if (dt === 0) {
  7839. yUnitVector.setRelative(p, p, (dm1 + dm2) / 2, pv, true);
  7840. return;
  7841. }
  7842. yUnitVector.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true);
  7843. },
  7844. // Slope of line normal to this.
  7845. normalSlope: 0,
  7846. // Sets the point 'p' relative to point 'rp'
  7847. // by the distance 'd'
  7848. //
  7849. // See APPENDIX on SETRELATIVE at the bottom of this file.
  7850. //
  7851. // p ... point to set
  7852. // rp ... reference point
  7853. // d ... distance on projection vector
  7854. // pv ... projection vector (undefined = this)
  7855. // org ... if true, uses the original position of rp as reference.
  7856. setRelative: function (p, rp, d, pv, org) {
  7857. if (!pv || pv === this) {
  7858. p.y = (org ? rp.yo : rp.y) + d;
  7859. return;
  7860. }
  7861. var rpx = org ? rp.xo : rp.x;
  7862. var rpy = org ? rp.yo : rp.y;
  7863. var rpdx = rpx + d * pv.x;
  7864. var rpdy = rpy + d * pv.y;
  7865. p.y = rpdy + pv.normalSlope * (p.x - rpdx);
  7866. },
  7867. // Slope of vector line.
  7868. slope: Number.POSITIVE_INFINITY,
  7869. // Touches the point p.
  7870. touch: function (p) {
  7871. p.yTouched = true;
  7872. },
  7873. // Tests if a point p is touched.
  7874. touched: function (p) {
  7875. return p.yTouched;
  7876. },
  7877. // Untouches the point p.
  7878. untouch: function (p) {
  7879. p.yTouched = false;
  7880. }
  7881. };
  7882. Object.freeze(xUnitVector);
  7883. Object.freeze(yUnitVector);
  7884. /*
  7885. * Creates a unit vector that is not x- or y-axis.
  7886. */
  7887. function UnitVector(x, y) {
  7888. this.x = x;
  7889. this.y = y;
  7890. this.axis = undefined;
  7891. this.slope = y / x;
  7892. this.normalSlope = -x / y;
  7893. Object.freeze(this);
  7894. }
  7895. /*
  7896. * Gets the projected distance between two points.
  7897. * o1/o2 ... if true, respective original position is used.
  7898. */
  7899. UnitVector.prototype.distance = function(p1, p2, o1, o2) {
  7900. return (
  7901. this.x * xUnitVector.distance(p1, p2, o1, o2) +
  7902. this.y * yUnitVector.distance(p1, p2, o1, o2)
  7903. );
  7904. };
  7905. /*
  7906. * Moves point p so the moved position has the same relative
  7907. * position to the moved positions of rp1 and rp2 than the
  7908. * original positions had.
  7909. *
  7910. * See APPENDIX on INTERPOLATE at the bottom of this file.
  7911. */
  7912. UnitVector.prototype.interpolate = function(p, rp1, rp2, pv) {
  7913. var dm1;
  7914. var dm2;
  7915. var do1;
  7916. var do2;
  7917. var doa1;
  7918. var doa2;
  7919. var dt;
  7920. do1 = pv.distance(p, rp1, true, true);
  7921. do2 = pv.distance(p, rp2, true, true);
  7922. dm1 = pv.distance(rp1, rp1, false, true);
  7923. dm2 = pv.distance(rp2, rp2, false, true);
  7924. doa1 = Math.abs(do1);
  7925. doa2 = Math.abs(do2);
  7926. dt = doa1 + doa2;
  7927. if (dt === 0) {
  7928. this.setRelative(p, p, (dm1 + dm2) / 2, pv, true);
  7929. return;
  7930. }
  7931. this.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true);
  7932. };
  7933. /*
  7934. * Sets the point 'p' relative to point 'rp'
  7935. * by the distance 'd'
  7936. *
  7937. * See APPENDIX on SETRELATIVE at the bottom of this file.
  7938. *
  7939. * p ... point to set
  7940. * rp ... reference point
  7941. * d ... distance on projection vector
  7942. * pv ... projection vector (undefined = this)
  7943. * org ... if true, uses the original position of rp as reference.
  7944. */
  7945. UnitVector.prototype.setRelative = function(p, rp, d, pv, org) {
  7946. pv = pv || this;
  7947. var rpx = org ? rp.xo : rp.x;
  7948. var rpy = org ? rp.yo : rp.y;
  7949. var rpdx = rpx + d * pv.x;
  7950. var rpdy = rpy + d * pv.y;
  7951. var pvns = pv.normalSlope;
  7952. var fvs = this.slope;
  7953. var px = p.x;
  7954. var py = p.y;
  7955. p.x = (fvs * px - pvns * rpdx + rpdy - py) / (fvs - pvns);
  7956. p.y = fvs * (p.x - px) + py;
  7957. };
  7958. /*
  7959. * Touches the point p.
  7960. */
  7961. UnitVector.prototype.touch = function(p) {
  7962. p.xTouched = true;
  7963. p.yTouched = true;
  7964. };
  7965. /*
  7966. * Returns a unit vector with x/y coordinates.
  7967. */
  7968. function getUnitVector(x, y) {
  7969. var d = Math.sqrt(x * x + y * y);
  7970. x /= d;
  7971. y /= d;
  7972. if (x === 1 && y === 0) { return xUnitVector; }
  7973. else if (x === 0 && y === 1) { return yUnitVector; }
  7974. else { return new UnitVector(x, y); }
  7975. }
  7976. /*
  7977. * Creates a point in the hinting engine.
  7978. */
  7979. function HPoint(
  7980. x,
  7981. y,
  7982. lastPointOfContour,
  7983. onCurve
  7984. ) {
  7985. this.x = this.xo = Math.round(x * 64) / 64; // hinted x value and original x-value
  7986. this.y = this.yo = Math.round(y * 64) / 64; // hinted y value and original y-value
  7987. this.lastPointOfContour = lastPointOfContour;
  7988. this.onCurve = onCurve;
  7989. this.prevPointOnContour = undefined;
  7990. this.nextPointOnContour = undefined;
  7991. this.xTouched = false;
  7992. this.yTouched = false;
  7993. Object.preventExtensions(this);
  7994. }
  7995. /*
  7996. * Returns the next touched point on the contour.
  7997. *
  7998. * v ... unit vector to test touch axis.
  7999. */
  8000. HPoint.prototype.nextTouched = function(v) {
  8001. var p = this.nextPointOnContour;
  8002. while (!v.touched(p) && p !== this) { p = p.nextPointOnContour; }
  8003. return p;
  8004. };
  8005. /*
  8006. * Returns the previous touched point on the contour
  8007. *
  8008. * v ... unit vector to test touch axis.
  8009. */
  8010. HPoint.prototype.prevTouched = function(v) {
  8011. var p = this.prevPointOnContour;
  8012. while (!v.touched(p) && p !== this) { p = p.prevPointOnContour; }
  8013. return p;
  8014. };
  8015. /*
  8016. * The zero point.
  8017. */
  8018. var HPZero = Object.freeze(new HPoint(0, 0));
  8019. /*
  8020. * The default state of the interpreter.
  8021. *
  8022. * Note: Freezing the defaultState and then deriving from it
  8023. * makes the V8 Javascript engine going awkward,
  8024. * so this is avoided, albeit the defaultState shouldn't
  8025. * ever change.
  8026. */
  8027. var defaultState = {
  8028. cvCutIn: 17 / 16, // control value cut in
  8029. deltaBase: 9,
  8030. deltaShift: 0.125,
  8031. loop: 1, // loops some instructions
  8032. minDis: 1, // minimum distance
  8033. autoFlip: true
  8034. };
  8035. /*
  8036. * The current state of the interpreter.
  8037. *
  8038. * env ... 'fpgm' or 'prep' or 'glyf'
  8039. * prog ... the program
  8040. */
  8041. function State(env, prog) {
  8042. this.env = env;
  8043. this.stack = [];
  8044. this.prog = prog;
  8045. switch (env) {
  8046. case 'glyf' :
  8047. this.zp0 = this.zp1 = this.zp2 = 1;
  8048. this.rp0 = this.rp1 = this.rp2 = 0;
  8049. /* fall through */
  8050. case 'prep' :
  8051. this.fv = this.pv = this.dpv = xUnitVector;
  8052. this.round = roundToGrid;
  8053. }
  8054. }
  8055. /*
  8056. * Executes a glyph program.
  8057. *
  8058. * This does the hinting for each glyph.
  8059. *
  8060. * Returns an array of moved points.
  8061. *
  8062. * glyph: the glyph to hint
  8063. * ppem: the size the glyph is rendered for
  8064. */
  8065. Hinting.prototype.exec = function(glyph, ppem) {
  8066. if (typeof ppem !== 'number') {
  8067. throw new Error('Point size is not a number!');
  8068. }
  8069. // Received a fatal error, don't do any hinting anymore.
  8070. if (this._errorState > 2) { return; }
  8071. var font = this.font;
  8072. var prepState = this._prepState;
  8073. if (!prepState || prepState.ppem !== ppem) {
  8074. var fpgmState = this._fpgmState;
  8075. if (!fpgmState) {
  8076. // Executes the fpgm state.
  8077. // This is used by fonts to define functions.
  8078. State.prototype = defaultState;
  8079. fpgmState =
  8080. this._fpgmState =
  8081. new State('fpgm', font.tables.fpgm);
  8082. fpgmState.funcs = [ ];
  8083. fpgmState.font = font;
  8084. if (exports.DEBUG) {
  8085. console.log('---EXEC FPGM---');
  8086. fpgmState.step = -1;
  8087. }
  8088. try {
  8089. exec(fpgmState);
  8090. } catch (e) {
  8091. console.log('Hinting error in FPGM:' + e);
  8092. this._errorState = 3;
  8093. return;
  8094. }
  8095. }
  8096. // Executes the prep program for this ppem setting.
  8097. // This is used by fonts to set cvt values
  8098. // depending on to be rendered font size.
  8099. State.prototype = fpgmState;
  8100. prepState =
  8101. this._prepState =
  8102. new State('prep', font.tables.prep);
  8103. prepState.ppem = ppem;
  8104. // Creates a copy of the cvt table
  8105. // and scales it to the current ppem setting.
  8106. var oCvt = font.tables.cvt;
  8107. if (oCvt) {
  8108. var cvt = prepState.cvt = new Array(oCvt.length);
  8109. var scale = ppem / font.unitsPerEm;
  8110. for (var c = 0; c < oCvt.length; c++) {
  8111. cvt[c] = oCvt[c] * scale;
  8112. }
  8113. } else {
  8114. prepState.cvt = [];
  8115. }
  8116. if (exports.DEBUG) {
  8117. console.log('---EXEC PREP---');
  8118. prepState.step = -1;
  8119. }
  8120. try {
  8121. exec(prepState);
  8122. } catch (e) {
  8123. if (this._errorState < 2) {
  8124. console.log('Hinting error in PREP:' + e);
  8125. }
  8126. this._errorState = 2;
  8127. }
  8128. }
  8129. if (this._errorState > 1) { return; }
  8130. try {
  8131. return execGlyph(glyph, prepState);
  8132. } catch (e) {
  8133. if (this._errorState < 1) {
  8134. console.log('Hinting error:' + e);
  8135. console.log('Note: further hinting errors are silenced');
  8136. }
  8137. this._errorState = 1;
  8138. return undefined;
  8139. }
  8140. };
  8141. /*
  8142. * Executes the hinting program for a glyph.
  8143. */
  8144. execGlyph = function(glyph, prepState) {
  8145. // original point positions
  8146. var xScale = prepState.ppem / prepState.font.unitsPerEm;
  8147. var yScale = xScale;
  8148. var components = glyph.components;
  8149. var contours;
  8150. var gZone;
  8151. var state;
  8152. State.prototype = prepState;
  8153. if (!components) {
  8154. state = new State('glyf', glyph.instructions);
  8155. if (exports.DEBUG) {
  8156. console.log('---EXEC GLYPH---');
  8157. state.step = -1;
  8158. }
  8159. execComponent(glyph, state, xScale, yScale);
  8160. gZone = state.gZone;
  8161. } else {
  8162. var font = prepState.font;
  8163. gZone = [];
  8164. contours = [];
  8165. for (var i = 0; i < components.length; i++) {
  8166. var c = components[i];
  8167. var cg = font.glyphs.get(c.glyphIndex);
  8168. state = new State('glyf', cg.instructions);
  8169. if (exports.DEBUG) {
  8170. console.log('---EXEC COMP ' + i + '---');
  8171. state.step = -1;
  8172. }
  8173. execComponent(cg, state, xScale, yScale);
  8174. // appends the computed points to the result array
  8175. // post processes the component points
  8176. var dx = Math.round(c.dx * xScale);
  8177. var dy = Math.round(c.dy * yScale);
  8178. var gz = state.gZone;
  8179. var cc = state.contours;
  8180. for (var pi = 0; pi < gz.length; pi++) {
  8181. var p = gz[pi];
  8182. p.xTouched = p.yTouched = false;
  8183. p.xo = p.x = p.x + dx;
  8184. p.yo = p.y = p.y + dy;
  8185. }
  8186. var gLen = gZone.length;
  8187. gZone.push.apply(gZone, gz);
  8188. for (var j = 0; j < cc.length; j++) {
  8189. contours.push(cc[j] + gLen);
  8190. }
  8191. }
  8192. if (glyph.instructions && !state.inhibitGridFit) {
  8193. // the composite has instructions on its own
  8194. state = new State('glyf', glyph.instructions);
  8195. state.gZone = state.z0 = state.z1 = state.z2 = gZone;
  8196. state.contours = contours;
  8197. // note: HPZero cannot be used here, since
  8198. // the point might be modified
  8199. gZone.push(
  8200. new HPoint(0, 0),
  8201. new HPoint(Math.round(glyph.advanceWidth * xScale), 0)
  8202. );
  8203. if (exports.DEBUG) {
  8204. console.log('---EXEC COMPOSITE---');
  8205. state.step = -1;
  8206. }
  8207. exec(state);
  8208. gZone.length -= 2;
  8209. }
  8210. }
  8211. return gZone;
  8212. };
  8213. /*
  8214. * Executes the hinting program for a component of a multi-component glyph
  8215. * or of the glyph itself for a non-component glyph.
  8216. */
  8217. execComponent = function(glyph, state, xScale, yScale)
  8218. {
  8219. var points = glyph.points || [];
  8220. var pLen = points.length;
  8221. var gZone = state.gZone = state.z0 = state.z1 = state.z2 = [];
  8222. var contours = state.contours = [];
  8223. // Scales the original points and
  8224. // makes copies for the hinted points.
  8225. var cp; // current point
  8226. for (var i = 0; i < pLen; i++) {
  8227. cp = points[i];
  8228. gZone[i] = new HPoint(
  8229. cp.x * xScale,
  8230. cp.y * yScale,
  8231. cp.lastPointOfContour,
  8232. cp.onCurve
  8233. );
  8234. }
  8235. // Chain links the contours.
  8236. var sp; // start point
  8237. var np; // next point
  8238. for (var i$1 = 0; i$1 < pLen; i$1++) {
  8239. cp = gZone[i$1];
  8240. if (!sp) {
  8241. sp = cp;
  8242. contours.push(i$1);
  8243. }
  8244. if (cp.lastPointOfContour) {
  8245. cp.nextPointOnContour = sp;
  8246. sp.prevPointOnContour = cp;
  8247. sp = undefined;
  8248. } else {
  8249. np = gZone[i$1 + 1];
  8250. cp.nextPointOnContour = np;
  8251. np.prevPointOnContour = cp;
  8252. }
  8253. }
  8254. if (state.inhibitGridFit) { return; }
  8255. if (exports.DEBUG) {
  8256. console.log('PROCESSING GLYPH', state.stack);
  8257. for (var i$2 = 0; i$2 < pLen; i$2++) {
  8258. console.log(i$2, gZone[i$2].x, gZone[i$2].y);
  8259. }
  8260. }
  8261. gZone.push(
  8262. new HPoint(0, 0),
  8263. new HPoint(Math.round(glyph.advanceWidth * xScale), 0)
  8264. );
  8265. exec(state);
  8266. // Removes the extra points.
  8267. gZone.length -= 2;
  8268. if (exports.DEBUG) {
  8269. console.log('FINISHED GLYPH', state.stack);
  8270. for (var i$3 = 0; i$3 < pLen; i$3++) {
  8271. console.log(i$3, gZone[i$3].x, gZone[i$3].y);
  8272. }
  8273. }
  8274. };
  8275. /*
  8276. * Executes the program loaded in state.
  8277. */
  8278. exec = function(state) {
  8279. var prog = state.prog;
  8280. if (!prog) { return; }
  8281. var pLen = prog.length;
  8282. var ins;
  8283. for (state.ip = 0; state.ip < pLen; state.ip++) {
  8284. if (exports.DEBUG) { state.step++; }
  8285. ins = instructionTable[prog[state.ip]];
  8286. if (!ins) {
  8287. throw new Error(
  8288. 'unknown instruction: 0x' +
  8289. Number(prog[state.ip]).toString(16)
  8290. );
  8291. }
  8292. ins(state);
  8293. // very extensive debugging for each step
  8294. /*
  8295. if (exports.DEBUG) {
  8296. var da;
  8297. if (state.gZone) {
  8298. da = [];
  8299. for (let i = 0; i < state.gZone.length; i++)
  8300. {
  8301. da.push(i + ' ' +
  8302. state.gZone[i].x * 64 + ' ' +
  8303. state.gZone[i].y * 64 + ' ' +
  8304. (state.gZone[i].xTouched ? 'x' : '') +
  8305. (state.gZone[i].yTouched ? 'y' : '')
  8306. );
  8307. }
  8308. console.log('GZ', da);
  8309. }
  8310. if (state.tZone) {
  8311. da = [];
  8312. for (let i = 0; i < state.tZone.length; i++) {
  8313. da.push(i + ' ' +
  8314. state.tZone[i].x * 64 + ' ' +
  8315. state.tZone[i].y * 64 + ' ' +
  8316. (state.tZone[i].xTouched ? 'x' : '') +
  8317. (state.tZone[i].yTouched ? 'y' : '')
  8318. );
  8319. }
  8320. console.log('TZ', da);
  8321. }
  8322. if (state.stack.length > 10) {
  8323. console.log(
  8324. state.stack.length,
  8325. '...', state.stack.slice(state.stack.length - 10)
  8326. );
  8327. } else {
  8328. console.log(state.stack.length, state.stack);
  8329. }
  8330. }
  8331. */
  8332. }
  8333. };
  8334. /*
  8335. * Initializes the twilight zone.
  8336. *
  8337. * This is only done if a SZPx instruction
  8338. * refers to the twilight zone.
  8339. */
  8340. function initTZone(state)
  8341. {
  8342. var tZone = state.tZone = new Array(state.gZone.length);
  8343. // no idea if this is actually correct...
  8344. for (var i = 0; i < tZone.length; i++)
  8345. {
  8346. tZone[i] = new HPoint(0, 0);
  8347. }
  8348. }
  8349. /*
  8350. * Skips the instruction pointer ahead over an IF/ELSE block.
  8351. * handleElse .. if true breaks on matching ELSE
  8352. */
  8353. function skip(state, handleElse)
  8354. {
  8355. var prog = state.prog;
  8356. var ip = state.ip;
  8357. var nesting = 1;
  8358. var ins;
  8359. do {
  8360. ins = prog[++ip];
  8361. if (ins === 0x58) // IF
  8362. { nesting++; }
  8363. else if (ins === 0x59) // EIF
  8364. { nesting--; }
  8365. else if (ins === 0x40) // NPUSHB
  8366. { ip += prog[ip + 1] + 1; }
  8367. else if (ins === 0x41) // NPUSHW
  8368. { ip += 2 * prog[ip + 1] + 1; }
  8369. else if (ins >= 0xB0 && ins <= 0xB7) // PUSHB
  8370. { ip += ins - 0xB0 + 1; }
  8371. else if (ins >= 0xB8 && ins <= 0xBF) // PUSHW
  8372. { ip += (ins - 0xB8 + 1) * 2; }
  8373. else if (handleElse && nesting === 1 && ins === 0x1B) // ELSE
  8374. { break; }
  8375. } while (nesting > 0);
  8376. state.ip = ip;
  8377. }
  8378. /*----------------------------------------------------------*
  8379. * And then a lot of instructions... *
  8380. *----------------------------------------------------------*/
  8381. // SVTCA[a] Set freedom and projection Vectors To Coordinate Axis
  8382. // 0x00-0x01
  8383. function SVTCA(v, state) {
  8384. if (exports.DEBUG) { console.log(state.step, 'SVTCA[' + v.axis + ']'); }
  8385. state.fv = state.pv = state.dpv = v;
  8386. }
  8387. // SPVTCA[a] Set Projection Vector to Coordinate Axis
  8388. // 0x02-0x03
  8389. function SPVTCA(v, state) {
  8390. if (exports.DEBUG) { console.log(state.step, 'SPVTCA[' + v.axis + ']'); }
  8391. state.pv = state.dpv = v;
  8392. }
  8393. // SFVTCA[a] Set Freedom Vector to Coordinate Axis
  8394. // 0x04-0x05
  8395. function SFVTCA(v, state) {
  8396. if (exports.DEBUG) { console.log(state.step, 'SFVTCA[' + v.axis + ']'); }
  8397. state.fv = v;
  8398. }
  8399. // SPVTL[a] Set Projection Vector To Line
  8400. // 0x06-0x07
  8401. function SPVTL(a, state) {
  8402. var stack = state.stack;
  8403. var p2i = stack.pop();
  8404. var p1i = stack.pop();
  8405. var p2 = state.z2[p2i];
  8406. var p1 = state.z1[p1i];
  8407. if (exports.DEBUG) { console.log('SPVTL[' + a + ']', p2i, p1i); }
  8408. var dx;
  8409. var dy;
  8410. if (!a) {
  8411. dx = p1.x - p2.x;
  8412. dy = p1.y - p2.y;
  8413. } else {
  8414. dx = p2.y - p1.y;
  8415. dy = p1.x - p2.x;
  8416. }
  8417. state.pv = state.dpv = getUnitVector(dx, dy);
  8418. }
  8419. // SFVTL[a] Set Freedom Vector To Line
  8420. // 0x08-0x09
  8421. function SFVTL(a, state) {
  8422. var stack = state.stack;
  8423. var p2i = stack.pop();
  8424. var p1i = stack.pop();
  8425. var p2 = state.z2[p2i];
  8426. var p1 = state.z1[p1i];
  8427. if (exports.DEBUG) { console.log('SFVTL[' + a + ']', p2i, p1i); }
  8428. var dx;
  8429. var dy;
  8430. if (!a) {
  8431. dx = p1.x - p2.x;
  8432. dy = p1.y - p2.y;
  8433. } else {
  8434. dx = p2.y - p1.y;
  8435. dy = p1.x - p2.x;
  8436. }
  8437. state.fv = getUnitVector(dx, dy);
  8438. }
  8439. // SPVFS[] Set Projection Vector From Stack
  8440. // 0x0A
  8441. function SPVFS(state) {
  8442. var stack = state.stack;
  8443. var y = stack.pop();
  8444. var x = stack.pop();
  8445. if (exports.DEBUG) { console.log(state.step, 'SPVFS[]', y, x); }
  8446. state.pv = state.dpv = getUnitVector(x, y);
  8447. }
  8448. // SFVFS[] Set Freedom Vector From Stack
  8449. // 0x0B
  8450. function SFVFS(state) {
  8451. var stack = state.stack;
  8452. var y = stack.pop();
  8453. var x = stack.pop();
  8454. if (exports.DEBUG) { console.log(state.step, 'SPVFS[]', y, x); }
  8455. state.fv = getUnitVector(x, y);
  8456. }
  8457. // GPV[] Get Projection Vector
  8458. // 0x0C
  8459. function GPV(state) {
  8460. var stack = state.stack;
  8461. var pv = state.pv;
  8462. if (exports.DEBUG) { console.log(state.step, 'GPV[]'); }
  8463. stack.push(pv.x * 0x4000);
  8464. stack.push(pv.y * 0x4000);
  8465. }
  8466. // GFV[] Get Freedom Vector
  8467. // 0x0C
  8468. function GFV(state) {
  8469. var stack = state.stack;
  8470. var fv = state.fv;
  8471. if (exports.DEBUG) { console.log(state.step, 'GFV[]'); }
  8472. stack.push(fv.x * 0x4000);
  8473. stack.push(fv.y * 0x4000);
  8474. }
  8475. // SFVTPV[] Set Freedom Vector To Projection Vector
  8476. // 0x0E
  8477. function SFVTPV(state) {
  8478. state.fv = state.pv;
  8479. if (exports.DEBUG) { console.log(state.step, 'SFVTPV[]'); }
  8480. }
  8481. // ISECT[] moves point p to the InterSECTion of two lines
  8482. // 0x0F
  8483. function ISECT(state)
  8484. {
  8485. var stack = state.stack;
  8486. var pa0i = stack.pop();
  8487. var pa1i = stack.pop();
  8488. var pb0i = stack.pop();
  8489. var pb1i = stack.pop();
  8490. var pi = stack.pop();
  8491. var z0 = state.z0;
  8492. var z1 = state.z1;
  8493. var pa0 = z0[pa0i];
  8494. var pa1 = z0[pa1i];
  8495. var pb0 = z1[pb0i];
  8496. var pb1 = z1[pb1i];
  8497. var p = state.z2[pi];
  8498. if (exports.DEBUG) { console.log('ISECT[], ', pa0i, pa1i, pb0i, pb1i, pi); }
  8499. // math from
  8500. // en.wikipedia.org/wiki/Line%E2%80%93line_intersection#Given_two_points_on_each_line
  8501. var x1 = pa0.x;
  8502. var y1 = pa0.y;
  8503. var x2 = pa1.x;
  8504. var y2 = pa1.y;
  8505. var x3 = pb0.x;
  8506. var y3 = pb0.y;
  8507. var x4 = pb1.x;
  8508. var y4 = pb1.y;
  8509. var div = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
  8510. var f1 = x1 * y2 - y1 * x2;
  8511. var f2 = x3 * y4 - y3 * x4;
  8512. p.x = (f1 * (x3 - x4) - f2 * (x1 - x2)) / div;
  8513. p.y = (f1 * (y3 - y4) - f2 * (y1 - y2)) / div;
  8514. }
  8515. // SRP0[] Set Reference Point 0
  8516. // 0x10
  8517. function SRP0(state) {
  8518. state.rp0 = state.stack.pop();
  8519. if (exports.DEBUG) { console.log(state.step, 'SRP0[]', state.rp0); }
  8520. }
  8521. // SRP1[] Set Reference Point 1
  8522. // 0x11
  8523. function SRP1(state) {
  8524. state.rp1 = state.stack.pop();
  8525. if (exports.DEBUG) { console.log(state.step, 'SRP1[]', state.rp1); }
  8526. }
  8527. // SRP1[] Set Reference Point 2
  8528. // 0x12
  8529. function SRP2(state) {
  8530. state.rp2 = state.stack.pop();
  8531. if (exports.DEBUG) { console.log(state.step, 'SRP2[]', state.rp2); }
  8532. }
  8533. // SZP0[] Set Zone Pointer 0
  8534. // 0x13
  8535. function SZP0(state) {
  8536. var n = state.stack.pop();
  8537. if (exports.DEBUG) { console.log(state.step, 'SZP0[]', n); }
  8538. state.zp0 = n;
  8539. switch (n) {
  8540. case 0:
  8541. if (!state.tZone) { initTZone(state); }
  8542. state.z0 = state.tZone;
  8543. break;
  8544. case 1 :
  8545. state.z0 = state.gZone;
  8546. break;
  8547. default :
  8548. throw new Error('Invalid zone pointer');
  8549. }
  8550. }
  8551. // SZP1[] Set Zone Pointer 1
  8552. // 0x14
  8553. function SZP1(state) {
  8554. var n = state.stack.pop();
  8555. if (exports.DEBUG) { console.log(state.step, 'SZP1[]', n); }
  8556. state.zp1 = n;
  8557. switch (n) {
  8558. case 0:
  8559. if (!state.tZone) { initTZone(state); }
  8560. state.z1 = state.tZone;
  8561. break;
  8562. case 1 :
  8563. state.z1 = state.gZone;
  8564. break;
  8565. default :
  8566. throw new Error('Invalid zone pointer');
  8567. }
  8568. }
  8569. // SZP2[] Set Zone Pointer 2
  8570. // 0x15
  8571. function SZP2(state) {
  8572. var n = state.stack.pop();
  8573. if (exports.DEBUG) { console.log(state.step, 'SZP2[]', n); }
  8574. state.zp2 = n;
  8575. switch (n) {
  8576. case 0:
  8577. if (!state.tZone) { initTZone(state); }
  8578. state.z2 = state.tZone;
  8579. break;
  8580. case 1 :
  8581. state.z2 = state.gZone;
  8582. break;
  8583. default :
  8584. throw new Error('Invalid zone pointer');
  8585. }
  8586. }
  8587. // SZPS[] Set Zone PointerS
  8588. // 0x16
  8589. function SZPS(state) {
  8590. var n = state.stack.pop();
  8591. if (exports.DEBUG) { console.log(state.step, 'SZPS[]', n); }
  8592. state.zp0 = state.zp1 = state.zp2 = n;
  8593. switch (n) {
  8594. case 0:
  8595. if (!state.tZone) { initTZone(state); }
  8596. state.z0 = state.z1 = state.z2 = state.tZone;
  8597. break;
  8598. case 1 :
  8599. state.z0 = state.z1 = state.z2 = state.gZone;
  8600. break;
  8601. default :
  8602. throw new Error('Invalid zone pointer');
  8603. }
  8604. }
  8605. // SLOOP[] Set LOOP variable
  8606. // 0x17
  8607. function SLOOP(state) {
  8608. state.loop = state.stack.pop();
  8609. if (exports.DEBUG) { console.log(state.step, 'SLOOP[]', state.loop); }
  8610. }
  8611. // RTG[] Round To Grid
  8612. // 0x18
  8613. function RTG(state) {
  8614. if (exports.DEBUG) { console.log(state.step, 'RTG[]'); }
  8615. state.round = roundToGrid;
  8616. }
  8617. // RTHG[] Round To Half Grid
  8618. // 0x19
  8619. function RTHG(state) {
  8620. if (exports.DEBUG) { console.log(state.step, 'RTHG[]'); }
  8621. state.round = roundToHalfGrid;
  8622. }
  8623. // SMD[] Set Minimum Distance
  8624. // 0x1A
  8625. function SMD(state) {
  8626. var d = state.stack.pop();
  8627. if (exports.DEBUG) { console.log(state.step, 'SMD[]', d); }
  8628. state.minDis = d / 0x40;
  8629. }
  8630. // ELSE[] ELSE clause
  8631. // 0x1B
  8632. function ELSE(state) {
  8633. // This instruction has been reached by executing a then branch
  8634. // so it just skips ahead until matching EIF.
  8635. //
  8636. // In case the IF was negative the IF[] instruction already
  8637. // skipped forward over the ELSE[]
  8638. if (exports.DEBUG) { console.log(state.step, 'ELSE[]'); }
  8639. skip(state, false);
  8640. }
  8641. // JMPR[] JuMP Relative
  8642. // 0x1C
  8643. function JMPR(state) {
  8644. var o = state.stack.pop();
  8645. if (exports.DEBUG) { console.log(state.step, 'JMPR[]', o); }
  8646. // A jump by 1 would do nothing.
  8647. state.ip += o - 1;
  8648. }
  8649. // SCVTCI[] Set Control Value Table Cut-In
  8650. // 0x1D
  8651. function SCVTCI(state) {
  8652. var n = state.stack.pop();
  8653. if (exports.DEBUG) { console.log(state.step, 'SCVTCI[]', n); }
  8654. state.cvCutIn = n / 0x40;
  8655. }
  8656. // DUP[] DUPlicate top stack element
  8657. // 0x20
  8658. function DUP(state) {
  8659. var stack = state.stack;
  8660. if (exports.DEBUG) { console.log(state.step, 'DUP[]'); }
  8661. stack.push(stack[stack.length - 1]);
  8662. }
  8663. // POP[] POP top stack element
  8664. // 0x21
  8665. function POP(state) {
  8666. if (exports.DEBUG) { console.log(state.step, 'POP[]'); }
  8667. state.stack.pop();
  8668. }
  8669. // CLEAR[] CLEAR the stack
  8670. // 0x22
  8671. function CLEAR(state) {
  8672. if (exports.DEBUG) { console.log(state.step, 'CLEAR[]'); }
  8673. state.stack.length = 0;
  8674. }
  8675. // SWAP[] SWAP the top two elements on the stack
  8676. // 0x23
  8677. function SWAP(state) {
  8678. var stack = state.stack;
  8679. var a = stack.pop();
  8680. var b = stack.pop();
  8681. if (exports.DEBUG) { console.log(state.step, 'SWAP[]'); }
  8682. stack.push(a);
  8683. stack.push(b);
  8684. }
  8685. // DEPTH[] DEPTH of the stack
  8686. // 0x24
  8687. function DEPTH(state) {
  8688. var stack = state.stack;
  8689. if (exports.DEBUG) { console.log(state.step, 'DEPTH[]'); }
  8690. stack.push(stack.length);
  8691. }
  8692. // LOOPCALL[] LOOPCALL function
  8693. // 0x2A
  8694. function LOOPCALL(state) {
  8695. var stack = state.stack;
  8696. var fn = stack.pop();
  8697. var c = stack.pop();
  8698. if (exports.DEBUG) { console.log(state.step, 'LOOPCALL[]', fn, c); }
  8699. // saves callers program
  8700. var cip = state.ip;
  8701. var cprog = state.prog;
  8702. state.prog = state.funcs[fn];
  8703. // executes the function
  8704. for (var i = 0; i < c; i++) {
  8705. exec(state);
  8706. if (exports.DEBUG) { console.log(
  8707. ++state.step,
  8708. i + 1 < c ? 'next loopcall' : 'done loopcall',
  8709. i
  8710. ); }
  8711. }
  8712. // restores the callers program
  8713. state.ip = cip;
  8714. state.prog = cprog;
  8715. }
  8716. // CALL[] CALL function
  8717. // 0x2B
  8718. function CALL(state) {
  8719. var fn = state.stack.pop();
  8720. if (exports.DEBUG) { console.log(state.step, 'CALL[]', fn); }
  8721. // saves callers program
  8722. var cip = state.ip;
  8723. var cprog = state.prog;
  8724. state.prog = state.funcs[fn];
  8725. // executes the function
  8726. exec(state);
  8727. // restores the callers program
  8728. state.ip = cip;
  8729. state.prog = cprog;
  8730. if (exports.DEBUG) { console.log(++state.step, 'returning from', fn); }
  8731. }
  8732. // CINDEX[] Copy the INDEXed element to the top of the stack
  8733. // 0x25
  8734. function CINDEX(state) {
  8735. var stack = state.stack;
  8736. var k = stack.pop();
  8737. if (exports.DEBUG) { console.log(state.step, 'CINDEX[]', k); }
  8738. // In case of k == 1, it copies the last element after popping
  8739. // thus stack.length - k.
  8740. stack.push(stack[stack.length - k]);
  8741. }
  8742. // MINDEX[] Move the INDEXed element to the top of the stack
  8743. // 0x26
  8744. function MINDEX(state) {
  8745. var stack = state.stack;
  8746. var k = stack.pop();
  8747. if (exports.DEBUG) { console.log(state.step, 'MINDEX[]', k); }
  8748. stack.push(stack.splice(stack.length - k, 1)[0]);
  8749. }
  8750. // FDEF[] Function DEFinition
  8751. // 0x2C
  8752. function FDEF(state) {
  8753. if (state.env !== 'fpgm') { throw new Error('FDEF not allowed here'); }
  8754. var stack = state.stack;
  8755. var prog = state.prog;
  8756. var ip = state.ip;
  8757. var fn = stack.pop();
  8758. var ipBegin = ip;
  8759. if (exports.DEBUG) { console.log(state.step, 'FDEF[]', fn); }
  8760. while (prog[++ip] !== 0x2D){ }
  8761. state.ip = ip;
  8762. state.funcs[fn] = prog.slice(ipBegin + 1, ip);
  8763. }
  8764. // MDAP[a] Move Direct Absolute Point
  8765. // 0x2E-0x2F
  8766. function MDAP(round, state) {
  8767. var pi = state.stack.pop();
  8768. var p = state.z0[pi];
  8769. var fv = state.fv;
  8770. var pv = state.pv;
  8771. if (exports.DEBUG) { console.log(state.step, 'MDAP[' + round + ']', pi); }
  8772. var d = pv.distance(p, HPZero);
  8773. if (round) { d = state.round(d); }
  8774. fv.setRelative(p, HPZero, d, pv);
  8775. fv.touch(p);
  8776. state.rp0 = state.rp1 = pi;
  8777. }
  8778. // IUP[a] Interpolate Untouched Points through the outline
  8779. // 0x30
  8780. function IUP(v, state) {
  8781. var z2 = state.z2;
  8782. var pLen = z2.length - 2;
  8783. var cp;
  8784. var pp;
  8785. var np;
  8786. if (exports.DEBUG) { console.log(state.step, 'IUP[' + v.axis + ']'); }
  8787. for (var i = 0; i < pLen; i++) {
  8788. cp = z2[i]; // current point
  8789. // if this point has been touched go on
  8790. if (v.touched(cp)) { continue; }
  8791. pp = cp.prevTouched(v);
  8792. // no point on the contour has been touched?
  8793. if (pp === cp) { continue; }
  8794. np = cp.nextTouched(v);
  8795. if (pp === np) {
  8796. // only one point on the contour has been touched
  8797. // so simply moves the point like that
  8798. v.setRelative(cp, cp, v.distance(pp, pp, false, true), v, true);
  8799. }
  8800. v.interpolate(cp, pp, np, v);
  8801. }
  8802. }
  8803. // SHP[] SHift Point using reference point
  8804. // 0x32-0x33
  8805. function SHP(a, state) {
  8806. var stack = state.stack;
  8807. var rpi = a ? state.rp1 : state.rp2;
  8808. var rp = (a ? state.z0 : state.z1)[rpi];
  8809. var fv = state.fv;
  8810. var pv = state.pv;
  8811. var loop = state.loop;
  8812. var z2 = state.z2;
  8813. while (loop--)
  8814. {
  8815. var pi = stack.pop();
  8816. var p = z2[pi];
  8817. var d = pv.distance(rp, rp, false, true);
  8818. fv.setRelative(p, p, d, pv);
  8819. fv.touch(p);
  8820. if (exports.DEBUG) {
  8821. console.log(
  8822. state.step,
  8823. (state.loop > 1 ?
  8824. 'loop ' + (state.loop - loop) + ': ' :
  8825. ''
  8826. ) +
  8827. 'SHP[' + (a ? 'rp1' : 'rp2') + ']', pi
  8828. );
  8829. }
  8830. }
  8831. state.loop = 1;
  8832. }
  8833. // SHC[] SHift Contour using reference point
  8834. // 0x36-0x37
  8835. function SHC(a, state) {
  8836. var stack = state.stack;
  8837. var rpi = a ? state.rp1 : state.rp2;
  8838. var rp = (a ? state.z0 : state.z1)[rpi];
  8839. var fv = state.fv;
  8840. var pv = state.pv;
  8841. var ci = stack.pop();
  8842. var sp = state.z2[state.contours[ci]];
  8843. var p = sp;
  8844. if (exports.DEBUG) { console.log(state.step, 'SHC[' + a + ']', ci); }
  8845. var d = pv.distance(rp, rp, false, true);
  8846. do {
  8847. if (p !== rp) { fv.setRelative(p, p, d, pv); }
  8848. p = p.nextPointOnContour;
  8849. } while (p !== sp);
  8850. }
  8851. // SHZ[] SHift Zone using reference point
  8852. // 0x36-0x37
  8853. function SHZ(a, state) {
  8854. var stack = state.stack;
  8855. var rpi = a ? state.rp1 : state.rp2;
  8856. var rp = (a ? state.z0 : state.z1)[rpi];
  8857. var fv = state.fv;
  8858. var pv = state.pv;
  8859. var e = stack.pop();
  8860. if (exports.DEBUG) { console.log(state.step, 'SHZ[' + a + ']', e); }
  8861. var z;
  8862. switch (e) {
  8863. case 0 : z = state.tZone; break;
  8864. case 1 : z = state.gZone; break;
  8865. default : throw new Error('Invalid zone');
  8866. }
  8867. var p;
  8868. var d = pv.distance(rp, rp, false, true);
  8869. var pLen = z.length - 2;
  8870. for (var i = 0; i < pLen; i++)
  8871. {
  8872. p = z[i];
  8873. fv.setRelative(p, p, d, pv);
  8874. //if (p !== rp) fv.setRelative(p, p, d, pv);
  8875. }
  8876. }
  8877. // SHPIX[] SHift point by a PIXel amount
  8878. // 0x38
  8879. function SHPIX(state) {
  8880. var stack = state.stack;
  8881. var loop = state.loop;
  8882. var fv = state.fv;
  8883. var d = stack.pop() / 0x40;
  8884. var z2 = state.z2;
  8885. while (loop--) {
  8886. var pi = stack.pop();
  8887. var p = z2[pi];
  8888. if (exports.DEBUG) {
  8889. console.log(
  8890. state.step,
  8891. (state.loop > 1 ? 'loop ' + (state.loop - loop) + ': ' : '') +
  8892. 'SHPIX[]', pi, d
  8893. );
  8894. }
  8895. fv.setRelative(p, p, d);
  8896. fv.touch(p);
  8897. }
  8898. state.loop = 1;
  8899. }
  8900. // IP[] Interpolate Point
  8901. // 0x39
  8902. function IP(state) {
  8903. var stack = state.stack;
  8904. var rp1i = state.rp1;
  8905. var rp2i = state.rp2;
  8906. var loop = state.loop;
  8907. var rp1 = state.z0[rp1i];
  8908. var rp2 = state.z1[rp2i];
  8909. var fv = state.fv;
  8910. var pv = state.dpv;
  8911. var z2 = state.z2;
  8912. while (loop--) {
  8913. var pi = stack.pop();
  8914. var p = z2[pi];
  8915. if (exports.DEBUG) {
  8916. console.log(
  8917. state.step,
  8918. (state.loop > 1 ? 'loop ' + (state.loop - loop) + ': ' : '') +
  8919. 'IP[]', pi, rp1i, '<->', rp2i
  8920. );
  8921. }
  8922. fv.interpolate(p, rp1, rp2, pv);
  8923. fv.touch(p);
  8924. }
  8925. state.loop = 1;
  8926. }
  8927. // MSIRP[a] Move Stack Indirect Relative Point
  8928. // 0x3A-0x3B
  8929. function MSIRP(a, state) {
  8930. var stack = state.stack;
  8931. var d = stack.pop() / 64;
  8932. var pi = stack.pop();
  8933. var p = state.z1[pi];
  8934. var rp0 = state.z0[state.rp0];
  8935. var fv = state.fv;
  8936. var pv = state.pv;
  8937. fv.setRelative(p, rp0, d, pv);
  8938. fv.touch(p);
  8939. if (exports.DEBUG) { console.log(state.step, 'MSIRP[' + a + ']', d, pi); }
  8940. state.rp1 = state.rp0;
  8941. state.rp2 = pi;
  8942. if (a) { state.rp0 = pi; }
  8943. }
  8944. // ALIGNRP[] Align to reference point.
  8945. // 0x3C
  8946. function ALIGNRP(state) {
  8947. var stack = state.stack;
  8948. var rp0i = state.rp0;
  8949. var rp0 = state.z0[rp0i];
  8950. var loop = state.loop;
  8951. var fv = state.fv;
  8952. var pv = state.pv;
  8953. var z1 = state.z1;
  8954. while (loop--) {
  8955. var pi = stack.pop();
  8956. var p = z1[pi];
  8957. if (exports.DEBUG) {
  8958. console.log(
  8959. state.step,
  8960. (state.loop > 1 ? 'loop ' + (state.loop - loop) + ': ' : '') +
  8961. 'ALIGNRP[]', pi
  8962. );
  8963. }
  8964. fv.setRelative(p, rp0, 0, pv);
  8965. fv.touch(p);
  8966. }
  8967. state.loop = 1;
  8968. }
  8969. // RTG[] Round To Double Grid
  8970. // 0x3D
  8971. function RTDG(state) {
  8972. if (exports.DEBUG) { console.log(state.step, 'RTDG[]'); }
  8973. state.round = roundToDoubleGrid;
  8974. }
  8975. // MIAP[a] Move Indirect Absolute Point
  8976. // 0x3E-0x3F
  8977. function MIAP(round, state) {
  8978. var stack = state.stack;
  8979. var n = stack.pop();
  8980. var pi = stack.pop();
  8981. var p = state.z0[pi];
  8982. var fv = state.fv;
  8983. var pv = state.pv;
  8984. var cv = state.cvt[n];
  8985. if (exports.DEBUG) {
  8986. console.log(
  8987. state.step,
  8988. 'MIAP[' + round + ']',
  8989. n, '(', cv, ')', pi
  8990. );
  8991. }
  8992. var d = pv.distance(p, HPZero);
  8993. if (round) {
  8994. if (Math.abs(d - cv) < state.cvCutIn) { d = cv; }
  8995. d = state.round(d);
  8996. }
  8997. fv.setRelative(p, HPZero, d, pv);
  8998. if (state.zp0 === 0) {
  8999. p.xo = p.x;
  9000. p.yo = p.y;
  9001. }
  9002. fv.touch(p);
  9003. state.rp0 = state.rp1 = pi;
  9004. }
  9005. // NPUSB[] PUSH N Bytes
  9006. // 0x40
  9007. function NPUSHB(state) {
  9008. var prog = state.prog;
  9009. var ip = state.ip;
  9010. var stack = state.stack;
  9011. var n = prog[++ip];
  9012. if (exports.DEBUG) { console.log(state.step, 'NPUSHB[]', n); }
  9013. for (var i = 0; i < n; i++) { stack.push(prog[++ip]); }
  9014. state.ip = ip;
  9015. }
  9016. // NPUSHW[] PUSH N Words
  9017. // 0x41
  9018. function NPUSHW(state) {
  9019. var ip = state.ip;
  9020. var prog = state.prog;
  9021. var stack = state.stack;
  9022. var n = prog[++ip];
  9023. if (exports.DEBUG) { console.log(state.step, 'NPUSHW[]', n); }
  9024. for (var i = 0; i < n; i++) {
  9025. var w = (prog[++ip] << 8) | prog[++ip];
  9026. if (w & 0x8000) { w = -((w ^ 0xffff) + 1); }
  9027. stack.push(w);
  9028. }
  9029. state.ip = ip;
  9030. }
  9031. // WS[] Write Store
  9032. // 0x42
  9033. function WS(state) {
  9034. var stack = state.stack;
  9035. var store = state.store;
  9036. if (!store) { store = state.store = []; }
  9037. var v = stack.pop();
  9038. var l = stack.pop();
  9039. if (exports.DEBUG) { console.log(state.step, 'WS', v, l); }
  9040. store[l] = v;
  9041. }
  9042. // RS[] Read Store
  9043. // 0x43
  9044. function RS(state) {
  9045. var stack = state.stack;
  9046. var store = state.store;
  9047. var l = stack.pop();
  9048. if (exports.DEBUG) { console.log(state.step, 'RS', l); }
  9049. var v = (store && store[l]) || 0;
  9050. stack.push(v);
  9051. }
  9052. // WCVTP[] Write Control Value Table in Pixel units
  9053. // 0x44
  9054. function WCVTP(state) {
  9055. var stack = state.stack;
  9056. var v = stack.pop();
  9057. var l = stack.pop();
  9058. if (exports.DEBUG) { console.log(state.step, 'WCVTP', v, l); }
  9059. state.cvt[l] = v / 0x40;
  9060. }
  9061. // RCVT[] Read Control Value Table entry
  9062. // 0x45
  9063. function RCVT(state) {
  9064. var stack = state.stack;
  9065. var cvte = stack.pop();
  9066. if (exports.DEBUG) { console.log(state.step, 'RCVT', cvte); }
  9067. stack.push(state.cvt[cvte] * 0x40);
  9068. }
  9069. // GC[] Get Coordinate projected onto the projection vector
  9070. // 0x46-0x47
  9071. function GC(a, state) {
  9072. var stack = state.stack;
  9073. var pi = stack.pop();
  9074. var p = state.z2[pi];
  9075. if (exports.DEBUG) { console.log(state.step, 'GC[' + a + ']', pi); }
  9076. stack.push(state.dpv.distance(p, HPZero, a, false) * 0x40);
  9077. }
  9078. // MD[a] Measure Distance
  9079. // 0x49-0x4A
  9080. function MD(a, state) {
  9081. var stack = state.stack;
  9082. var pi2 = stack.pop();
  9083. var pi1 = stack.pop();
  9084. var p2 = state.z1[pi2];
  9085. var p1 = state.z0[pi1];
  9086. var d = state.dpv.distance(p1, p2, a, a);
  9087. if (exports.DEBUG) { console.log(state.step, 'MD[' + a + ']', pi2, pi1, '->', d); }
  9088. state.stack.push(Math.round(d * 64));
  9089. }
  9090. // MPPEM[] Measure Pixels Per EM
  9091. // 0x4B
  9092. function MPPEM(state) {
  9093. if (exports.DEBUG) { console.log(state.step, 'MPPEM[]'); }
  9094. state.stack.push(state.ppem);
  9095. }
  9096. // FLIPON[] set the auto FLIP Boolean to ON
  9097. // 0x4D
  9098. function FLIPON(state) {
  9099. if (exports.DEBUG) { console.log(state.step, 'FLIPON[]'); }
  9100. state.autoFlip = true;
  9101. }
  9102. // LT[] Less Than
  9103. // 0x50
  9104. function LT(state) {
  9105. var stack = state.stack;
  9106. var e2 = stack.pop();
  9107. var e1 = stack.pop();
  9108. if (exports.DEBUG) { console.log(state.step, 'LT[]', e2, e1); }
  9109. stack.push(e1 < e2 ? 1 : 0);
  9110. }
  9111. // LTEQ[] Less Than or EQual
  9112. // 0x53
  9113. function LTEQ(state) {
  9114. var stack = state.stack;
  9115. var e2 = stack.pop();
  9116. var e1 = stack.pop();
  9117. if (exports.DEBUG) { console.log(state.step, 'LTEQ[]', e2, e1); }
  9118. stack.push(e1 <= e2 ? 1 : 0);
  9119. }
  9120. // GTEQ[] Greater Than
  9121. // 0x52
  9122. function GT(state) {
  9123. var stack = state.stack;
  9124. var e2 = stack.pop();
  9125. var e1 = stack.pop();
  9126. if (exports.DEBUG) { console.log(state.step, 'GT[]', e2, e1); }
  9127. stack.push(e1 > e2 ? 1 : 0);
  9128. }
  9129. // GTEQ[] Greater Than or EQual
  9130. // 0x53
  9131. function GTEQ(state) {
  9132. var stack = state.stack;
  9133. var e2 = stack.pop();
  9134. var e1 = stack.pop();
  9135. if (exports.DEBUG) { console.log(state.step, 'GTEQ[]', e2, e1); }
  9136. stack.push(e1 >= e2 ? 1 : 0);
  9137. }
  9138. // EQ[] EQual
  9139. // 0x54
  9140. function EQ(state) {
  9141. var stack = state.stack;
  9142. var e2 = stack.pop();
  9143. var e1 = stack.pop();
  9144. if (exports.DEBUG) { console.log(state.step, 'EQ[]', e2, e1); }
  9145. stack.push(e2 === e1 ? 1 : 0);
  9146. }
  9147. // NEQ[] Not EQual
  9148. // 0x55
  9149. function NEQ(state) {
  9150. var stack = state.stack;
  9151. var e2 = stack.pop();
  9152. var e1 = stack.pop();
  9153. if (exports.DEBUG) { console.log(state.step, 'NEQ[]', e2, e1); }
  9154. stack.push(e2 !== e1 ? 1 : 0);
  9155. }
  9156. // ODD[] ODD
  9157. // 0x56
  9158. function ODD(state) {
  9159. var stack = state.stack;
  9160. var n = stack.pop();
  9161. if (exports.DEBUG) { console.log(state.step, 'ODD[]', n); }
  9162. stack.push(Math.trunc(n) % 2 ? 1 : 0);
  9163. }
  9164. // EVEN[] EVEN
  9165. // 0x57
  9166. function EVEN(state) {
  9167. var stack = state.stack;
  9168. var n = stack.pop();
  9169. if (exports.DEBUG) { console.log(state.step, 'EVEN[]', n); }
  9170. stack.push(Math.trunc(n) % 2 ? 0 : 1);
  9171. }
  9172. // IF[] IF test
  9173. // 0x58
  9174. function IF(state) {
  9175. var test = state.stack.pop();
  9176. if (exports.DEBUG) { console.log(state.step, 'IF[]', test); }
  9177. // if test is true it just continues
  9178. // if not the ip is skipped until matching ELSE or EIF
  9179. if (!test) {
  9180. skip(state, true);
  9181. if (exports.DEBUG) { console.log(state.step, 'EIF[]'); }
  9182. }
  9183. }
  9184. // EIF[] End IF
  9185. // 0x59
  9186. function EIF(state) {
  9187. // this can be reached normally when
  9188. // executing an else branch.
  9189. // -> just ignore it
  9190. if (exports.DEBUG) { console.log(state.step, 'EIF[]'); }
  9191. }
  9192. // AND[] logical AND
  9193. // 0x5A
  9194. function AND(state) {
  9195. var stack = state.stack;
  9196. var e2 = stack.pop();
  9197. var e1 = stack.pop();
  9198. if (exports.DEBUG) { console.log(state.step, 'AND[]', e2, e1); }
  9199. stack.push(e2 && e1 ? 1 : 0);
  9200. }
  9201. // OR[] logical OR
  9202. // 0x5B
  9203. function OR(state) {
  9204. var stack = state.stack;
  9205. var e2 = stack.pop();
  9206. var e1 = stack.pop();
  9207. if (exports.DEBUG) { console.log(state.step, 'OR[]', e2, e1); }
  9208. stack.push(e2 || e1 ? 1 : 0);
  9209. }
  9210. // NOT[] logical NOT
  9211. // 0x5C
  9212. function NOT(state) {
  9213. var stack = state.stack;
  9214. var e = stack.pop();
  9215. if (exports.DEBUG) { console.log(state.step, 'NOT[]', e); }
  9216. stack.push(e ? 0 : 1);
  9217. }
  9218. // DELTAP1[] DELTA exception P1
  9219. // DELTAP2[] DELTA exception P2
  9220. // DELTAP3[] DELTA exception P3
  9221. // 0x5D, 0x71, 0x72
  9222. function DELTAP123(b, state) {
  9223. var stack = state.stack;
  9224. var n = stack.pop();
  9225. var fv = state.fv;
  9226. var pv = state.pv;
  9227. var ppem = state.ppem;
  9228. var base = state.deltaBase + (b - 1) * 16;
  9229. var ds = state.deltaShift;
  9230. var z0 = state.z0;
  9231. if (exports.DEBUG) { console.log(state.step, 'DELTAP[' + b + ']', n, stack); }
  9232. for (var i = 0; i < n; i++) {
  9233. var pi = stack.pop();
  9234. var arg = stack.pop();
  9235. var appem = base + ((arg & 0xF0) >> 4);
  9236. if (appem !== ppem) { continue; }
  9237. var mag = (arg & 0x0F) - 8;
  9238. if (mag >= 0) { mag++; }
  9239. if (exports.DEBUG) { console.log(state.step, 'DELTAPFIX', pi, 'by', mag * ds); }
  9240. var p = z0[pi];
  9241. fv.setRelative(p, p, mag * ds, pv);
  9242. }
  9243. }
  9244. // SDB[] Set Delta Base in the graphics state
  9245. // 0x5E
  9246. function SDB(state) {
  9247. var stack = state.stack;
  9248. var n = stack.pop();
  9249. if (exports.DEBUG) { console.log(state.step, 'SDB[]', n); }
  9250. state.deltaBase = n;
  9251. }
  9252. // SDS[] Set Delta Shift in the graphics state
  9253. // 0x5F
  9254. function SDS(state) {
  9255. var stack = state.stack;
  9256. var n = stack.pop();
  9257. if (exports.DEBUG) { console.log(state.step, 'SDS[]', n); }
  9258. state.deltaShift = Math.pow(0.5, n);
  9259. }
  9260. // ADD[] ADD
  9261. // 0x60
  9262. function ADD(state) {
  9263. var stack = state.stack;
  9264. var n2 = stack.pop();
  9265. var n1 = stack.pop();
  9266. if (exports.DEBUG) { console.log(state.step, 'ADD[]', n2, n1); }
  9267. stack.push(n1 + n2);
  9268. }
  9269. // SUB[] SUB
  9270. // 0x61
  9271. function SUB(state) {
  9272. var stack = state.stack;
  9273. var n2 = stack.pop();
  9274. var n1 = stack.pop();
  9275. if (exports.DEBUG) { console.log(state.step, 'SUB[]', n2, n1); }
  9276. stack.push(n1 - n2);
  9277. }
  9278. // DIV[] DIV
  9279. // 0x62
  9280. function DIV(state) {
  9281. var stack = state.stack;
  9282. var n2 = stack.pop();
  9283. var n1 = stack.pop();
  9284. if (exports.DEBUG) { console.log(state.step, 'DIV[]', n2, n1); }
  9285. stack.push(n1 * 64 / n2);
  9286. }
  9287. // MUL[] MUL
  9288. // 0x63
  9289. function MUL(state) {
  9290. var stack = state.stack;
  9291. var n2 = stack.pop();
  9292. var n1 = stack.pop();
  9293. if (exports.DEBUG) { console.log(state.step, 'MUL[]', n2, n1); }
  9294. stack.push(n1 * n2 / 64);
  9295. }
  9296. // ABS[] ABSolute value
  9297. // 0x64
  9298. function ABS(state) {
  9299. var stack = state.stack;
  9300. var n = stack.pop();
  9301. if (exports.DEBUG) { console.log(state.step, 'ABS[]', n); }
  9302. stack.push(Math.abs(n));
  9303. }
  9304. // NEG[] NEGate
  9305. // 0x65
  9306. function NEG(state) {
  9307. var stack = state.stack;
  9308. var n = stack.pop();
  9309. if (exports.DEBUG) { console.log(state.step, 'NEG[]', n); }
  9310. stack.push(-n);
  9311. }
  9312. // FLOOR[] FLOOR
  9313. // 0x66
  9314. function FLOOR(state) {
  9315. var stack = state.stack;
  9316. var n = stack.pop();
  9317. if (exports.DEBUG) { console.log(state.step, 'FLOOR[]', n); }
  9318. stack.push(Math.floor(n / 0x40) * 0x40);
  9319. }
  9320. // CEILING[] CEILING
  9321. // 0x67
  9322. function CEILING(state) {
  9323. var stack = state.stack;
  9324. var n = stack.pop();
  9325. if (exports.DEBUG) { console.log(state.step, 'CEILING[]', n); }
  9326. stack.push(Math.ceil(n / 0x40) * 0x40);
  9327. }
  9328. // ROUND[ab] ROUND value
  9329. // 0x68-0x6B
  9330. function ROUND(dt, state) {
  9331. var stack = state.stack;
  9332. var n = stack.pop();
  9333. if (exports.DEBUG) { console.log(state.step, 'ROUND[]'); }
  9334. stack.push(state.round(n / 0x40) * 0x40);
  9335. }
  9336. // WCVTF[] Write Control Value Table in Funits
  9337. // 0x70
  9338. function WCVTF(state) {
  9339. var stack = state.stack;
  9340. var v = stack.pop();
  9341. var l = stack.pop();
  9342. if (exports.DEBUG) { console.log(state.step, 'WCVTF[]', v, l); }
  9343. state.cvt[l] = v * state.ppem / state.font.unitsPerEm;
  9344. }
  9345. // DELTAC1[] DELTA exception C1
  9346. // DELTAC2[] DELTA exception C2
  9347. // DELTAC3[] DELTA exception C3
  9348. // 0x73, 0x74, 0x75
  9349. function DELTAC123(b, state) {
  9350. var stack = state.stack;
  9351. var n = stack.pop();
  9352. var ppem = state.ppem;
  9353. var base = state.deltaBase + (b - 1) * 16;
  9354. var ds = state.deltaShift;
  9355. if (exports.DEBUG) { console.log(state.step, 'DELTAC[' + b + ']', n, stack); }
  9356. for (var i = 0; i < n; i++) {
  9357. var c = stack.pop();
  9358. var arg = stack.pop();
  9359. var appem = base + ((arg & 0xF0) >> 4);
  9360. if (appem !== ppem) { continue; }
  9361. var mag = (arg & 0x0F) - 8;
  9362. if (mag >= 0) { mag++; }
  9363. var delta = mag * ds;
  9364. if (exports.DEBUG) { console.log(state.step, 'DELTACFIX', c, 'by', delta); }
  9365. state.cvt[c] += delta;
  9366. }
  9367. }
  9368. // SROUND[] Super ROUND
  9369. // 0x76
  9370. function SROUND(state) {
  9371. var n = state.stack.pop();
  9372. if (exports.DEBUG) { console.log(state.step, 'SROUND[]', n); }
  9373. state.round = roundSuper;
  9374. var period;
  9375. switch (n & 0xC0) {
  9376. case 0x00:
  9377. period = 0.5;
  9378. break;
  9379. case 0x40:
  9380. period = 1;
  9381. break;
  9382. case 0x80:
  9383. period = 2;
  9384. break;
  9385. default:
  9386. throw new Error('invalid SROUND value');
  9387. }
  9388. state.srPeriod = period;
  9389. switch (n & 0x30) {
  9390. case 0x00:
  9391. state.srPhase = 0;
  9392. break;
  9393. case 0x10:
  9394. state.srPhase = 0.25 * period;
  9395. break;
  9396. case 0x20:
  9397. state.srPhase = 0.5 * period;
  9398. break;
  9399. case 0x30:
  9400. state.srPhase = 0.75 * period;
  9401. break;
  9402. default: throw new Error('invalid SROUND value');
  9403. }
  9404. n &= 0x0F;
  9405. if (n === 0) { state.srThreshold = 0; }
  9406. else { state.srThreshold = (n / 8 - 0.5) * period; }
  9407. }
  9408. // S45ROUND[] Super ROUND 45 degrees
  9409. // 0x77
  9410. function S45ROUND(state) {
  9411. var n = state.stack.pop();
  9412. if (exports.DEBUG) { console.log(state.step, 'S45ROUND[]', n); }
  9413. state.round = roundSuper;
  9414. var period;
  9415. switch (n & 0xC0) {
  9416. case 0x00:
  9417. period = Math.sqrt(2) / 2;
  9418. break;
  9419. case 0x40:
  9420. period = Math.sqrt(2);
  9421. break;
  9422. case 0x80:
  9423. period = 2 * Math.sqrt(2);
  9424. break;
  9425. default:
  9426. throw new Error('invalid S45ROUND value');
  9427. }
  9428. state.srPeriod = period;
  9429. switch (n & 0x30) {
  9430. case 0x00:
  9431. state.srPhase = 0;
  9432. break;
  9433. case 0x10:
  9434. state.srPhase = 0.25 * period;
  9435. break;
  9436. case 0x20:
  9437. state.srPhase = 0.5 * period;
  9438. break;
  9439. case 0x30:
  9440. state.srPhase = 0.75 * period;
  9441. break;
  9442. default:
  9443. throw new Error('invalid S45ROUND value');
  9444. }
  9445. n &= 0x0F;
  9446. if (n === 0) { state.srThreshold = 0; }
  9447. else { state.srThreshold = (n / 8 - 0.5) * period; }
  9448. }
  9449. // ROFF[] Round Off
  9450. // 0x7A
  9451. function ROFF(state) {
  9452. if (exports.DEBUG) { console.log(state.step, 'ROFF[]'); }
  9453. state.round = roundOff;
  9454. }
  9455. // RUTG[] Round Up To Grid
  9456. // 0x7C
  9457. function RUTG(state) {
  9458. if (exports.DEBUG) { console.log(state.step, 'RUTG[]'); }
  9459. state.round = roundUpToGrid;
  9460. }
  9461. // RDTG[] Round Down To Grid
  9462. // 0x7D
  9463. function RDTG(state) {
  9464. if (exports.DEBUG) { console.log(state.step, 'RDTG[]'); }
  9465. state.round = roundDownToGrid;
  9466. }
  9467. // SCANCTRL[] SCAN conversion ConTRoL
  9468. // 0x85
  9469. function SCANCTRL(state) {
  9470. var n = state.stack.pop();
  9471. // ignored by opentype.js
  9472. if (exports.DEBUG) { console.log(state.step, 'SCANCTRL[]', n); }
  9473. }
  9474. // SDPVTL[a] Set Dual Projection Vector To Line
  9475. // 0x86-0x87
  9476. function SDPVTL(a, state) {
  9477. var stack = state.stack;
  9478. var p2i = stack.pop();
  9479. var p1i = stack.pop();
  9480. var p2 = state.z2[p2i];
  9481. var p1 = state.z1[p1i];
  9482. if (exports.DEBUG) { console.log(state.step, 'SDPVTL[' + a + ']', p2i, p1i); }
  9483. var dx;
  9484. var dy;
  9485. if (!a) {
  9486. dx = p1.x - p2.x;
  9487. dy = p1.y - p2.y;
  9488. } else {
  9489. dx = p2.y - p1.y;
  9490. dy = p1.x - p2.x;
  9491. }
  9492. state.dpv = getUnitVector(dx, dy);
  9493. }
  9494. // GETINFO[] GET INFOrmation
  9495. // 0x88
  9496. function GETINFO(state) {
  9497. var stack = state.stack;
  9498. var sel = stack.pop();
  9499. var r = 0;
  9500. if (exports.DEBUG) { console.log(state.step, 'GETINFO[]', sel); }
  9501. // v35 as in no subpixel hinting
  9502. if (sel & 0x01) { r = 35; }
  9503. // TODO rotation and stretch currently not supported
  9504. // and thus those GETINFO are always 0.
  9505. // opentype.js is always gray scaling
  9506. if (sel & 0x20) { r |= 0x1000; }
  9507. stack.push(r);
  9508. }
  9509. // ROLL[] ROLL the top three stack elements
  9510. // 0x8A
  9511. function ROLL(state) {
  9512. var stack = state.stack;
  9513. var a = stack.pop();
  9514. var b = stack.pop();
  9515. var c = stack.pop();
  9516. if (exports.DEBUG) { console.log(state.step, 'ROLL[]'); }
  9517. stack.push(b);
  9518. stack.push(a);
  9519. stack.push(c);
  9520. }
  9521. // MAX[] MAXimum of top two stack elements
  9522. // 0x8B
  9523. function MAX(state) {
  9524. var stack = state.stack;
  9525. var e2 = stack.pop();
  9526. var e1 = stack.pop();
  9527. if (exports.DEBUG) { console.log(state.step, 'MAX[]', e2, e1); }
  9528. stack.push(Math.max(e1, e2));
  9529. }
  9530. // MIN[] MINimum of top two stack elements
  9531. // 0x8C
  9532. function MIN(state) {
  9533. var stack = state.stack;
  9534. var e2 = stack.pop();
  9535. var e1 = stack.pop();
  9536. if (exports.DEBUG) { console.log(state.step, 'MIN[]', e2, e1); }
  9537. stack.push(Math.min(e1, e2));
  9538. }
  9539. // SCANTYPE[] SCANTYPE
  9540. // 0x8D
  9541. function SCANTYPE(state) {
  9542. var n = state.stack.pop();
  9543. // ignored by opentype.js
  9544. if (exports.DEBUG) { console.log(state.step, 'SCANTYPE[]', n); }
  9545. }
  9546. // INSTCTRL[] INSTCTRL
  9547. // 0x8D
  9548. function INSTCTRL(state) {
  9549. var s = state.stack.pop();
  9550. var v = state.stack.pop();
  9551. if (exports.DEBUG) { console.log(state.step, 'INSTCTRL[]', s, v); }
  9552. switch (s) {
  9553. case 1 : state.inhibitGridFit = !!v; return;
  9554. case 2 : state.ignoreCvt = !!v; return;
  9555. default: throw new Error('invalid INSTCTRL[] selector');
  9556. }
  9557. }
  9558. // PUSHB[abc] PUSH Bytes
  9559. // 0xB0-0xB7
  9560. function PUSHB(n, state) {
  9561. var stack = state.stack;
  9562. var prog = state.prog;
  9563. var ip = state.ip;
  9564. if (exports.DEBUG) { console.log(state.step, 'PUSHB[' + n + ']'); }
  9565. for (var i = 0; i < n; i++) { stack.push(prog[++ip]); }
  9566. state.ip = ip;
  9567. }
  9568. // PUSHW[abc] PUSH Words
  9569. // 0xB8-0xBF
  9570. function PUSHW(n, state) {
  9571. var ip = state.ip;
  9572. var prog = state.prog;
  9573. var stack = state.stack;
  9574. if (exports.DEBUG) { console.log(state.ip, 'PUSHW[' + n + ']'); }
  9575. for (var i = 0; i < n; i++) {
  9576. var w = (prog[++ip] << 8) | prog[++ip];
  9577. if (w & 0x8000) { w = -((w ^ 0xffff) + 1); }
  9578. stack.push(w);
  9579. }
  9580. state.ip = ip;
  9581. }
  9582. // MDRP[abcde] Move Direct Relative Point
  9583. // 0xD0-0xEF
  9584. // (if indirect is 0)
  9585. //
  9586. // and
  9587. //
  9588. // MIRP[abcde] Move Indirect Relative Point
  9589. // 0xE0-0xFF
  9590. // (if indirect is 1)
  9591. function MDRP_MIRP(indirect, setRp0, keepD, ro, dt, state) {
  9592. var stack = state.stack;
  9593. var cvte = indirect && stack.pop();
  9594. var pi = stack.pop();
  9595. var rp0i = state.rp0;
  9596. var rp = state.z0[rp0i];
  9597. var p = state.z1[pi];
  9598. var md = state.minDis;
  9599. var fv = state.fv;
  9600. var pv = state.dpv;
  9601. var od; // original distance
  9602. var d; // moving distance
  9603. var sign; // sign of distance
  9604. var cv;
  9605. d = od = pv.distance(p, rp, true, true);
  9606. sign = d >= 0 ? 1 : -1; // Math.sign would be 0 in case of 0
  9607. // TODO consider autoFlip
  9608. d = Math.abs(d);
  9609. if (indirect) {
  9610. cv = state.cvt[cvte];
  9611. if (ro && Math.abs(d - cv) < state.cvCutIn) { d = cv; }
  9612. }
  9613. if (keepD && d < md) { d = md; }
  9614. if (ro) { d = state.round(d); }
  9615. fv.setRelative(p, rp, sign * d, pv);
  9616. fv.touch(p);
  9617. if (exports.DEBUG) {
  9618. console.log(
  9619. state.step,
  9620. (indirect ? 'MIRP[' : 'MDRP[') +
  9621. (setRp0 ? 'M' : 'm') +
  9622. (keepD ? '>' : '_') +
  9623. (ro ? 'R' : '_') +
  9624. (dt === 0 ? 'Gr' : (dt === 1 ? 'Bl' : (dt === 2 ? 'Wh' : ''))) +
  9625. ']',
  9626. indirect ?
  9627. cvte + '(' + state.cvt[cvte] + ',' + cv + ')' :
  9628. '',
  9629. pi,
  9630. '(d =', od, '->', sign * d, ')'
  9631. );
  9632. }
  9633. state.rp1 = state.rp0;
  9634. state.rp2 = pi;
  9635. if (setRp0) { state.rp0 = pi; }
  9636. }
  9637. /*
  9638. * The instruction table.
  9639. */
  9640. instructionTable = [
  9641. /* 0x00 */ SVTCA.bind(undefined, yUnitVector),
  9642. /* 0x01 */ SVTCA.bind(undefined, xUnitVector),
  9643. /* 0x02 */ SPVTCA.bind(undefined, yUnitVector),
  9644. /* 0x03 */ SPVTCA.bind(undefined, xUnitVector),
  9645. /* 0x04 */ SFVTCA.bind(undefined, yUnitVector),
  9646. /* 0x05 */ SFVTCA.bind(undefined, xUnitVector),
  9647. /* 0x06 */ SPVTL.bind(undefined, 0),
  9648. /* 0x07 */ SPVTL.bind(undefined, 1),
  9649. /* 0x08 */ SFVTL.bind(undefined, 0),
  9650. /* 0x09 */ SFVTL.bind(undefined, 1),
  9651. /* 0x0A */ SPVFS,
  9652. /* 0x0B */ SFVFS,
  9653. /* 0x0C */ GPV,
  9654. /* 0x0D */ GFV,
  9655. /* 0x0E */ SFVTPV,
  9656. /* 0x0F */ ISECT,
  9657. /* 0x10 */ SRP0,
  9658. /* 0x11 */ SRP1,
  9659. /* 0x12 */ SRP2,
  9660. /* 0x13 */ SZP0,
  9661. /* 0x14 */ SZP1,
  9662. /* 0x15 */ SZP2,
  9663. /* 0x16 */ SZPS,
  9664. /* 0x17 */ SLOOP,
  9665. /* 0x18 */ RTG,
  9666. /* 0x19 */ RTHG,
  9667. /* 0x1A */ SMD,
  9668. /* 0x1B */ ELSE,
  9669. /* 0x1C */ JMPR,
  9670. /* 0x1D */ SCVTCI,
  9671. /* 0x1E */ undefined, // TODO SSWCI
  9672. /* 0x1F */ undefined, // TODO SSW
  9673. /* 0x20 */ DUP,
  9674. /* 0x21 */ POP,
  9675. /* 0x22 */ CLEAR,
  9676. /* 0x23 */ SWAP,
  9677. /* 0x24 */ DEPTH,
  9678. /* 0x25 */ CINDEX,
  9679. /* 0x26 */ MINDEX,
  9680. /* 0x27 */ undefined, // TODO ALIGNPTS
  9681. /* 0x28 */ undefined,
  9682. /* 0x29 */ undefined, // TODO UTP
  9683. /* 0x2A */ LOOPCALL,
  9684. /* 0x2B */ CALL,
  9685. /* 0x2C */ FDEF,
  9686. /* 0x2D */ undefined, // ENDF (eaten by FDEF)
  9687. /* 0x2E */ MDAP.bind(undefined, 0),
  9688. /* 0x2F */ MDAP.bind(undefined, 1),
  9689. /* 0x30 */ IUP.bind(undefined, yUnitVector),
  9690. /* 0x31 */ IUP.bind(undefined, xUnitVector),
  9691. /* 0x32 */ SHP.bind(undefined, 0),
  9692. /* 0x33 */ SHP.bind(undefined, 1),
  9693. /* 0x34 */ SHC.bind(undefined, 0),
  9694. /* 0x35 */ SHC.bind(undefined, 1),
  9695. /* 0x36 */ SHZ.bind(undefined, 0),
  9696. /* 0x37 */ SHZ.bind(undefined, 1),
  9697. /* 0x38 */ SHPIX,
  9698. /* 0x39 */ IP,
  9699. /* 0x3A */ MSIRP.bind(undefined, 0),
  9700. /* 0x3B */ MSIRP.bind(undefined, 1),
  9701. /* 0x3C */ ALIGNRP,
  9702. /* 0x3D */ RTDG,
  9703. /* 0x3E */ MIAP.bind(undefined, 0),
  9704. /* 0x3F */ MIAP.bind(undefined, 1),
  9705. /* 0x40 */ NPUSHB,
  9706. /* 0x41 */ NPUSHW,
  9707. /* 0x42 */ WS,
  9708. /* 0x43 */ RS,
  9709. /* 0x44 */ WCVTP,
  9710. /* 0x45 */ RCVT,
  9711. /* 0x46 */ GC.bind(undefined, 0),
  9712. /* 0x47 */ GC.bind(undefined, 1),
  9713. /* 0x48 */ undefined, // TODO SCFS
  9714. /* 0x49 */ MD.bind(undefined, 0),
  9715. /* 0x4A */ MD.bind(undefined, 1),
  9716. /* 0x4B */ MPPEM,
  9717. /* 0x4C */ undefined, // TODO MPS
  9718. /* 0x4D */ FLIPON,
  9719. /* 0x4E */ undefined, // TODO FLIPOFF
  9720. /* 0x4F */ undefined, // TODO DEBUG
  9721. /* 0x50 */ LT,
  9722. /* 0x51 */ LTEQ,
  9723. /* 0x52 */ GT,
  9724. /* 0x53 */ GTEQ,
  9725. /* 0x54 */ EQ,
  9726. /* 0x55 */ NEQ,
  9727. /* 0x56 */ ODD,
  9728. /* 0x57 */ EVEN,
  9729. /* 0x58 */ IF,
  9730. /* 0x59 */ EIF,
  9731. /* 0x5A */ AND,
  9732. /* 0x5B */ OR,
  9733. /* 0x5C */ NOT,
  9734. /* 0x5D */ DELTAP123.bind(undefined, 1),
  9735. /* 0x5E */ SDB,
  9736. /* 0x5F */ SDS,
  9737. /* 0x60 */ ADD,
  9738. /* 0x61 */ SUB,
  9739. /* 0x62 */ DIV,
  9740. /* 0x63 */ MUL,
  9741. /* 0x64 */ ABS,
  9742. /* 0x65 */ NEG,
  9743. /* 0x66 */ FLOOR,
  9744. /* 0x67 */ CEILING,
  9745. /* 0x68 */ ROUND.bind(undefined, 0),
  9746. /* 0x69 */ ROUND.bind(undefined, 1),
  9747. /* 0x6A */ ROUND.bind(undefined, 2),
  9748. /* 0x6B */ ROUND.bind(undefined, 3),
  9749. /* 0x6C */ undefined, // TODO NROUND[ab]
  9750. /* 0x6D */ undefined, // TODO NROUND[ab]
  9751. /* 0x6E */ undefined, // TODO NROUND[ab]
  9752. /* 0x6F */ undefined, // TODO NROUND[ab]
  9753. /* 0x70 */ WCVTF,
  9754. /* 0x71 */ DELTAP123.bind(undefined, 2),
  9755. /* 0x72 */ DELTAP123.bind(undefined, 3),
  9756. /* 0x73 */ DELTAC123.bind(undefined, 1),
  9757. /* 0x74 */ DELTAC123.bind(undefined, 2),
  9758. /* 0x75 */ DELTAC123.bind(undefined, 3),
  9759. /* 0x76 */ SROUND,
  9760. /* 0x77 */ S45ROUND,
  9761. /* 0x78 */ undefined, // TODO JROT[]
  9762. /* 0x79 */ undefined, // TODO JROF[]
  9763. /* 0x7A */ ROFF,
  9764. /* 0x7B */ undefined,
  9765. /* 0x7C */ RUTG,
  9766. /* 0x7D */ RDTG,
  9767. /* 0x7E */ POP, // actually SANGW, supposed to do only a pop though
  9768. /* 0x7F */ POP, // actually AA, supposed to do only a pop though
  9769. /* 0x80 */ undefined, // TODO FLIPPT
  9770. /* 0x81 */ undefined, // TODO FLIPRGON
  9771. /* 0x82 */ undefined, // TODO FLIPRGOFF
  9772. /* 0x83 */ undefined,
  9773. /* 0x84 */ undefined,
  9774. /* 0x85 */ SCANCTRL,
  9775. /* 0x86 */ SDPVTL.bind(undefined, 0),
  9776. /* 0x87 */ SDPVTL.bind(undefined, 1),
  9777. /* 0x88 */ GETINFO,
  9778. /* 0x89 */ undefined, // TODO IDEF
  9779. /* 0x8A */ ROLL,
  9780. /* 0x8B */ MAX,
  9781. /* 0x8C */ MIN,
  9782. /* 0x8D */ SCANTYPE,
  9783. /* 0x8E */ INSTCTRL,
  9784. /* 0x8F */ undefined,
  9785. /* 0x90 */ undefined,
  9786. /* 0x91 */ undefined,
  9787. /* 0x92 */ undefined,
  9788. /* 0x93 */ undefined,
  9789. /* 0x94 */ undefined,
  9790. /* 0x95 */ undefined,
  9791. /* 0x96 */ undefined,
  9792. /* 0x97 */ undefined,
  9793. /* 0x98 */ undefined,
  9794. /* 0x99 */ undefined,
  9795. /* 0x9A */ undefined,
  9796. /* 0x9B */ undefined,
  9797. /* 0x9C */ undefined,
  9798. /* 0x9D */ undefined,
  9799. /* 0x9E */ undefined,
  9800. /* 0x9F */ undefined,
  9801. /* 0xA0 */ undefined,
  9802. /* 0xA1 */ undefined,
  9803. /* 0xA2 */ undefined,
  9804. /* 0xA3 */ undefined,
  9805. /* 0xA4 */ undefined,
  9806. /* 0xA5 */ undefined,
  9807. /* 0xA6 */ undefined,
  9808. /* 0xA7 */ undefined,
  9809. /* 0xA8 */ undefined,
  9810. /* 0xA9 */ undefined,
  9811. /* 0xAA */ undefined,
  9812. /* 0xAB */ undefined,
  9813. /* 0xAC */ undefined,
  9814. /* 0xAD */ undefined,
  9815. /* 0xAE */ undefined,
  9816. /* 0xAF */ undefined,
  9817. /* 0xB0 */ PUSHB.bind(undefined, 1),
  9818. /* 0xB1 */ PUSHB.bind(undefined, 2),
  9819. /* 0xB2 */ PUSHB.bind(undefined, 3),
  9820. /* 0xB3 */ PUSHB.bind(undefined, 4),
  9821. /* 0xB4 */ PUSHB.bind(undefined, 5),
  9822. /* 0xB5 */ PUSHB.bind(undefined, 6),
  9823. /* 0xB6 */ PUSHB.bind(undefined, 7),
  9824. /* 0xB7 */ PUSHB.bind(undefined, 8),
  9825. /* 0xB8 */ PUSHW.bind(undefined, 1),
  9826. /* 0xB9 */ PUSHW.bind(undefined, 2),
  9827. /* 0xBA */ PUSHW.bind(undefined, 3),
  9828. /* 0xBB */ PUSHW.bind(undefined, 4),
  9829. /* 0xBC */ PUSHW.bind(undefined, 5),
  9830. /* 0xBD */ PUSHW.bind(undefined, 6),
  9831. /* 0xBE */ PUSHW.bind(undefined, 7),
  9832. /* 0xBF */ PUSHW.bind(undefined, 8),
  9833. /* 0xC0 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 0),
  9834. /* 0xC1 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 1),
  9835. /* 0xC2 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 2),
  9836. /* 0xC3 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 3),
  9837. /* 0xC4 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 0),
  9838. /* 0xC5 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 1),
  9839. /* 0xC6 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 2),
  9840. /* 0xC7 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 3),
  9841. /* 0xC8 */ MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 0),
  9842. /* 0xC9 */ MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 1),
  9843. /* 0xCA */ MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 2),
  9844. /* 0xCB */ MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 3),
  9845. /* 0xCC */ MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 0),
  9846. /* 0xCD */ MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 1),
  9847. /* 0xCE */ MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 2),
  9848. /* 0xCF */ MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 3),
  9849. /* 0xD0 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 0),
  9850. /* 0xD1 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 1),
  9851. /* 0xD2 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 2),
  9852. /* 0xD3 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 3),
  9853. /* 0xD4 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 0),
  9854. /* 0xD5 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 1),
  9855. /* 0xD6 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 2),
  9856. /* 0xD7 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 3),
  9857. /* 0xD8 */ MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 0),
  9858. /* 0xD9 */ MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 1),
  9859. /* 0xDA */ MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 2),
  9860. /* 0xDB */ MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 3),
  9861. /* 0xDC */ MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 0),
  9862. /* 0xDD */ MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 1),
  9863. /* 0xDE */ MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 2),
  9864. /* 0xDF */ MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 3),
  9865. /* 0xE0 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 0),
  9866. /* 0xE1 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 1),
  9867. /* 0xE2 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 2),
  9868. /* 0xE3 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 3),
  9869. /* 0xE4 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 0),
  9870. /* 0xE5 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 1),
  9871. /* 0xE6 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 2),
  9872. /* 0xE7 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 3),
  9873. /* 0xE8 */ MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 0),
  9874. /* 0xE9 */ MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 1),
  9875. /* 0xEA */ MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 2),
  9876. /* 0xEB */ MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 3),
  9877. /* 0xEC */ MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 0),
  9878. /* 0xED */ MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 1),
  9879. /* 0xEE */ MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 2),
  9880. /* 0xEF */ MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 3),
  9881. /* 0xF0 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 0),
  9882. /* 0xF1 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 1),
  9883. /* 0xF2 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 2),
  9884. /* 0xF3 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 3),
  9885. /* 0xF4 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 0),
  9886. /* 0xF5 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 1),
  9887. /* 0xF6 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 2),
  9888. /* 0xF7 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 3),
  9889. /* 0xF8 */ MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 0),
  9890. /* 0xF9 */ MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 1),
  9891. /* 0xFA */ MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 2),
  9892. /* 0xFB */ MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 3),
  9893. /* 0xFC */ MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 0),
  9894. /* 0xFD */ MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 1),
  9895. /* 0xFE */ MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 2),
  9896. /* 0xFF */ MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 3)
  9897. ];
  9898. /*****************************
  9899. Mathematical Considerations
  9900. ******************************
  9901. fv ... refers to freedom vector
  9902. pv ... refers to projection vector
  9903. rp ... refers to reference point
  9904. p ... refers to to point being operated on
  9905. d ... refers to distance
  9906. SETRELATIVE:
  9907. ============
  9908. case freedom vector == x-axis:
  9909. ------------------------------
  9910. (pv)
  9911. .-'
  9912. rpd .-'
  9913. .-*
  9914. d .-'90°'
  9915. .-' '
  9916. .-' '
  9917. *-' ' b
  9918. rp '
  9919. '
  9920. '
  9921. p *----------*-------------- (fv)
  9922. pm
  9923. rpdx = rpx + d * pv.x
  9924. rpdy = rpy + d * pv.y
  9925. equation of line b
  9926. y - rpdy = pvns * (x- rpdx)
  9927. y = p.y
  9928. x = rpdx + ( p.y - rpdy ) / pvns
  9929. case freedom vector == y-axis:
  9930. ------------------------------
  9931. * pm
  9932. |\
  9933. | \
  9934. | \
  9935. | \
  9936. | \
  9937. | \
  9938. | \
  9939. | \
  9940. | \
  9941. | \ b
  9942. | \
  9943. | \
  9944. | \ .-' (pv)
  9945. | 90° \.-'
  9946. | .-'* rpd
  9947. | .-'
  9948. * *-' d
  9949. p rp
  9950. rpdx = rpx + d * pv.x
  9951. rpdy = rpy + d * pv.y
  9952. equation of line b:
  9953. pvns ... normal slope to pv
  9954. y - rpdy = pvns * (x - rpdx)
  9955. x = p.x
  9956. y = rpdy + pvns * (p.x - rpdx)
  9957. generic case:
  9958. -------------
  9959. .'(fv)
  9960. .'
  9961. .* pm
  9962. .' !
  9963. .' .
  9964. .' !
  9965. .' . b
  9966. .' !
  9967. * .
  9968. p !
  9969. 90° . ... (pv)
  9970. ...-*-'''
  9971. ...---''' rpd
  9972. ...---''' d
  9973. *--'''
  9974. rp
  9975. rpdx = rpx + d * pv.x
  9976. rpdy = rpy + d * pv.y
  9977. equation of line b:
  9978. pvns... normal slope to pv
  9979. y - rpdy = pvns * (x - rpdx)
  9980. equation of freedom vector line:
  9981. fvs ... slope of freedom vector (=fy/fx)
  9982. y - py = fvs * (x - px)
  9983. on pm both equations are true for same x/y
  9984. y - rpdy = pvns * (x - rpdx)
  9985. y - py = fvs * (x - px)
  9986. form to y and set equal:
  9987. pvns * (x - rpdx) + rpdy = fvs * (x - px) + py
  9988. expand:
  9989. pvns * x - pvns * rpdx + rpdy = fvs * x - fvs * px + py
  9990. switch:
  9991. fvs * x - fvs * px + py = pvns * x - pvns * rpdx + rpdy
  9992. solve for x:
  9993. fvs * x - pvns * x = fvs * px - pvns * rpdx - py + rpdy
  9994. fvs * px - pvns * rpdx + rpdy - py
  9995. x = -----------------------------------
  9996. fvs - pvns
  9997. and:
  9998. y = fvs * (x - px) + py
  9999. INTERPOLATE:
  10000. ============
  10001. Examples of point interpolation.
  10002. The weight of the movement of the reference point gets bigger
  10003. the further the other reference point is away, thus the safest
  10004. option (that is avoiding 0/0 divisions) is to weight the
  10005. original distance of the other point by the sum of both distances.
  10006. If the sum of both distances is 0, then move the point by the
  10007. arithmetic average of the movement of both reference points.
  10008. (+6)
  10009. rp1o *---->*rp1
  10010. . . (+12)
  10011. . . rp2o *---------->* rp2
  10012. . . . .
  10013. . . . .
  10014. . 10 20 . .
  10015. |.........|...................| .
  10016. . . .
  10017. . . (+8) .
  10018. po *------>*p .
  10019. . . .
  10020. . 12 . 24 .
  10021. |...........|.......................|
  10022. 36
  10023. -------
  10024. (+10)
  10025. rp1o *-------->*rp1
  10026. . . (-10)
  10027. . . rp2 *<---------* rpo2
  10028. . . . .
  10029. . . . .
  10030. . 10 . 30 . .
  10031. |.........|.............................|
  10032. . .
  10033. . (+5) .
  10034. po *--->* p .
  10035. . . .
  10036. . . 20 .
  10037. |....|..............|
  10038. 5 15
  10039. -------
  10040. (+10)
  10041. rp1o *-------->*rp1
  10042. . .
  10043. . .
  10044. rp2o *-------->*rp2
  10045. (+10)
  10046. po *-------->* p
  10047. -------
  10048. (+10)
  10049. rp1o *-------->*rp1
  10050. . .
  10051. . .(+30)
  10052. rp2o *---------------------------->*rp2
  10053. (+25)
  10054. po *----------------------->* p
  10055. vim: set ts=4 sw=4 expandtab:
  10056. *****/
  10057. /**
  10058. * Converts a string into a list of tokens.
  10059. */
  10060. /**
  10061. * Create a new token
  10062. * @param {string} char a single char
  10063. */
  10064. function Token(char) {
  10065. this.char = char;
  10066. this.state = {};
  10067. this.activeState = null;
  10068. }
  10069. /**
  10070. * Create a new context range
  10071. * @param {number} startIndex range start index
  10072. * @param {number} endOffset range end index offset
  10073. * @param {string} contextName owner context name
  10074. */
  10075. function ContextRange(startIndex, endOffset, contextName) {
  10076. this.contextName = contextName;
  10077. this.startIndex = startIndex;
  10078. this.endOffset = endOffset;
  10079. }
  10080. /**
  10081. * Check context start and end
  10082. * @param {string} contextName a unique context name
  10083. * @param {function} checkStart a predicate function the indicates a context's start
  10084. * @param {function} checkEnd a predicate function the indicates a context's end
  10085. */
  10086. function ContextChecker(contextName, checkStart, checkEnd) {
  10087. this.contextName = contextName;
  10088. this.openRange = null;
  10089. this.ranges = [];
  10090. this.checkStart = checkStart;
  10091. this.checkEnd = checkEnd;
  10092. }
  10093. /**
  10094. * @typedef ContextParams
  10095. * @type Object
  10096. * @property {array} context context items
  10097. * @property {number} currentIndex current item index
  10098. */
  10099. /**
  10100. * Create a context params
  10101. * @param {array} context a list of items
  10102. * @param {number} currentIndex current item index
  10103. */
  10104. function ContextParams(context, currentIndex) {
  10105. this.context = context;
  10106. this.index = currentIndex;
  10107. this.length = context.length;
  10108. this.current = context[currentIndex];
  10109. this.backtrack = context.slice(0, currentIndex);
  10110. this.lookahead = context.slice(currentIndex + 1);
  10111. }
  10112. /**
  10113. * Create an event instance
  10114. * @param {string} eventId event unique id
  10115. */
  10116. function Event(eventId) {
  10117. this.eventId = eventId;
  10118. this.subscribers = [];
  10119. }
  10120. /**
  10121. * Initialize a core events and auto subscribe required event handlers
  10122. * @param {any} events an object that enlists core events handlers
  10123. */
  10124. function initializeCoreEvents(events) {
  10125. var this$1 = this;
  10126. var coreEvents = [
  10127. 'start', 'end', 'next', 'newToken', 'contextStart',
  10128. 'contextEnd', 'insertToken', 'removeToken', 'removeRange',
  10129. 'replaceToken', 'replaceRange', 'composeRUD', 'updateContextsRanges'
  10130. ];
  10131. coreEvents.forEach(function (eventId) {
  10132. Object.defineProperty(this$1.events, eventId, {
  10133. value: new Event(eventId)
  10134. });
  10135. });
  10136. if (!!events) {
  10137. coreEvents.forEach(function (eventId) {
  10138. var event = events[eventId];
  10139. if (typeof event === 'function') {
  10140. this$1.events[eventId].subscribe(event);
  10141. }
  10142. });
  10143. }
  10144. var requiresContextUpdate = [
  10145. 'insertToken', 'removeToken', 'removeRange',
  10146. 'replaceToken', 'replaceRange', 'composeRUD'
  10147. ];
  10148. requiresContextUpdate.forEach(function (eventId) {
  10149. this$1.events[eventId].subscribe(
  10150. this$1.updateContextsRanges
  10151. );
  10152. });
  10153. }
  10154. /**
  10155. * Converts a string into a list of tokens
  10156. * @param {any} events tokenizer core events
  10157. */
  10158. function Tokenizer(events) {
  10159. this.tokens = [];
  10160. this.registeredContexts = {};
  10161. this.contextCheckers = [];
  10162. this.events = {};
  10163. this.registeredModifiers = [];
  10164. initializeCoreEvents.call(this, events);
  10165. }
  10166. /**
  10167. * Sets the state of a token, usually called by a state modifier.
  10168. * @param {string} key state item key
  10169. * @param {any} value state item value
  10170. */
  10171. Token.prototype.setState = function(key, value) {
  10172. this.state[key] = value;
  10173. this.activeState = { key: key, value: this.state[key] };
  10174. return this.activeState;
  10175. };
  10176. Token.prototype.getState = function (stateId) {
  10177. return this.state[stateId] || null;
  10178. };
  10179. /**
  10180. * Checks if an index exists in the tokens list.
  10181. * @param {number} index token index
  10182. */
  10183. Tokenizer.prototype.inboundIndex = function(index) {
  10184. return index >= 0 && index < this.tokens.length;
  10185. };
  10186. /**
  10187. * Compose and apply a list of operations (replace, update, delete)
  10188. * @param {array} RUDs replace, update and delete operations
  10189. * TODO: Perf. Optimization (lengthBefore === lengthAfter ? dispatch once)
  10190. */
  10191. Tokenizer.prototype.composeRUD = function (RUDs) {
  10192. var this$1 = this;
  10193. var silent = true;
  10194. var state = RUDs.map(function (RUD) { return (
  10195. this$1[RUD[0]].apply(this$1, RUD.slice(1).concat(silent))
  10196. ); });
  10197. var hasFAILObject = function (obj) { return (
  10198. typeof obj === 'object' &&
  10199. obj.hasOwnProperty('FAIL')
  10200. ); };
  10201. if (state.every(hasFAILObject)) {
  10202. return {
  10203. FAIL: "composeRUD: one or more operations hasn't completed successfully",
  10204. report: state.filter(hasFAILObject)
  10205. };
  10206. }
  10207. this.dispatch('composeRUD', [state.filter(function (op) { return !hasFAILObject(op); })]);
  10208. };
  10209. /**
  10210. * Replace a range of tokens with a list of tokens
  10211. * @param {number} startIndex range start index
  10212. * @param {number} offset range offset
  10213. * @param {token} tokens a list of tokens to replace
  10214. * @param {boolean} silent dispatch events and update context ranges
  10215. */
  10216. Tokenizer.prototype.replaceRange = function (startIndex, offset, tokens, silent) {
  10217. offset = offset !== null ? offset : this.tokens.length;
  10218. var isTokenType = tokens.every(function (token) { return token instanceof Token; });
  10219. if (!isNaN(startIndex) && this.inboundIndex(startIndex) && isTokenType) {
  10220. var replaced = this.tokens.splice.apply(
  10221. this.tokens, [startIndex, offset].concat(tokens)
  10222. );
  10223. if (!silent) { this.dispatch('replaceToken', [startIndex, offset, tokens]); }
  10224. return [replaced, tokens];
  10225. } else {
  10226. return { FAIL: 'replaceRange: invalid tokens or startIndex.' };
  10227. }
  10228. };
  10229. /**
  10230. * Replace a token with another token
  10231. * @param {number} index token index
  10232. * @param {token} token a token to replace
  10233. * @param {boolean} silent dispatch events and update context ranges
  10234. */
  10235. Tokenizer.prototype.replaceToken = function (index, token, silent) {
  10236. if (!isNaN(index) && this.inboundIndex(index) && token instanceof Token) {
  10237. var replaced = this.tokens.splice(index, 1, token);
  10238. if (!silent) { this.dispatch('replaceToken', [index, token]); }
  10239. return [replaced[0], token];
  10240. } else {
  10241. return { FAIL: 'replaceToken: invalid token or index.' };
  10242. }
  10243. };
  10244. /**
  10245. * Removes a range of tokens
  10246. * @param {number} startIndex range start index
  10247. * @param {number} offset range offset
  10248. * @param {boolean} silent dispatch events and update context ranges
  10249. */
  10250. Tokenizer.prototype.removeRange = function(startIndex, offset, silent) {
  10251. offset = !isNaN(offset) ? offset : this.tokens.length;
  10252. var tokens = this.tokens.splice(startIndex, offset);
  10253. if (!silent) { this.dispatch('removeRange', [tokens, startIndex, offset]); }
  10254. return tokens;
  10255. };
  10256. /**
  10257. * Remove a token at a certain index
  10258. * @param {number} index token index
  10259. * @param {boolean} silent dispatch events and update context ranges
  10260. */
  10261. Tokenizer.prototype.removeToken = function(index, silent) {
  10262. if (!isNaN(index) && this.inboundIndex(index)) {
  10263. var token = this.tokens.splice(index, 1);
  10264. if (!silent) { this.dispatch('removeToken', [token, index]); }
  10265. return token;
  10266. } else {
  10267. return { FAIL: 'removeToken: invalid token index.' };
  10268. }
  10269. };
  10270. /**
  10271. * Insert a list of tokens at a certain index
  10272. * @param {array} tokens a list of tokens to insert
  10273. * @param {number} index insert the list of tokens at index
  10274. * @param {boolean} silent dispatch events and update context ranges
  10275. */
  10276. Tokenizer.prototype.insertToken = function (tokens, index, silent) {
  10277. var tokenType = tokens.every(
  10278. function (token) { return token instanceof Token; }
  10279. );
  10280. if (tokenType) {
  10281. this.tokens.splice.apply(
  10282. this.tokens, [index, 0].concat(tokens)
  10283. );
  10284. if (!silent) { this.dispatch('insertToken', [tokens, index]); }
  10285. return tokens;
  10286. } else {
  10287. return { FAIL: 'insertToken: invalid token(s).' };
  10288. }
  10289. };
  10290. /**
  10291. * A state modifier that is called on 'newToken' event
  10292. * @param {string} modifierId state modifier id
  10293. * @param {function} condition a predicate function that returns true or false
  10294. * @param {function} modifier a function to update token state
  10295. */
  10296. Tokenizer.prototype.registerModifier = function(modifierId, condition, modifier) {
  10297. this.events.newToken.subscribe(function(token, contextParams) {
  10298. var conditionParams = [token, contextParams];
  10299. var canApplyModifier = (
  10300. condition === null ||
  10301. condition.apply(this, conditionParams) === true
  10302. );
  10303. var modifierParams = [token, contextParams];
  10304. if (canApplyModifier) {
  10305. var newStateValue = modifier.apply(this, modifierParams);
  10306. token.setState(modifierId, newStateValue);
  10307. }
  10308. });
  10309. this.registeredModifiers.push(modifierId);
  10310. };
  10311. /**
  10312. * Subscribe a handler to an event
  10313. * @param {function} eventHandler an event handler function
  10314. */
  10315. Event.prototype.subscribe = function (eventHandler) {
  10316. if (typeof eventHandler === 'function') {
  10317. return ((this.subscribers.push(eventHandler)) - 1);
  10318. } else {
  10319. return { FAIL: ("invalid '" + (this.eventId) + "' event handler")};
  10320. }
  10321. };
  10322. /**
  10323. * Unsubscribe an event handler
  10324. * @param {string} subsId subscription id
  10325. */
  10326. Event.prototype.unsubscribe = function (subsId) {
  10327. this.subscribers.splice(subsId, 1);
  10328. };
  10329. /**
  10330. * Sets context params current value index
  10331. * @param {number} index context params current value index
  10332. */
  10333. ContextParams.prototype.setCurrentIndex = function(index) {
  10334. this.index = index;
  10335. this.current = this.context[index];
  10336. this.backtrack = this.context.slice(0, index);
  10337. this.lookahead = this.context.slice(index + 1);
  10338. };
  10339. /**
  10340. * Get an item at an offset from the current value
  10341. * example (current value is 3):
  10342. * 1 2 [3] 4 5 | items values
  10343. * -2 -1 0 1 2 | offset values
  10344. * @param {number} offset an offset from current value index
  10345. */
  10346. ContextParams.prototype.get = function (offset) {
  10347. switch (true) {
  10348. case (offset === 0):
  10349. return this.current;
  10350. case (offset < 0 && Math.abs(offset) <= this.backtrack.length):
  10351. return this.backtrack.slice(offset)[0];
  10352. case (offset > 0 && offset <= this.lookahead.length):
  10353. return this.lookahead[offset - 1];
  10354. default:
  10355. return null;
  10356. }
  10357. };
  10358. /**
  10359. * Converts a context range into a string value
  10360. * @param {contextRange} range a context range
  10361. */
  10362. Tokenizer.prototype.rangeToText = function (range) {
  10363. if (range instanceof ContextRange) {
  10364. return (
  10365. this.getRangeTokens(range)
  10366. .map(function (token) { return token.char; }).join('')
  10367. );
  10368. }
  10369. };
  10370. /**
  10371. * Converts all tokens into a string
  10372. */
  10373. Tokenizer.prototype.getText = function () {
  10374. return this.tokens.map(function (token) { return token.char; }).join('');
  10375. };
  10376. /**
  10377. * Get a context by name
  10378. * @param {string} contextName context name to get
  10379. */
  10380. Tokenizer.prototype.getContext = function (contextName) {
  10381. var context = this.registeredContexts[contextName];
  10382. return !!context ? context : null;
  10383. };
  10384. /**
  10385. * Subscribes a new event handler to an event
  10386. * @param {string} eventName event name to subscribe to
  10387. * @param {function} eventHandler a function to be invoked on event
  10388. */
  10389. Tokenizer.prototype.on = function(eventName, eventHandler) {
  10390. var event = this.events[eventName];
  10391. if (!!event) {
  10392. return event.subscribe(eventHandler);
  10393. } else {
  10394. return null;
  10395. }
  10396. };
  10397. /**
  10398. * Dispatches an event
  10399. * @param {string} eventName event name
  10400. * @param {any} args event handler arguments
  10401. */
  10402. Tokenizer.prototype.dispatch = function(eventName, args) {
  10403. var this$1 = this;
  10404. var event = this.events[eventName];
  10405. if (event instanceof Event) {
  10406. event.subscribers.forEach(function (subscriber) {
  10407. subscriber.apply(this$1, args || []);
  10408. });
  10409. }
  10410. };
  10411. /**
  10412. * Register a new context checker
  10413. * @param {string} contextName a unique context name
  10414. * @param {function} contextStartCheck a predicate function that returns true on context start
  10415. * @param {function} contextEndCheck a predicate function that returns true on context end
  10416. * TODO: call tokenize on registration to update context ranges with the new context.
  10417. */
  10418. Tokenizer.prototype.registerContextChecker = function(contextName, contextStartCheck, contextEndCheck) {
  10419. if (!!this.getContext(contextName)) { return {
  10420. FAIL:
  10421. ("context name '" + contextName + "' is already registered.")
  10422. }; }
  10423. if (typeof contextStartCheck !== 'function') { return {
  10424. FAIL:
  10425. "missing context start check."
  10426. }; }
  10427. if (typeof contextEndCheck !== 'function') { return {
  10428. FAIL:
  10429. "missing context end check."
  10430. }; }
  10431. var contextCheckers = new ContextChecker(
  10432. contextName, contextStartCheck, contextEndCheck
  10433. );
  10434. this.registeredContexts[contextName] = contextCheckers;
  10435. this.contextCheckers.push(contextCheckers);
  10436. return contextCheckers;
  10437. };
  10438. /**
  10439. * Gets a context range tokens
  10440. * @param {contextRange} range a context range
  10441. */
  10442. Tokenizer.prototype.getRangeTokens = function(range) {
  10443. var endIndex = range.startIndex + range.endOffset;
  10444. return [].concat(
  10445. this.tokens
  10446. .slice(range.startIndex, endIndex)
  10447. );
  10448. };
  10449. /**
  10450. * Gets the ranges of a context
  10451. * @param {string} contextName context name
  10452. */
  10453. Tokenizer.prototype.getContextRanges = function(contextName) {
  10454. var context = this.getContext(contextName);
  10455. if (!!context) {
  10456. return context.ranges;
  10457. } else {
  10458. return { FAIL: ("context checker '" + contextName + "' is not registered.") };
  10459. }
  10460. };
  10461. /**
  10462. * Resets context ranges to run context update
  10463. */
  10464. Tokenizer.prototype.resetContextsRanges = function () {
  10465. var registeredContexts = this.registeredContexts;
  10466. for (var contextName in registeredContexts) {
  10467. if (registeredContexts.hasOwnProperty(contextName)) {
  10468. var context = registeredContexts[contextName];
  10469. context.ranges = [];
  10470. }
  10471. }
  10472. };
  10473. /**
  10474. * Updates context ranges
  10475. */
  10476. Tokenizer.prototype.updateContextsRanges = function () {
  10477. this.resetContextsRanges();
  10478. var chars = this.tokens.map(function (token) { return token.char; });
  10479. for (var i = 0; i < chars.length; i++) {
  10480. var contextParams = new ContextParams(chars, i);
  10481. this.runContextCheck(contextParams);
  10482. }
  10483. this.dispatch('updateContextsRanges', [this.registeredContexts]);
  10484. };
  10485. /**
  10486. * Sets the end offset of an open range
  10487. * @param {number} offset range end offset
  10488. * @param {string} contextName context name
  10489. */
  10490. Tokenizer.prototype.setEndOffset = function (offset, contextName) {
  10491. var startIndex = this.getContext(contextName).openRange.startIndex;
  10492. var range = new ContextRange(startIndex, offset, contextName);
  10493. var ranges = this.getContext(contextName).ranges;
  10494. range.rangeId = contextName + "." + (ranges.length);
  10495. ranges.push(range);
  10496. this.getContext(contextName).openRange = null;
  10497. return range;
  10498. };
  10499. /**
  10500. * Runs a context check on the current context
  10501. * @param {contextParams} contextParams current context params
  10502. */
  10503. Tokenizer.prototype.runContextCheck = function(contextParams) {
  10504. var this$1 = this;
  10505. var index = contextParams.index;
  10506. this.contextCheckers.forEach(function (contextChecker) {
  10507. var contextName = contextChecker.contextName;
  10508. var openRange = this$1.getContext(contextName).openRange;
  10509. if (!openRange && contextChecker.checkStart(contextParams)) {
  10510. openRange = new ContextRange(index, null, contextName);
  10511. this$1.getContext(contextName).openRange = openRange;
  10512. this$1.dispatch('contextStart', [contextName, index]);
  10513. }
  10514. if (!!openRange && contextChecker.checkEnd(contextParams)) {
  10515. var offset = (index - openRange.startIndex) + 1;
  10516. var range = this$1.setEndOffset(offset, contextName);
  10517. this$1.dispatch('contextEnd', [contextName, range]);
  10518. }
  10519. });
  10520. };
  10521. /**
  10522. * Converts a text into a list of tokens
  10523. * @param {string} text a text to tokenize
  10524. */
  10525. Tokenizer.prototype.tokenize = function (text) {
  10526. this.tokens = [];
  10527. this.resetContextsRanges();
  10528. var chars = Array.from(text);
  10529. this.dispatch('start');
  10530. for (var i = 0; i < chars.length; i++) {
  10531. var char = chars[i];
  10532. var contextParams = new ContextParams(chars, i);
  10533. this.dispatch('next', [contextParams]);
  10534. this.runContextCheck(contextParams);
  10535. var token = new Token(char);
  10536. this.tokens.push(token);
  10537. this.dispatch('newToken', [token, contextParams]);
  10538. }
  10539. this.dispatch('end', [this.tokens]);
  10540. return this.tokens;
  10541. };
  10542. // ╭─┄┄┄────────────────────────┄─────────────────────────────────────────────╮
  10543. // ┊ Character Class Assertions ┊ Checks if a char belongs to a certain class ┊
  10544. // ╰─╾──────────────────────────┄─────────────────────────────────────────────╯
  10545. // jscs:disable maximumLineLength
  10546. /**
  10547. * Check if a char is Arabic
  10548. * @param {string} c a single char
  10549. */
  10550. function isArabicChar(c) {
  10551. return /[\u0600-\u065F\u066A-\u06D2\u06FA-\u06FF]/.test(c);
  10552. }
  10553. /**
  10554. * Check if a char is an isolated arabic char
  10555. * @param {string} c a single char
  10556. */
  10557. function isIsolatedArabicChar(char) {
  10558. return /[\u0630\u0690\u0621\u0631\u0661\u0671\u0622\u0632\u0672\u0692\u06C2\u0623\u0673\u0693\u06C3\u0624\u0694\u06C4\u0625\u0675\u0695\u06C5\u06E5\u0676\u0696\u06C6\u0627\u0677\u0697\u06C7\u0648\u0688\u0698\u06C8\u0689\u0699\u06C9\u068A\u06CA\u066B\u068B\u06CB\u068C\u068D\u06CD\u06FD\u068E\u06EE\u06FE\u062F\u068F\u06CF\u06EF]/.test(char);
  10559. }
  10560. /**
  10561. * Check if a char is an Arabic Tashkeel char
  10562. * @param {string} c a single char
  10563. */
  10564. function isTashkeelArabicChar(char) {
  10565. return /[\u0600-\u0605\u060C-\u060E\u0610-\u061B\u061E\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED]/.test(char);
  10566. }
  10567. /**
  10568. * Check if a char is Latin
  10569. * @param {string} c a single char
  10570. */
  10571. function isLatinChar(c) {
  10572. return /[A-z]/.test(c);
  10573. }
  10574. /**
  10575. * Check if a char is whitespace char
  10576. * @param {string} c a single char
  10577. */
  10578. function isWhiteSpace(c) {
  10579. return /\s/.test(c);
  10580. }
  10581. /**
  10582. * Query a feature by some of it's properties to lookup a glyph substitution.
  10583. */
  10584. /**
  10585. * Create feature query instance
  10586. * @param {Font} font opentype font instance
  10587. */
  10588. function FeatureQuery(font) {
  10589. this.font = font;
  10590. this.features = {};
  10591. }
  10592. /**
  10593. * @typedef SubstitutionAction
  10594. * @type Object
  10595. * @property {number} id substitution type
  10596. * @property {string} tag feature tag
  10597. * @property {any} substitution substitution value(s)
  10598. */
  10599. /**
  10600. * Create a substitution action instance
  10601. * @param {SubstitutionAction} action
  10602. */
  10603. function SubstitutionAction(action) {
  10604. this.id = action.id;
  10605. this.tag = action.tag;
  10606. this.substitution = action.substitution;
  10607. }
  10608. /**
  10609. * Lookup a coverage table
  10610. * @param {number} glyphIndex glyph index
  10611. * @param {CoverageTable} coverage coverage table
  10612. */
  10613. function lookupCoverage(glyphIndex, coverage) {
  10614. if (!glyphIndex) { return -1; }
  10615. switch (coverage.format) {
  10616. case 1:
  10617. return coverage.glyphs.indexOf(glyphIndex);
  10618. case 2:
  10619. var ranges = coverage.ranges;
  10620. for (var i = 0; i < ranges.length; i++) {
  10621. var range = ranges[i];
  10622. if (glyphIndex >= range.start && glyphIndex <= range.end) {
  10623. var offset = glyphIndex - range.start;
  10624. return range.index + offset;
  10625. }
  10626. }
  10627. break;
  10628. default:
  10629. return -1; // not found
  10630. }
  10631. return -1;
  10632. }
  10633. /**
  10634. * Handle a single substitution - format 1
  10635. * @param {ContextParams} contextParams context params to lookup
  10636. */
  10637. function singleSubstitutionFormat1(glyphIndex, subtable) {
  10638. var substituteIndex = lookupCoverage(glyphIndex, subtable.coverage);
  10639. if (substituteIndex === -1) { return null; }
  10640. return glyphIndex + subtable.deltaGlyphId;
  10641. }
  10642. /**
  10643. * Handle a single substitution - format 2
  10644. * @param {ContextParams} contextParams context params to lookup
  10645. */
  10646. function singleSubstitutionFormat2(glyphIndex, subtable) {
  10647. var substituteIndex = lookupCoverage(glyphIndex, subtable.coverage);
  10648. if (substituteIndex === -1) { return null; }
  10649. return subtable.substitute[substituteIndex];
  10650. }
  10651. /**
  10652. * Lookup a list of coverage tables
  10653. * @param {any} coverageList a list of coverage tables
  10654. * @param {ContextParams} contextParams context params to lookup
  10655. */
  10656. function lookupCoverageList(coverageList, contextParams) {
  10657. var lookupList = [];
  10658. for (var i = 0; i < coverageList.length; i++) {
  10659. var coverage = coverageList[i];
  10660. var glyphIndex = contextParams.current;
  10661. glyphIndex = Array.isArray(glyphIndex) ? glyphIndex[0] : glyphIndex;
  10662. var lookupIndex = lookupCoverage(glyphIndex, coverage);
  10663. if (lookupIndex !== -1) {
  10664. lookupList.push(lookupIndex);
  10665. }
  10666. }
  10667. if (lookupList.length !== coverageList.length) { return -1; }
  10668. return lookupList;
  10669. }
  10670. /**
  10671. * Handle chaining context substitution - format 3
  10672. * @param {ContextParams} contextParams context params to lookup
  10673. */
  10674. function chainingSubstitutionFormat3(contextParams, subtable) {
  10675. var lookupsCount = (
  10676. subtable.inputCoverage.length +
  10677. subtable.lookaheadCoverage.length +
  10678. subtable.backtrackCoverage.length
  10679. );
  10680. if (contextParams.context.length < lookupsCount) { return []; }
  10681. // INPUT LOOKUP //
  10682. var inputLookups = lookupCoverageList(
  10683. subtable.inputCoverage, contextParams
  10684. );
  10685. if (inputLookups === -1) { return []; }
  10686. // LOOKAHEAD LOOKUP //
  10687. var lookaheadOffset = subtable.inputCoverage.length - 1;
  10688. if (contextParams.lookahead.length < subtable.lookaheadCoverage.length) { return []; }
  10689. var lookaheadContext = contextParams.lookahead.slice(lookaheadOffset);
  10690. while (lookaheadContext.length && isTashkeelArabicChar(lookaheadContext[0].char)) {
  10691. lookaheadContext.shift();
  10692. }
  10693. var lookaheadParams = new ContextParams(lookaheadContext, 0);
  10694. var lookaheadLookups = lookupCoverageList(
  10695. subtable.lookaheadCoverage, lookaheadParams
  10696. );
  10697. // BACKTRACK LOOKUP //
  10698. var backtrackContext = [].concat(contextParams.backtrack);
  10699. backtrackContext.reverse();
  10700. while (backtrackContext.length && isTashkeelArabicChar(backtrackContext[0].char)) {
  10701. backtrackContext.shift();
  10702. }
  10703. if (backtrackContext.length < subtable.backtrackCoverage.length) { return []; }
  10704. var backtrackParams = new ContextParams(backtrackContext, 0);
  10705. var backtrackLookups = lookupCoverageList(
  10706. subtable.backtrackCoverage, backtrackParams
  10707. );
  10708. var contextRulesMatch = (
  10709. inputLookups.length === subtable.inputCoverage.length &&
  10710. lookaheadLookups.length === subtable.lookaheadCoverage.length &&
  10711. backtrackLookups.length === subtable.backtrackCoverage.length
  10712. );
  10713. var substitutions = [];
  10714. if (contextRulesMatch) {
  10715. for (var i = 0; i < subtable.lookupRecords.length; i++) {
  10716. var lookupRecord = subtable.lookupRecords[i];
  10717. var lookupListIndex = lookupRecord.lookupListIndex;
  10718. var lookupTable = this.getLookupByIndex(lookupListIndex);
  10719. for (var s = 0; s < lookupTable.subtables.length; s++) {
  10720. var subtable$1 = lookupTable.subtables[s];
  10721. var lookup = this.getLookupMethod(lookupTable, subtable$1);
  10722. var substitutionType = this.getSubstitutionType(lookupTable, subtable$1);
  10723. if (substitutionType === '12') {
  10724. for (var n = 0; n < inputLookups.length; n++) {
  10725. var glyphIndex = contextParams.get(n);
  10726. var substitution = lookup(glyphIndex);
  10727. if (substitution) { substitutions.push(substitution); }
  10728. }
  10729. }
  10730. }
  10731. }
  10732. }
  10733. return substitutions;
  10734. }
  10735. /**
  10736. * Handle ligature substitution - format 1
  10737. * @param {ContextParams} contextParams context params to lookup
  10738. */
  10739. function ligatureSubstitutionFormat1(contextParams, subtable) {
  10740. // COVERAGE LOOKUP //
  10741. var glyphIndex = contextParams.current;
  10742. var ligSetIndex = lookupCoverage(glyphIndex, subtable.coverage);
  10743. if (ligSetIndex === -1) { return null; }
  10744. // COMPONENTS LOOKUP
  10745. // (!) note, components are ordered in the written direction.
  10746. var ligature;
  10747. var ligatureSet = subtable.ligatureSets[ligSetIndex];
  10748. for (var s = 0; s < ligatureSet.length; s++) {
  10749. ligature = ligatureSet[s];
  10750. for (var l = 0; l < ligature.components.length; l++) {
  10751. var lookaheadItem = contextParams.lookahead[l];
  10752. var component = ligature.components[l];
  10753. if (lookaheadItem !== component) { break; }
  10754. if (l === ligature.components.length - 1) { return ligature; }
  10755. }
  10756. }
  10757. return null;
  10758. }
  10759. /**
  10760. * Handle decomposition substitution - format 1
  10761. * @param {number} glyphIndex glyph index
  10762. * @param {any} subtable subtable
  10763. */
  10764. function decompositionSubstitutionFormat1(glyphIndex, subtable) {
  10765. var substituteIndex = lookupCoverage(glyphIndex, subtable.coverage);
  10766. if (substituteIndex === -1) { return null; }
  10767. return subtable.sequences[substituteIndex];
  10768. }
  10769. /**
  10770. * Get default script features indexes
  10771. */
  10772. FeatureQuery.prototype.getDefaultScriptFeaturesIndexes = function () {
  10773. var scripts = this.font.tables.gsub.scripts;
  10774. for (var s = 0; s < scripts.length; s++) {
  10775. var script = scripts[s];
  10776. if (script.tag === 'DFLT') { return (
  10777. script.script.defaultLangSys.featureIndexes
  10778. ); }
  10779. }
  10780. return [];
  10781. };
  10782. /**
  10783. * Get feature indexes of a specific script
  10784. * @param {string} scriptTag script tag
  10785. */
  10786. FeatureQuery.prototype.getScriptFeaturesIndexes = function(scriptTag) {
  10787. var tables = this.font.tables;
  10788. if (!tables.gsub) { return []; }
  10789. if (!scriptTag) { return this.getDefaultScriptFeaturesIndexes(); }
  10790. var scripts = this.font.tables.gsub.scripts;
  10791. for (var i = 0; i < scripts.length; i++) {
  10792. var script = scripts[i];
  10793. if (script.tag === scriptTag && script.script.defaultLangSys) {
  10794. return script.script.defaultLangSys.featureIndexes;
  10795. } else {
  10796. var langSysRecords = script.langSysRecords;
  10797. if (!!langSysRecords) {
  10798. for (var j = 0; j < langSysRecords.length; j++) {
  10799. var langSysRecord = langSysRecords[j];
  10800. if (langSysRecord.tag === scriptTag) {
  10801. var langSys = langSysRecord.langSys;
  10802. return langSys.featureIndexes;
  10803. }
  10804. }
  10805. }
  10806. }
  10807. }
  10808. return this.getDefaultScriptFeaturesIndexes();
  10809. };
  10810. /**
  10811. * Map a feature tag to a gsub feature
  10812. * @param {any} features gsub features
  10813. * @param {string} scriptTag script tag
  10814. */
  10815. FeatureQuery.prototype.mapTagsToFeatures = function (features, scriptTag) {
  10816. var tags = {};
  10817. for (var i = 0; i < features.length; i++) {
  10818. var tag = features[i].tag;
  10819. var feature = features[i].feature;
  10820. tags[tag] = feature;
  10821. }
  10822. this.features[scriptTag].tags = tags;
  10823. };
  10824. /**
  10825. * Get features of a specific script
  10826. * @param {string} scriptTag script tag
  10827. */
  10828. FeatureQuery.prototype.getScriptFeatures = function (scriptTag) {
  10829. var features = this.features[scriptTag];
  10830. if (this.features.hasOwnProperty(scriptTag)) { return features; }
  10831. var featuresIndexes = this.getScriptFeaturesIndexes(scriptTag);
  10832. if (!featuresIndexes) { return null; }
  10833. var gsub = this.font.tables.gsub;
  10834. features = featuresIndexes.map(function (index) { return gsub.features[index]; });
  10835. this.features[scriptTag] = features;
  10836. this.mapTagsToFeatures(features, scriptTag);
  10837. return features;
  10838. };
  10839. /**
  10840. * Get substitution type
  10841. * @param {any} lookupTable lookup table
  10842. * @param {any} subtable subtable
  10843. */
  10844. FeatureQuery.prototype.getSubstitutionType = function(lookupTable, subtable) {
  10845. var lookupType = lookupTable.lookupType.toString();
  10846. var substFormat = subtable.substFormat.toString();
  10847. return lookupType + substFormat;
  10848. };
  10849. /**
  10850. * Get lookup method
  10851. * @param {any} lookupTable lookup table
  10852. * @param {any} subtable subtable
  10853. */
  10854. FeatureQuery.prototype.getLookupMethod = function(lookupTable, subtable) {
  10855. var this$1 = this;
  10856. var substitutionType = this.getSubstitutionType(lookupTable, subtable);
  10857. switch (substitutionType) {
  10858. case '11':
  10859. return function (glyphIndex) { return singleSubstitutionFormat1.apply(
  10860. this$1, [glyphIndex, subtable]
  10861. ); };
  10862. case '12':
  10863. return function (glyphIndex) { return singleSubstitutionFormat2.apply(
  10864. this$1, [glyphIndex, subtable]
  10865. ); };
  10866. case '63':
  10867. return function (contextParams) { return chainingSubstitutionFormat3.apply(
  10868. this$1, [contextParams, subtable]
  10869. ); };
  10870. case '41':
  10871. return function (contextParams) { return ligatureSubstitutionFormat1.apply(
  10872. this$1, [contextParams, subtable]
  10873. ); };
  10874. case '21':
  10875. return function (glyphIndex) { return decompositionSubstitutionFormat1.apply(
  10876. this$1, [glyphIndex, subtable]
  10877. ); };
  10878. default:
  10879. throw new Error(
  10880. "lookupType: " + (lookupTable.lookupType) + " - " +
  10881. "substFormat: " + (subtable.substFormat) + " " +
  10882. "is not yet supported"
  10883. );
  10884. }
  10885. };
  10886. /**
  10887. * [ LOOKUP TYPES ]
  10888. * -------------------------------
  10889. * Single 1;
  10890. * Multiple 2;
  10891. * Alternate 3;
  10892. * Ligature 4;
  10893. * Context 5;
  10894. * ChainingContext 6;
  10895. * ExtensionSubstitution 7;
  10896. * ReverseChainingContext 8;
  10897. * -------------------------------
  10898. *
  10899. */
  10900. /**
  10901. * @typedef FQuery
  10902. * @type Object
  10903. * @param {string} tag feature tag
  10904. * @param {string} script feature script
  10905. * @param {ContextParams} contextParams context params
  10906. */
  10907. /**
  10908. * Lookup a feature using a query parameters
  10909. * @param {FQuery} query feature query
  10910. */
  10911. FeatureQuery.prototype.lookupFeature = function (query) {
  10912. var contextParams = query.contextParams;
  10913. var currentIndex = contextParams.index;
  10914. var feature = this.getFeature({
  10915. tag: query.tag, script: query.script
  10916. });
  10917. if (!feature) { return new Error(
  10918. "font '" + (this.font.names.fullName.en) + "' " +
  10919. "doesn't support feature '" + (query.tag) + "' " +
  10920. "for script '" + (query.script) + "'."
  10921. ); }
  10922. var lookups = this.getFeatureLookups(feature);
  10923. var substitutions = [].concat(contextParams.context);
  10924. for (var l = 0; l < lookups.length; l++) {
  10925. var lookupTable = lookups[l];
  10926. var subtables = this.getLookupSubtables(lookupTable);
  10927. for (var s = 0; s < subtables.length; s++) {
  10928. var subtable = subtables[s];
  10929. var substType = this.getSubstitutionType(lookupTable, subtable);
  10930. var lookup = this.getLookupMethod(lookupTable, subtable);
  10931. var substitution = (void 0);
  10932. switch (substType) {
  10933. case '11':
  10934. substitution = lookup(contextParams.current);
  10935. if (substitution) {
  10936. substitutions.splice(currentIndex, 1, new SubstitutionAction({
  10937. id: 11, tag: query.tag, substitution: substitution
  10938. }));
  10939. }
  10940. break;
  10941. case '12':
  10942. substitution = lookup(contextParams.current);
  10943. if (substitution) {
  10944. substitutions.splice(currentIndex, 1, new SubstitutionAction({
  10945. id: 12, tag: query.tag, substitution: substitution
  10946. }));
  10947. }
  10948. break;
  10949. case '63':
  10950. substitution = lookup(contextParams);
  10951. if (Array.isArray(substitution) && substitution.length) {
  10952. substitutions.splice(currentIndex, 1, new SubstitutionAction({
  10953. id: 63, tag: query.tag, substitution: substitution
  10954. }));
  10955. }
  10956. break;
  10957. case '41':
  10958. substitution = lookup(contextParams);
  10959. if (substitution) {
  10960. substitutions.splice(currentIndex, 1, new SubstitutionAction({
  10961. id: 41, tag: query.tag, substitution: substitution
  10962. }));
  10963. }
  10964. break;
  10965. case '21':
  10966. substitution = lookup(contextParams.current);
  10967. if (substitution) {
  10968. substitutions.splice(currentIndex, 1, new SubstitutionAction({
  10969. id: 21, tag: query.tag, substitution: substitution
  10970. }));
  10971. }
  10972. break;
  10973. }
  10974. contextParams = new ContextParams(substitutions, currentIndex);
  10975. if (Array.isArray(substitution) && !substitution.length) { continue; }
  10976. substitution = null;
  10977. }
  10978. }
  10979. return substitutions.length ? substitutions : null;
  10980. };
  10981. /**
  10982. * Checks if a font supports a specific features
  10983. * @param {FQuery} query feature query object
  10984. */
  10985. FeatureQuery.prototype.supports = function (query) {
  10986. if (!query.script) { return false; }
  10987. this.getScriptFeatures(query.script);
  10988. var supportedScript = this.features.hasOwnProperty(query.script);
  10989. if (!query.tag) { return supportedScript; }
  10990. var supportedFeature = (
  10991. this.features[query.script].some(function (feature) { return feature.tag === query.tag; })
  10992. );
  10993. return supportedScript && supportedFeature;
  10994. };
  10995. /**
  10996. * Get lookup table subtables
  10997. * @param {any} lookupTable lookup table
  10998. */
  10999. FeatureQuery.prototype.getLookupSubtables = function (lookupTable) {
  11000. return lookupTable.subtables || null;
  11001. };
  11002. /**
  11003. * Get lookup table by index
  11004. * @param {number} index lookup table index
  11005. */
  11006. FeatureQuery.prototype.getLookupByIndex = function (index) {
  11007. var lookups = this.font.tables.gsub.lookups;
  11008. return lookups[index] || null;
  11009. };
  11010. /**
  11011. * Get lookup tables for a feature
  11012. * @param {string} feature
  11013. */
  11014. FeatureQuery.prototype.getFeatureLookups = function (feature) {
  11015. // TODO: memoize
  11016. return feature.lookupListIndexes.map(this.getLookupByIndex.bind(this));
  11017. };
  11018. /**
  11019. * Query a feature by it's properties
  11020. * @param {any} query an object that describes the properties of a query
  11021. */
  11022. FeatureQuery.prototype.getFeature = function getFeature(query) {
  11023. if (!this.font) { return { FAIL: "No font was found"}; }
  11024. if (!this.features.hasOwnProperty(query.script)) {
  11025. this.getScriptFeatures(query.script);
  11026. }
  11027. var scriptFeatures = this.features[query.script];
  11028. if (!scriptFeatures) { return (
  11029. { FAIL: ("No feature for script " + (query.script))}
  11030. ); }
  11031. if (!scriptFeatures.tags[query.tag]) { return null; }
  11032. return this.features[query.script].tags[query.tag];
  11033. };
  11034. /**
  11035. * Arabic word context checkers
  11036. */
  11037. function arabicWordStartCheck(contextParams) {
  11038. var char = contextParams.current;
  11039. var prevChar = contextParams.get(-1);
  11040. return (
  11041. // ? arabic first char
  11042. (prevChar === null && isArabicChar(char)) ||
  11043. // ? arabic char preceded with a non arabic char
  11044. (!isArabicChar(prevChar) && isArabicChar(char))
  11045. );
  11046. }
  11047. function arabicWordEndCheck(contextParams) {
  11048. var nextChar = contextParams.get(1);
  11049. return (
  11050. // ? last arabic char
  11051. (nextChar === null) ||
  11052. // ? next char is not arabic
  11053. (!isArabicChar(nextChar))
  11054. );
  11055. }
  11056. var arabicWordCheck = {
  11057. startCheck: arabicWordStartCheck,
  11058. endCheck: arabicWordEndCheck
  11059. };
  11060. /**
  11061. * Arabic sentence context checkers
  11062. */
  11063. function arabicSentenceStartCheck(contextParams) {
  11064. var char = contextParams.current;
  11065. var prevChar = contextParams.get(-1);
  11066. return (
  11067. // ? an arabic char preceded with a non arabic char
  11068. (isArabicChar(char) || isTashkeelArabicChar(char)) &&
  11069. !isArabicChar(prevChar)
  11070. );
  11071. }
  11072. function arabicSentenceEndCheck(contextParams) {
  11073. var nextChar = contextParams.get(1);
  11074. switch (true) {
  11075. case nextChar === null:
  11076. return true;
  11077. case (!isArabicChar(nextChar) && !isTashkeelArabicChar(nextChar)):
  11078. var nextIsWhitespace = isWhiteSpace(nextChar);
  11079. if (!nextIsWhitespace) { return true; }
  11080. if (nextIsWhitespace) {
  11081. var arabicCharAhead = false;
  11082. arabicCharAhead = (
  11083. contextParams.lookahead.some(
  11084. function (c) { return isArabicChar(c) || isTashkeelArabicChar(c); }
  11085. )
  11086. );
  11087. if (!arabicCharAhead) { return true; }
  11088. }
  11089. break;
  11090. default:
  11091. return false;
  11092. }
  11093. }
  11094. var arabicSentenceCheck = {
  11095. startCheck: arabicSentenceStartCheck,
  11096. endCheck: arabicSentenceEndCheck
  11097. };
  11098. /**
  11099. * Apply single substitution format 1
  11100. * @param {Array} substitutions substitutions
  11101. * @param {any} tokens a list of tokens
  11102. * @param {number} index token index
  11103. */
  11104. function singleSubstitutionFormat1$1(action, tokens, index) {
  11105. tokens[index].setState(action.tag, action.substitution);
  11106. }
  11107. /**
  11108. * Apply single substitution format 2
  11109. * @param {Array} substitutions substitutions
  11110. * @param {any} tokens a list of tokens
  11111. * @param {number} index token index
  11112. */
  11113. function singleSubstitutionFormat2$1(action, tokens, index) {
  11114. tokens[index].setState(action.tag, action.substitution);
  11115. }
  11116. /**
  11117. * Apply chaining context substitution format 3
  11118. * @param {Array} substitutions substitutions
  11119. * @param {any} tokens a list of tokens
  11120. * @param {number} index token index
  11121. */
  11122. function chainingSubstitutionFormat3$1(action, tokens, index) {
  11123. action.substitution.forEach(function (subst, offset) {
  11124. var token = tokens[index + offset];
  11125. token.setState(action.tag, subst);
  11126. });
  11127. }
  11128. /**
  11129. * Apply ligature substitution format 1
  11130. * @param {Array} substitutions substitutions
  11131. * @param {any} tokens a list of tokens
  11132. * @param {number} index token index
  11133. */
  11134. function ligatureSubstitutionFormat1$1(action, tokens, index) {
  11135. var token = tokens[index];
  11136. token.setState(action.tag, action.substitution.ligGlyph);
  11137. var compsCount = action.substitution.components.length;
  11138. for (var i = 0; i < compsCount; i++) {
  11139. token = tokens[index + i + 1];
  11140. token.setState('deleted', true);
  11141. }
  11142. }
  11143. /**
  11144. * Supported substitutions
  11145. */
  11146. var SUBSTITUTIONS = {
  11147. 11: singleSubstitutionFormat1$1,
  11148. 12: singleSubstitutionFormat2$1,
  11149. 63: chainingSubstitutionFormat3$1,
  11150. 41: ligatureSubstitutionFormat1$1
  11151. };
  11152. /**
  11153. * Apply substitutions to a list of tokens
  11154. * @param {Array} substitutions substitutions
  11155. * @param {any} tokens a list of tokens
  11156. * @param {number} index token index
  11157. */
  11158. function applySubstitution(action, tokens, index) {
  11159. if (action instanceof SubstitutionAction && SUBSTITUTIONS[action.id]) {
  11160. SUBSTITUTIONS[action.id](action, tokens, index);
  11161. }
  11162. }
  11163. /**
  11164. * Apply Arabic presentation forms to a range of tokens
  11165. */
  11166. /**
  11167. * Check if a char can be connected to it's preceding char
  11168. * @param {ContextParams} charContextParams context params of a char
  11169. */
  11170. function willConnectPrev(charContextParams) {
  11171. var backtrack = [].concat(charContextParams.backtrack);
  11172. for (var i = backtrack.length - 1; i >= 0; i--) {
  11173. var prevChar = backtrack[i];
  11174. var isolated = isIsolatedArabicChar(prevChar);
  11175. var tashkeel = isTashkeelArabicChar(prevChar);
  11176. if (!isolated && !tashkeel) { return true; }
  11177. if (isolated) { return false; }
  11178. }
  11179. return false;
  11180. }
  11181. /**
  11182. * Check if a char can be connected to it's proceeding char
  11183. * @param {ContextParams} charContextParams context params of a char
  11184. */
  11185. function willConnectNext(charContextParams) {
  11186. if (isIsolatedArabicChar(charContextParams.current)) { return false; }
  11187. for (var i = 0; i < charContextParams.lookahead.length; i++) {
  11188. var nextChar = charContextParams.lookahead[i];
  11189. var tashkeel = isTashkeelArabicChar(nextChar);
  11190. if (!tashkeel) { return true; }
  11191. }
  11192. return false;
  11193. }
  11194. /**
  11195. * Apply arabic presentation forms to a list of tokens
  11196. * @param {ContextRange} range a range of tokens
  11197. */
  11198. function arabicPresentationForms(range) {
  11199. var this$1 = this;
  11200. var script = 'arab';
  11201. var tags = this.featuresTags[script];
  11202. var tokens = this.tokenizer.getRangeTokens(range);
  11203. if (tokens.length === 1) { return; }
  11204. var contextParams = new ContextParams(
  11205. tokens.map(function (token) { return token.getState('glyphIndex'); }
  11206. ), 0);
  11207. var charContextParams = new ContextParams(
  11208. tokens.map(function (token) { return token.char; }
  11209. ), 0);
  11210. tokens.forEach(function (token, index) {
  11211. if (isTashkeelArabicChar(token.char)) { return; }
  11212. contextParams.setCurrentIndex(index);
  11213. charContextParams.setCurrentIndex(index);
  11214. var CONNECT = 0; // 2 bits 00 (10: can connect next) (01: can connect prev)
  11215. if (willConnectPrev(charContextParams)) { CONNECT |= 1; }
  11216. if (willConnectNext(charContextParams)) { CONNECT |= 2; }
  11217. var tag;
  11218. switch (CONNECT) {
  11219. case 1: (tag = 'fina'); break;
  11220. case 2: (tag = 'init'); break;
  11221. case 3: (tag = 'medi'); break;
  11222. }
  11223. if (tags.indexOf(tag) === -1) { return; }
  11224. var substitutions = this$1.query.lookupFeature({
  11225. tag: tag, script: script, contextParams: contextParams
  11226. });
  11227. if (substitutions instanceof Error) { return console.info(substitutions.message); }
  11228. substitutions.forEach(function (action, index) {
  11229. if (action instanceof SubstitutionAction) {
  11230. applySubstitution(action, tokens, index);
  11231. contextParams.context[index] = action.substitution;
  11232. }
  11233. });
  11234. });
  11235. }
  11236. /**
  11237. * Apply Arabic required ligatures feature to a range of tokens
  11238. */
  11239. /**
  11240. * Update context params
  11241. * @param {any} tokens a list of tokens
  11242. * @param {number} index current item index
  11243. */
  11244. function getContextParams(tokens, index) {
  11245. var context = tokens.map(function (token) { return token.activeState.value; });
  11246. return new ContextParams(context, index || 0);
  11247. }
  11248. /**
  11249. * Apply Arabic required ligatures to a context range
  11250. * @param {ContextRange} range a range of tokens
  11251. */
  11252. function arabicRequiredLigatures(range) {
  11253. var this$1 = this;
  11254. var script = 'arab';
  11255. var tokens = this.tokenizer.getRangeTokens(range);
  11256. var contextParams = getContextParams(tokens);
  11257. contextParams.context.forEach(function (glyphIndex, index) {
  11258. contextParams.setCurrentIndex(index);
  11259. var substitutions = this$1.query.lookupFeature({
  11260. tag: 'rlig', script: script, contextParams: contextParams
  11261. });
  11262. if (substitutions.length) {
  11263. substitutions.forEach(
  11264. function (action) { return applySubstitution(action, tokens, index); }
  11265. );
  11266. contextParams = getContextParams(tokens);
  11267. }
  11268. });
  11269. }
  11270. /**
  11271. * Latin word context checkers
  11272. */
  11273. function latinWordStartCheck(contextParams) {
  11274. var char = contextParams.current;
  11275. var prevChar = contextParams.get(-1);
  11276. return (
  11277. // ? latin first char
  11278. (prevChar === null && isLatinChar(char)) ||
  11279. // ? latin char preceded with a non latin char
  11280. (!isLatinChar(prevChar) && isLatinChar(char))
  11281. );
  11282. }
  11283. function latinWordEndCheck(contextParams) {
  11284. var nextChar = contextParams.get(1);
  11285. return (
  11286. // ? last latin char
  11287. (nextChar === null) ||
  11288. // ? next char is not latin
  11289. (!isLatinChar(nextChar))
  11290. );
  11291. }
  11292. var latinWordCheck = {
  11293. startCheck: latinWordStartCheck,
  11294. endCheck: latinWordEndCheck
  11295. };
  11296. /**
  11297. * Apply Latin ligature feature to a range of tokens
  11298. */
  11299. /**
  11300. * Update context params
  11301. * @param {any} tokens a list of tokens
  11302. * @param {number} index current item index
  11303. */
  11304. function getContextParams$1(tokens, index) {
  11305. var context = tokens.map(function (token) { return token.activeState.value; });
  11306. return new ContextParams(context, index || 0);
  11307. }
  11308. /**
  11309. * Apply Arabic required ligatures to a context range
  11310. * @param {ContextRange} range a range of tokens
  11311. */
  11312. function latinLigature(range) {
  11313. var this$1 = this;
  11314. var script = 'latn';
  11315. var tokens = this.tokenizer.getRangeTokens(range);
  11316. var contextParams = getContextParams$1(tokens);
  11317. contextParams.context.forEach(function (glyphIndex, index) {
  11318. contextParams.setCurrentIndex(index);
  11319. var substitutions = this$1.query.lookupFeature({
  11320. tag: 'liga', script: script, contextParams: contextParams
  11321. });
  11322. if (substitutions.length) {
  11323. substitutions.forEach(
  11324. function (action) { return applySubstitution(action, tokens, index); }
  11325. );
  11326. contextParams = getContextParams$1(tokens);
  11327. }
  11328. });
  11329. }
  11330. /**
  11331. * Infer bidirectional properties for a given text and apply
  11332. * the corresponding layout rules.
  11333. */
  11334. /**
  11335. * Create Bidi. features
  11336. * @param {string} baseDir text base direction. value either 'ltr' or 'rtl'
  11337. */
  11338. function Bidi(baseDir) {
  11339. this.baseDir = baseDir || 'ltr';
  11340. this.tokenizer = new Tokenizer();
  11341. this.featuresTags = {};
  11342. }
  11343. /**
  11344. * Sets Bidi text
  11345. * @param {string} text a text input
  11346. */
  11347. Bidi.prototype.setText = function (text) {
  11348. this.text = text;
  11349. };
  11350. /**
  11351. * Store essential context checks:
  11352. * arabic word check for applying gsub features
  11353. * arabic sentence check for adjusting arabic layout
  11354. */
  11355. Bidi.prototype.contextChecks = ({
  11356. latinWordCheck: latinWordCheck,
  11357. arabicWordCheck: arabicWordCheck,
  11358. arabicSentenceCheck: arabicSentenceCheck
  11359. });
  11360. /**
  11361. * Register arabic word check
  11362. */
  11363. function registerContextChecker(checkId) {
  11364. var check = this.contextChecks[(checkId + "Check")];
  11365. return this.tokenizer.registerContextChecker(
  11366. checkId, check.startCheck, check.endCheck
  11367. );
  11368. }
  11369. /**
  11370. * Perform pre tokenization procedure then
  11371. * tokenize text input
  11372. */
  11373. function tokenizeText() {
  11374. registerContextChecker.call(this, 'latinWord');
  11375. registerContextChecker.call(this, 'arabicWord');
  11376. registerContextChecker.call(this, 'arabicSentence');
  11377. return this.tokenizer.tokenize(this.text);
  11378. }
  11379. /**
  11380. * Reverse arabic sentence layout
  11381. * TODO: check base dir before applying adjustments - priority low
  11382. */
  11383. function reverseArabicSentences() {
  11384. var this$1 = this;
  11385. var ranges = this.tokenizer.getContextRanges('arabicSentence');
  11386. ranges.forEach(function (range) {
  11387. var rangeTokens = this$1.tokenizer.getRangeTokens(range);
  11388. this$1.tokenizer.replaceRange(
  11389. range.startIndex,
  11390. range.endOffset,
  11391. rangeTokens.reverse()
  11392. );
  11393. });
  11394. }
  11395. /**
  11396. * Register supported features tags
  11397. * @param {script} script script tag
  11398. * @param {Array} tags features tags list
  11399. */
  11400. Bidi.prototype.registerFeatures = function (script, tags) {
  11401. var this$1 = this;
  11402. var supportedTags = tags.filter(
  11403. function (tag) { return this$1.query.supports({script: script, tag: tag}); }
  11404. );
  11405. if (!this.featuresTags.hasOwnProperty(script)) {
  11406. this.featuresTags[script] = supportedTags;
  11407. } else {
  11408. this.featuresTags[script] =
  11409. this.featuresTags[script].concat(supportedTags);
  11410. }
  11411. };
  11412. /**
  11413. * Apply GSUB features
  11414. * @param {Array} tagsList a list of features tags
  11415. * @param {string} script a script tag
  11416. * @param {Font} font opentype font instance
  11417. */
  11418. Bidi.prototype.applyFeatures = function (font, features) {
  11419. if (!font) { throw new Error(
  11420. 'No valid font was provided to apply features'
  11421. ); }
  11422. if (!this.query) { this.query = new FeatureQuery(font); }
  11423. for (var f = 0; f < features.length; f++) {
  11424. var feature = features[f];
  11425. if (!this.query.supports({script: feature.script})) { continue; }
  11426. this.registerFeatures(feature.script, feature.tags);
  11427. }
  11428. };
  11429. /**
  11430. * Register a state modifier
  11431. * @param {string} modifierId state modifier id
  11432. * @param {function} condition a predicate function that returns true or false
  11433. * @param {function} modifier a modifier function to set token state
  11434. */
  11435. Bidi.prototype.registerModifier = function (modifierId, condition, modifier) {
  11436. this.tokenizer.registerModifier(modifierId, condition, modifier);
  11437. };
  11438. /**
  11439. * Check if 'glyphIndex' is registered
  11440. */
  11441. function checkGlyphIndexStatus() {
  11442. if (this.tokenizer.registeredModifiers.indexOf('glyphIndex') === -1) {
  11443. throw new Error(
  11444. 'glyphIndex modifier is required to apply ' +
  11445. 'arabic presentation features.'
  11446. );
  11447. }
  11448. }
  11449. /**
  11450. * Apply arabic presentation forms features
  11451. */
  11452. function applyArabicPresentationForms() {
  11453. var this$1 = this;
  11454. var script = 'arab';
  11455. if (!this.featuresTags.hasOwnProperty(script)) { return; }
  11456. checkGlyphIndexStatus.call(this);
  11457. var ranges = this.tokenizer.getContextRanges('arabicWord');
  11458. ranges.forEach(function (range) {
  11459. arabicPresentationForms.call(this$1, range);
  11460. });
  11461. }
  11462. /**
  11463. * Apply required arabic ligatures
  11464. */
  11465. function applyArabicRequireLigatures() {
  11466. var this$1 = this;
  11467. var script = 'arab';
  11468. if (!this.featuresTags.hasOwnProperty(script)) { return; }
  11469. var tags = this.featuresTags[script];
  11470. if (tags.indexOf('rlig') === -1) { return; }
  11471. checkGlyphIndexStatus.call(this);
  11472. var ranges = this.tokenizer.getContextRanges('arabicWord');
  11473. ranges.forEach(function (range) {
  11474. arabicRequiredLigatures.call(this$1, range);
  11475. });
  11476. }
  11477. /**
  11478. * Apply required arabic ligatures
  11479. */
  11480. function applyLatinLigatures() {
  11481. var this$1 = this;
  11482. var script = 'latn';
  11483. if (!this.featuresTags.hasOwnProperty(script)) { return; }
  11484. var tags = this.featuresTags[script];
  11485. if (tags.indexOf('liga') === -1) { return; }
  11486. checkGlyphIndexStatus.call(this);
  11487. var ranges = this.tokenizer.getContextRanges('latinWord');
  11488. ranges.forEach(function (range) {
  11489. latinLigature.call(this$1, range);
  11490. });
  11491. }
  11492. /**
  11493. * Check if a context is registered
  11494. * @param {string} contextId context id
  11495. */
  11496. Bidi.prototype.checkContextReady = function (contextId) {
  11497. return !!this.tokenizer.getContext(contextId);
  11498. };
  11499. /**
  11500. * Apply features to registered contexts
  11501. */
  11502. Bidi.prototype.applyFeaturesToContexts = function () {
  11503. if (this.checkContextReady('arabicWord')) {
  11504. applyArabicPresentationForms.call(this);
  11505. applyArabicRequireLigatures.call(this);
  11506. }
  11507. if (this.checkContextReady('latinWord')) {
  11508. applyLatinLigatures.call(this);
  11509. }
  11510. if (this.checkContextReady('arabicSentence')) {
  11511. reverseArabicSentences.call(this);
  11512. }
  11513. };
  11514. /**
  11515. * process text input
  11516. * @param {string} text an input text
  11517. */
  11518. Bidi.prototype.processText = function(text) {
  11519. if (!this.text || this.text !== text) {
  11520. this.setText(text);
  11521. tokenizeText.call(this);
  11522. this.applyFeaturesToContexts();
  11523. }
  11524. };
  11525. /**
  11526. * Process a string of text to identify and adjust
  11527. * bidirectional text entities.
  11528. * @param {string} text input text
  11529. */
  11530. Bidi.prototype.getBidiText = function (text) {
  11531. this.processText(text);
  11532. return this.tokenizer.getText();
  11533. };
  11534. /**
  11535. * Get the current state index of each token
  11536. * @param {text} text an input text
  11537. */
  11538. Bidi.prototype.getTextGlyphs = function (text) {
  11539. this.processText(text);
  11540. var indexes = [];
  11541. for (var i = 0; i < this.tokenizer.tokens.length; i++) {
  11542. var token = this.tokenizer.tokens[i];
  11543. if (token.state.deleted) { continue; }
  11544. var index = token.activeState.value;
  11545. indexes.push(Array.isArray(index) ? index[0] : index);
  11546. }
  11547. return indexes;
  11548. };
  11549. // The Font object
  11550. /**
  11551. * @typedef FontOptions
  11552. * @type Object
  11553. * @property {Boolean} empty - whether to create a new empty font
  11554. * @property {string} familyName
  11555. * @property {string} styleName
  11556. * @property {string=} fullName
  11557. * @property {string=} postScriptName
  11558. * @property {string=} designer
  11559. * @property {string=} designerURL
  11560. * @property {string=} manufacturer
  11561. * @property {string=} manufacturerURL
  11562. * @property {string=} license
  11563. * @property {string=} licenseURL
  11564. * @property {string=} version
  11565. * @property {string=} description
  11566. * @property {string=} copyright
  11567. * @property {string=} trademark
  11568. * @property {Number} unitsPerEm
  11569. * @property {Number} ascender
  11570. * @property {Number} descender
  11571. * @property {Number} createdTimestamp
  11572. * @property {string=} weightClass
  11573. * @property {string=} widthClass
  11574. * @property {string=} fsSelection
  11575. */
  11576. /**
  11577. * A Font represents a loaded OpenType font file.
  11578. * It contains a set of glyphs and methods to draw text on a drawing context,
  11579. * or to get a path representing the text.
  11580. * @exports opentype.Font
  11581. * @class
  11582. * @param {FontOptions}
  11583. * @constructor
  11584. */
  11585. function Font(options) {
  11586. options = options || {};
  11587. options.tables = options.tables || {};
  11588. if (!options.empty) {
  11589. // Check that we've provided the minimum set of names.
  11590. checkArgument(options.familyName, 'When creating a new Font object, familyName is required.');
  11591. checkArgument(options.styleName, 'When creating a new Font object, styleName is required.');
  11592. checkArgument(options.unitsPerEm, 'When creating a new Font object, unitsPerEm is required.');
  11593. checkArgument(options.ascender, 'When creating a new Font object, ascender is required.');
  11594. checkArgument(options.descender <= 0, 'When creating a new Font object, negative descender value is required.');
  11595. // OS X will complain if the names are empty, so we put a single space everywhere by default.
  11596. this.names = {
  11597. fontFamily: {en: options.familyName || ' '},
  11598. fontSubfamily: {en: options.styleName || ' '},
  11599. fullName: {en: options.fullName || options.familyName + ' ' + options.styleName},
  11600. // postScriptName may not contain any whitespace
  11601. postScriptName: {en: options.postScriptName || (options.familyName + options.styleName).replace(/\s/g, '')},
  11602. designer: {en: options.designer || ' '},
  11603. designerURL: {en: options.designerURL || ' '},
  11604. manufacturer: {en: options.manufacturer || ' '},
  11605. manufacturerURL: {en: options.manufacturerURL || ' '},
  11606. license: {en: options.license || ' '},
  11607. licenseURL: {en: options.licenseURL || ' '},
  11608. version: {en: options.version || 'Version 0.1'},
  11609. description: {en: options.description || ' '},
  11610. copyright: {en: options.copyright || ' '},
  11611. trademark: {en: options.trademark || ' '}
  11612. };
  11613. this.unitsPerEm = options.unitsPerEm || 1000;
  11614. this.ascender = options.ascender;
  11615. this.descender = options.descender;
  11616. this.createdTimestamp = options.createdTimestamp;
  11617. this.tables = Object.assign(options.tables, {
  11618. os2: Object.assign({
  11619. usWeightClass: options.weightClass || this.usWeightClasses.MEDIUM,
  11620. usWidthClass: options.widthClass || this.usWidthClasses.MEDIUM,
  11621. fsSelection: options.fsSelection || this.fsSelectionValues.REGULAR,
  11622. }, options.tables.os2)
  11623. });
  11624. }
  11625. this.supported = true; // Deprecated: parseBuffer will throw an error if font is not supported.
  11626. this.glyphs = new glyphset.GlyphSet(this, options.glyphs || []);
  11627. this.encoding = new DefaultEncoding(this);
  11628. this.position = new Position(this);
  11629. this.substitution = new Substitution(this);
  11630. this.tables = this.tables || {};
  11631. // needed for low memory mode only.
  11632. this._push = null;
  11633. this._hmtxTableData = {};
  11634. Object.defineProperty(this, 'hinting', {
  11635. get: function() {
  11636. if (this._hinting) { return this._hinting; }
  11637. if (this.outlinesFormat === 'truetype') {
  11638. return (this._hinting = new Hinting(this));
  11639. }
  11640. }
  11641. });
  11642. }
  11643. /**
  11644. * Check if the font has a glyph for the given character.
  11645. * @param {string}
  11646. * @return {Boolean}
  11647. */
  11648. Font.prototype.hasChar = function(c) {
  11649. return this.encoding.charToGlyphIndex(c) !== null;
  11650. };
  11651. /**
  11652. * Convert the given character to a single glyph index.
  11653. * Note that this function assumes that there is a one-to-one mapping between
  11654. * the given character and a glyph; for complex scripts this might not be the case.
  11655. * @param {string}
  11656. * @return {Number}
  11657. */
  11658. Font.prototype.charToGlyphIndex = function(s) {
  11659. return this.encoding.charToGlyphIndex(s);
  11660. };
  11661. /**
  11662. * Convert the given character to a single Glyph object.
  11663. * Note that this function assumes that there is a one-to-one mapping between
  11664. * the given character and a glyph; for complex scripts this might not be the case.
  11665. * @param {string}
  11666. * @return {opentype.Glyph}
  11667. */
  11668. Font.prototype.charToGlyph = function(c) {
  11669. var glyphIndex = this.charToGlyphIndex(c);
  11670. var glyph = this.glyphs.get(glyphIndex);
  11671. if (!glyph) {
  11672. // .notdef
  11673. glyph = this.glyphs.get(0);
  11674. }
  11675. return glyph;
  11676. };
  11677. /**
  11678. * Update features
  11679. * @param {any} options features options
  11680. */
  11681. Font.prototype.updateFeatures = function (options) {
  11682. // TODO: update all features options not only 'latn'.
  11683. return this.defaultRenderOptions.features.map(function (feature) {
  11684. if (feature.script === 'latn') {
  11685. return {
  11686. script: 'latn',
  11687. tags: feature.tags.filter(function (tag) { return options[tag]; })
  11688. };
  11689. } else {
  11690. return feature;
  11691. }
  11692. });
  11693. };
  11694. /**
  11695. * Convert the given text to a list of Glyph objects.
  11696. * Note that there is no strict one-to-one mapping between characters and
  11697. * glyphs, so the list of returned glyphs can be larger or smaller than the
  11698. * length of the given string.
  11699. * @param {string}
  11700. * @param {GlyphRenderOptions} [options]
  11701. * @return {opentype.Glyph[]}
  11702. */
  11703. Font.prototype.stringToGlyphs = function(s, options) {
  11704. var this$1 = this;
  11705. var bidi = new Bidi();
  11706. // Create and register 'glyphIndex' state modifier
  11707. var charToGlyphIndexMod = function (token) { return this$1.charToGlyphIndex(token.char); };
  11708. bidi.registerModifier('glyphIndex', null, charToGlyphIndexMod);
  11709. // roll-back to default features
  11710. var features = options ?
  11711. this.updateFeatures(options.features) :
  11712. this.defaultRenderOptions.features;
  11713. bidi.applyFeatures(this, features);
  11714. var indexes = bidi.getTextGlyphs(s);
  11715. var length = indexes.length;
  11716. // convert glyph indexes to glyph objects
  11717. var glyphs = new Array(length);
  11718. var notdef = this.glyphs.get(0);
  11719. for (var i = 0; i < length; i += 1) {
  11720. glyphs[i] = this.glyphs.get(indexes[i]) || notdef;
  11721. }
  11722. return glyphs;
  11723. };
  11724. /**
  11725. * @param {string}
  11726. * @return {Number}
  11727. */
  11728. Font.prototype.nameToGlyphIndex = function(name) {
  11729. return this.glyphNames.nameToGlyphIndex(name);
  11730. };
  11731. /**
  11732. * @param {string}
  11733. * @return {opentype.Glyph}
  11734. */
  11735. Font.prototype.nameToGlyph = function(name) {
  11736. var glyphIndex = this.nameToGlyphIndex(name);
  11737. var glyph = this.glyphs.get(glyphIndex);
  11738. if (!glyph) {
  11739. // .notdef
  11740. glyph = this.glyphs.get(0);
  11741. }
  11742. return glyph;
  11743. };
  11744. /**
  11745. * @param {Number}
  11746. * @return {String}
  11747. */
  11748. Font.prototype.glyphIndexToName = function(gid) {
  11749. if (!this.glyphNames.glyphIndexToName) {
  11750. return '';
  11751. }
  11752. return this.glyphNames.glyphIndexToName(gid);
  11753. };
  11754. /**
  11755. * Retrieve the value of the kerning pair between the left glyph (or its index)
  11756. * and the right glyph (or its index). If no kerning pair is found, return 0.
  11757. * The kerning value gets added to the advance width when calculating the spacing
  11758. * between glyphs.
  11759. * For GPOS kerning, this method uses the default script and language, which covers
  11760. * most use cases. To have greater control, use font.position.getKerningValue .
  11761. * @param {opentype.Glyph} leftGlyph
  11762. * @param {opentype.Glyph} rightGlyph
  11763. * @return {Number}
  11764. */
  11765. Font.prototype.getKerningValue = function(leftGlyph, rightGlyph) {
  11766. leftGlyph = leftGlyph.index || leftGlyph;
  11767. rightGlyph = rightGlyph.index || rightGlyph;
  11768. var gposKerning = this.position.defaultKerningTables;
  11769. if (gposKerning) {
  11770. return this.position.getKerningValue(gposKerning, leftGlyph, rightGlyph);
  11771. }
  11772. // "kern" table
  11773. return this.kerningPairs[leftGlyph + ',' + rightGlyph] || 0;
  11774. };
  11775. /**
  11776. * @typedef GlyphRenderOptions
  11777. * @type Object
  11778. * @property {string} [script] - script used to determine which features to apply. By default, 'DFLT' or 'latn' is used.
  11779. * See https://www.microsoft.com/typography/otspec/scripttags.htm
  11780. * @property {string} [language='dflt'] - language system used to determine which features to apply.
  11781. * See https://www.microsoft.com/typography/developers/opentype/languagetags.aspx
  11782. * @property {boolean} [kerning=true] - whether to include kerning values
  11783. * @property {object} [features] - OpenType Layout feature tags. Used to enable or disable the features of the given script/language system.
  11784. * See https://www.microsoft.com/typography/otspec/featuretags.htm
  11785. */
  11786. Font.prototype.defaultRenderOptions = {
  11787. kerning: true,
  11788. features: [
  11789. /**
  11790. * these 4 features are required to render Arabic text properly
  11791. * and shouldn't be turned off when rendering arabic text.
  11792. */
  11793. { script: 'arab', tags: ['init', 'medi', 'fina', 'rlig'] },
  11794. { script: 'latn', tags: ['liga', 'rlig'] }
  11795. ]
  11796. };
  11797. /**
  11798. * Helper function that invokes the given callback for each glyph in the given text.
  11799. * The callback gets `(glyph, x, y, fontSize, options)`.* @param {string} text
  11800. * @param {string} text - The text to apply.
  11801. * @param {number} [x=0] - Horizontal position of the beginning of the text.
  11802. * @param {number} [y=0] - Vertical position of the *baseline* of the text.
  11803. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
  11804. * @param {GlyphRenderOptions=} options
  11805. * @param {Function} callback
  11806. */
  11807. Font.prototype.forEachGlyph = function(text, x, y, fontSize, options, callback) {
  11808. x = x !== undefined ? x : 0;
  11809. y = y !== undefined ? y : 0;
  11810. fontSize = fontSize !== undefined ? fontSize : 72;
  11811. options = Object.assign({}, this.defaultRenderOptions, options);
  11812. var fontScale = 1 / this.unitsPerEm * fontSize;
  11813. var glyphs = this.stringToGlyphs(text, options);
  11814. var kerningLookups;
  11815. if (options.kerning) {
  11816. var script = options.script || this.position.getDefaultScriptName();
  11817. kerningLookups = this.position.getKerningTables(script, options.language);
  11818. }
  11819. for (var i = 0; i < glyphs.length; i += 1) {
  11820. var glyph = glyphs[i];
  11821. callback.call(this, glyph, x, y, fontSize, options);
  11822. if (glyph.advanceWidth) {
  11823. x += glyph.advanceWidth * fontScale;
  11824. }
  11825. if (options.kerning && i < glyphs.length - 1) {
  11826. // We should apply position adjustment lookups in a more generic way.
  11827. // Here we only use the xAdvance value.
  11828. var kerningValue = kerningLookups ?
  11829. this.position.getKerningValue(kerningLookups, glyph.index, glyphs[i + 1].index) :
  11830. this.getKerningValue(glyph, glyphs[i + 1]);
  11831. x += kerningValue * fontScale;
  11832. }
  11833. if (options.letterSpacing) {
  11834. x += options.letterSpacing * fontSize;
  11835. } else if (options.tracking) {
  11836. x += (options.tracking / 1000) * fontSize;
  11837. }
  11838. }
  11839. return x;
  11840. };
  11841. /**
  11842. * Create a Path object that represents the given text.
  11843. * @param {string} text - The text to create.
  11844. * @param {number} [x=0] - Horizontal position of the beginning of the text.
  11845. * @param {number} [y=0] - Vertical position of the *baseline* of the text.
  11846. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
  11847. * @param {GlyphRenderOptions=} options
  11848. * @return {opentype.Path}
  11849. */
  11850. Font.prototype.getPath = function(text, x, y, fontSize, options) {
  11851. var fullPath = new Path();
  11852. this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) {
  11853. var glyphPath = glyph.getPath(gX, gY, gFontSize, options, this);
  11854. fullPath.extend(glyphPath);
  11855. });
  11856. return fullPath;
  11857. };
  11858. /**
  11859. * Create an array of Path objects that represent the glyphs of a given text.
  11860. * @param {string} text - The text to create.
  11861. * @param {number} [x=0] - Horizontal position of the beginning of the text.
  11862. * @param {number} [y=0] - Vertical position of the *baseline* of the text.
  11863. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
  11864. * @param {GlyphRenderOptions=} options
  11865. * @return {opentype.Path[]}
  11866. */
  11867. Font.prototype.getPaths = function(text, x, y, fontSize, options) {
  11868. var glyphPaths = [];
  11869. this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) {
  11870. var glyphPath = glyph.getPath(gX, gY, gFontSize, options, this);
  11871. glyphPaths.push(glyphPath);
  11872. });
  11873. return glyphPaths;
  11874. };
  11875. /**
  11876. * Returns the advance width of a text.
  11877. *
  11878. * This is something different than Path.getBoundingBox() as for example a
  11879. * suffixed whitespace increases the advanceWidth but not the bounding box
  11880. * or an overhanging letter like a calligraphic 'f' might have a quite larger
  11881. * bounding box than its advance width.
  11882. *
  11883. * This corresponds to canvas2dContext.measureText(text).width
  11884. *
  11885. * @param {string} text - The text to create.
  11886. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
  11887. * @param {GlyphRenderOptions=} options
  11888. * @return advance width
  11889. */
  11890. Font.prototype.getAdvanceWidth = function(text, fontSize, options) {
  11891. return this.forEachGlyph(text, 0, 0, fontSize, options, function() {});
  11892. };
  11893. /**
  11894. * Draw the text on the given drawing context.
  11895. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas.
  11896. * @param {string} text - The text to create.
  11897. * @param {number} [x=0] - Horizontal position of the beginning of the text.
  11898. * @param {number} [y=0] - Vertical position of the *baseline* of the text.
  11899. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
  11900. * @param {GlyphRenderOptions=} options
  11901. */
  11902. Font.prototype.draw = function(ctx, text, x, y, fontSize, options) {
  11903. this.getPath(text, x, y, fontSize, options).draw(ctx);
  11904. };
  11905. /**
  11906. * Draw the points of all glyphs in the text.
  11907. * On-curve points will be drawn in blue, off-curve points will be drawn in red.
  11908. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas.
  11909. * @param {string} text - The text to create.
  11910. * @param {number} [x=0] - Horizontal position of the beginning of the text.
  11911. * @param {number} [y=0] - Vertical position of the *baseline* of the text.
  11912. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
  11913. * @param {GlyphRenderOptions=} options
  11914. */
  11915. Font.prototype.drawPoints = function(ctx, text, x, y, fontSize, options) {
  11916. this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) {
  11917. glyph.drawPoints(ctx, gX, gY, gFontSize);
  11918. });
  11919. };
  11920. /**
  11921. * Draw lines indicating important font measurements for all glyphs in the text.
  11922. * Black lines indicate the origin of the coordinate system (point 0,0).
  11923. * Blue lines indicate the glyph bounding box.
  11924. * Green line indicates the advance width of the glyph.
  11925. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas.
  11926. * @param {string} text - The text to create.
  11927. * @param {number} [x=0] - Horizontal position of the beginning of the text.
  11928. * @param {number} [y=0] - Vertical position of the *baseline* of the text.
  11929. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
  11930. * @param {GlyphRenderOptions=} options
  11931. */
  11932. Font.prototype.drawMetrics = function(ctx, text, x, y, fontSize, options) {
  11933. this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) {
  11934. glyph.drawMetrics(ctx, gX, gY, gFontSize);
  11935. });
  11936. };
  11937. /**
  11938. * @param {string}
  11939. * @return {string}
  11940. */
  11941. Font.prototype.getEnglishName = function(name) {
  11942. var translations = this.names[name];
  11943. if (translations) {
  11944. return translations.en;
  11945. }
  11946. };
  11947. /**
  11948. * Validate
  11949. */
  11950. Font.prototype.validate = function() {
  11951. var _this = this;
  11952. function assert(predicate, message) {
  11953. }
  11954. function assertNamePresent(name) {
  11955. var englishName = _this.getEnglishName(name);
  11956. assert(englishName && englishName.trim().length > 0);
  11957. }
  11958. // Identification information
  11959. assertNamePresent('fontFamily');
  11960. assertNamePresent('weightName');
  11961. assertNamePresent('manufacturer');
  11962. assertNamePresent('copyright');
  11963. assertNamePresent('version');
  11964. // Dimension information
  11965. assert(this.unitsPerEm > 0);
  11966. };
  11967. /**
  11968. * Convert the font object to a SFNT data structure.
  11969. * This structure contains all the necessary tables and metadata to create a binary OTF file.
  11970. * @return {opentype.Table}
  11971. */
  11972. Font.prototype.toTables = function() {
  11973. return sfnt.fontToTable(this);
  11974. };
  11975. /**
  11976. * @deprecated Font.toBuffer is deprecated. Use Font.toArrayBuffer instead.
  11977. */
  11978. Font.prototype.toBuffer = function() {
  11979. console.warn('Font.toBuffer is deprecated. Use Font.toArrayBuffer instead.');
  11980. return this.toArrayBuffer();
  11981. };
  11982. /**
  11983. * Converts a `opentype.Font` into an `ArrayBuffer`
  11984. * @return {ArrayBuffer}
  11985. */
  11986. Font.prototype.toArrayBuffer = function() {
  11987. var sfntTable = this.toTables();
  11988. var bytes = sfntTable.encode();
  11989. var buffer = new ArrayBuffer(bytes.length);
  11990. var intArray = new Uint8Array(buffer);
  11991. for (var i = 0; i < bytes.length; i++) {
  11992. intArray[i] = bytes[i];
  11993. }
  11994. return buffer;
  11995. };
  11996. /**
  11997. * Initiate a download of the OpenType font.
  11998. */
  11999. Font.prototype.download = function(fileName) {
  12000. var familyName = this.getEnglishName('fontFamily');
  12001. var styleName = this.getEnglishName('fontSubfamily');
  12002. fileName = fileName || familyName.replace(/\s/g, '') + '-' + styleName + '.otf';
  12003. var arrayBuffer = this.toArrayBuffer();
  12004. if (isBrowser()) {
  12005. window.URL = window.URL || window.webkitURL;
  12006. if (window.URL) {
  12007. var dataView = new DataView(arrayBuffer);
  12008. var blob = new Blob([dataView], {type: 'font/opentype'});
  12009. var link = document.createElement('a');
  12010. link.href = window.URL.createObjectURL(blob);
  12011. link.download = fileName;
  12012. var event = document.createEvent('MouseEvents');
  12013. event.initEvent('click', true, false);
  12014. link.dispatchEvent(event);
  12015. } else {
  12016. console.warn('Font file could not be downloaded. Try using a different browser.');
  12017. }
  12018. } else {
  12019. var fs = require('fs');
  12020. var buffer = arrayBufferToNodeBuffer(arrayBuffer);
  12021. fs.writeFileSync(fileName, buffer);
  12022. }
  12023. };
  12024. /**
  12025. * @private
  12026. */
  12027. Font.prototype.fsSelectionValues = {
  12028. ITALIC: 0x001, //1
  12029. UNDERSCORE: 0x002, //2
  12030. NEGATIVE: 0x004, //4
  12031. OUTLINED: 0x008, //8
  12032. STRIKEOUT: 0x010, //16
  12033. BOLD: 0x020, //32
  12034. REGULAR: 0x040, //64
  12035. USER_TYPO_METRICS: 0x080, //128
  12036. WWS: 0x100, //256
  12037. OBLIQUE: 0x200 //512
  12038. };
  12039. /**
  12040. * @private
  12041. */
  12042. Font.prototype.usWidthClasses = {
  12043. ULTRA_CONDENSED: 1,
  12044. EXTRA_CONDENSED: 2,
  12045. CONDENSED: 3,
  12046. SEMI_CONDENSED: 4,
  12047. MEDIUM: 5,
  12048. SEMI_EXPANDED: 6,
  12049. EXPANDED: 7,
  12050. EXTRA_EXPANDED: 8,
  12051. ULTRA_EXPANDED: 9
  12052. };
  12053. /**
  12054. * @private
  12055. */
  12056. Font.prototype.usWeightClasses = {
  12057. THIN: 100,
  12058. EXTRA_LIGHT: 200,
  12059. LIGHT: 300,
  12060. NORMAL: 400,
  12061. MEDIUM: 500,
  12062. SEMI_BOLD: 600,
  12063. BOLD: 700,
  12064. EXTRA_BOLD: 800,
  12065. BLACK: 900
  12066. };
  12067. // The `fvar` table stores font variation axes and instances.
  12068. function addName(name, names) {
  12069. var nameString = JSON.stringify(name);
  12070. var nameID = 256;
  12071. for (var nameKey in names) {
  12072. var n = parseInt(nameKey);
  12073. if (!n || n < 256) {
  12074. continue;
  12075. }
  12076. if (JSON.stringify(names[nameKey]) === nameString) {
  12077. return n;
  12078. }
  12079. if (nameID <= n) {
  12080. nameID = n + 1;
  12081. }
  12082. }
  12083. names[nameID] = name;
  12084. return nameID;
  12085. }
  12086. function makeFvarAxis(n, axis, names) {
  12087. var nameID = addName(axis.name, names);
  12088. return [
  12089. {name: 'tag_' + n, type: 'TAG', value: axis.tag},
  12090. {name: 'minValue_' + n, type: 'FIXED', value: axis.minValue << 16},
  12091. {name: 'defaultValue_' + n, type: 'FIXED', value: axis.defaultValue << 16},
  12092. {name: 'maxValue_' + n, type: 'FIXED', value: axis.maxValue << 16},
  12093. {name: 'flags_' + n, type: 'USHORT', value: 0},
  12094. {name: 'nameID_' + n, type: 'USHORT', value: nameID}
  12095. ];
  12096. }
  12097. function parseFvarAxis(data, start, names) {
  12098. var axis = {};
  12099. var p = new parse.Parser(data, start);
  12100. axis.tag = p.parseTag();
  12101. axis.minValue = p.parseFixed();
  12102. axis.defaultValue = p.parseFixed();
  12103. axis.maxValue = p.parseFixed();
  12104. p.skip('uShort', 1); // reserved for flags; no values defined
  12105. axis.name = names[p.parseUShort()] || {};
  12106. return axis;
  12107. }
  12108. function makeFvarInstance(n, inst, axes, names) {
  12109. var nameID = addName(inst.name, names);
  12110. var fields = [
  12111. {name: 'nameID_' + n, type: 'USHORT', value: nameID},
  12112. {name: 'flags_' + n, type: 'USHORT', value: 0}
  12113. ];
  12114. for (var i = 0; i < axes.length; ++i) {
  12115. var axisTag = axes[i].tag;
  12116. fields.push({
  12117. name: 'axis_' + n + ' ' + axisTag,
  12118. type: 'FIXED',
  12119. value: inst.coordinates[axisTag] << 16
  12120. });
  12121. }
  12122. return fields;
  12123. }
  12124. function parseFvarInstance(data, start, axes, names) {
  12125. var inst = {};
  12126. var p = new parse.Parser(data, start);
  12127. inst.name = names[p.parseUShort()] || {};
  12128. p.skip('uShort', 1); // reserved for flags; no values defined
  12129. inst.coordinates = {};
  12130. for (var i = 0; i < axes.length; ++i) {
  12131. inst.coordinates[axes[i].tag] = p.parseFixed();
  12132. }
  12133. return inst;
  12134. }
  12135. function makeFvarTable(fvar, names) {
  12136. var result = new table.Table('fvar', [
  12137. {name: 'version', type: 'ULONG', value: 0x10000},
  12138. {name: 'offsetToData', type: 'USHORT', value: 0},
  12139. {name: 'countSizePairs', type: 'USHORT', value: 2},
  12140. {name: 'axisCount', type: 'USHORT', value: fvar.axes.length},
  12141. {name: 'axisSize', type: 'USHORT', value: 20},
  12142. {name: 'instanceCount', type: 'USHORT', value: fvar.instances.length},
  12143. {name: 'instanceSize', type: 'USHORT', value: 4 + fvar.axes.length * 4}
  12144. ]);
  12145. result.offsetToData = result.sizeOf();
  12146. for (var i = 0; i < fvar.axes.length; i++) {
  12147. result.fields = result.fields.concat(makeFvarAxis(i, fvar.axes[i], names));
  12148. }
  12149. for (var j = 0; j < fvar.instances.length; j++) {
  12150. result.fields = result.fields.concat(makeFvarInstance(j, fvar.instances[j], fvar.axes, names));
  12151. }
  12152. return result;
  12153. }
  12154. function parseFvarTable(data, start, names) {
  12155. var p = new parse.Parser(data, start);
  12156. var tableVersion = p.parseULong();
  12157. check.argument(tableVersion === 0x00010000, 'Unsupported fvar table version.');
  12158. var offsetToData = p.parseOffset16();
  12159. // Skip countSizePairs.
  12160. p.skip('uShort', 1);
  12161. var axisCount = p.parseUShort();
  12162. var axisSize = p.parseUShort();
  12163. var instanceCount = p.parseUShort();
  12164. var instanceSize = p.parseUShort();
  12165. var axes = [];
  12166. for (var i = 0; i < axisCount; i++) {
  12167. axes.push(parseFvarAxis(data, start + offsetToData + i * axisSize, names));
  12168. }
  12169. var instances = [];
  12170. var instanceStart = start + offsetToData + axisCount * axisSize;
  12171. for (var j = 0; j < instanceCount; j++) {
  12172. instances.push(parseFvarInstance(data, instanceStart + j * instanceSize, axes, names));
  12173. }
  12174. return {axes: axes, instances: instances};
  12175. }
  12176. var fvar = { make: makeFvarTable, parse: parseFvarTable };
  12177. // The `GDEF` table contains various glyph properties
  12178. var attachList = function() {
  12179. return {
  12180. coverage: this.parsePointer(Parser.coverage),
  12181. attachPoints: this.parseList(Parser.pointer(Parser.uShortList))
  12182. };
  12183. };
  12184. var caretValue = function() {
  12185. var format = this.parseUShort();
  12186. check.argument(format === 1 || format === 2 || format === 3,
  12187. 'Unsupported CaretValue table version.');
  12188. if (format === 1) {
  12189. return { coordinate: this.parseShort() };
  12190. } else if (format === 2) {
  12191. return { pointindex: this.parseShort() };
  12192. } else if (format === 3) {
  12193. // Device / Variation Index tables unsupported
  12194. return { coordinate: this.parseShort() };
  12195. }
  12196. };
  12197. var ligGlyph = function() {
  12198. return this.parseList(Parser.pointer(caretValue));
  12199. };
  12200. var ligCaretList = function() {
  12201. return {
  12202. coverage: this.parsePointer(Parser.coverage),
  12203. ligGlyphs: this.parseList(Parser.pointer(ligGlyph))
  12204. };
  12205. };
  12206. var markGlyphSets = function() {
  12207. this.parseUShort(); // Version
  12208. return this.parseList(Parser.pointer(Parser.coverage));
  12209. };
  12210. function parseGDEFTable(data, start) {
  12211. start = start || 0;
  12212. var p = new Parser(data, start);
  12213. var tableVersion = p.parseVersion(1);
  12214. check.argument(tableVersion === 1 || tableVersion === 1.2 || tableVersion === 1.3,
  12215. 'Unsupported GDEF table version.');
  12216. var gdef = {
  12217. version: tableVersion,
  12218. classDef: p.parsePointer(Parser.classDef),
  12219. attachList: p.parsePointer(attachList),
  12220. ligCaretList: p.parsePointer(ligCaretList),
  12221. markAttachClassDef: p.parsePointer(Parser.classDef)
  12222. };
  12223. if (tableVersion >= 1.2) {
  12224. gdef.markGlyphSets = p.parsePointer(markGlyphSets);
  12225. }
  12226. return gdef;
  12227. }
  12228. var gdef = { parse: parseGDEFTable };
  12229. // The `GPOS` table contains kerning pairs, among other things.
  12230. var subtableParsers$1 = new Array(10); // subtableParsers[0] is unused
  12231. // https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#lookup-type-1-single-adjustment-positioning-subtable
  12232. // this = Parser instance
  12233. subtableParsers$1[1] = function parseLookup1() {
  12234. var start = this.offset + this.relativeOffset;
  12235. var posformat = this.parseUShort();
  12236. if (posformat === 1) {
  12237. return {
  12238. posFormat: 1,
  12239. coverage: this.parsePointer(Parser.coverage),
  12240. value: this.parseValueRecord()
  12241. };
  12242. } else if (posformat === 2) {
  12243. return {
  12244. posFormat: 2,
  12245. coverage: this.parsePointer(Parser.coverage),
  12246. values: this.parseValueRecordList()
  12247. };
  12248. }
  12249. check.assert(false, '0x' + start.toString(16) + ': GPOS lookup type 1 format must be 1 or 2.');
  12250. };
  12251. // https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#lookup-type-2-pair-adjustment-positioning-subtable
  12252. subtableParsers$1[2] = function parseLookup2() {
  12253. var start = this.offset + this.relativeOffset;
  12254. var posFormat = this.parseUShort();
  12255. check.assert(posFormat === 1 || posFormat === 2, '0x' + start.toString(16) + ': GPOS lookup type 2 format must be 1 or 2.');
  12256. var coverage = this.parsePointer(Parser.coverage);
  12257. var valueFormat1 = this.parseUShort();
  12258. var valueFormat2 = this.parseUShort();
  12259. if (posFormat === 1) {
  12260. // Adjustments for Glyph Pairs
  12261. return {
  12262. posFormat: posFormat,
  12263. coverage: coverage,
  12264. valueFormat1: valueFormat1,
  12265. valueFormat2: valueFormat2,
  12266. pairSets: this.parseList(Parser.pointer(Parser.list(function() {
  12267. return { // pairValueRecord
  12268. secondGlyph: this.parseUShort(),
  12269. value1: this.parseValueRecord(valueFormat1),
  12270. value2: this.parseValueRecord(valueFormat2)
  12271. };
  12272. })))
  12273. };
  12274. } else if (posFormat === 2) {
  12275. var classDef1 = this.parsePointer(Parser.classDef);
  12276. var classDef2 = this.parsePointer(Parser.classDef);
  12277. var class1Count = this.parseUShort();
  12278. var class2Count = this.parseUShort();
  12279. return {
  12280. // Class Pair Adjustment
  12281. posFormat: posFormat,
  12282. coverage: coverage,
  12283. valueFormat1: valueFormat1,
  12284. valueFormat2: valueFormat2,
  12285. classDef1: classDef1,
  12286. classDef2: classDef2,
  12287. class1Count: class1Count,
  12288. class2Count: class2Count,
  12289. classRecords: this.parseList(class1Count, Parser.list(class2Count, function() {
  12290. return {
  12291. value1: this.parseValueRecord(valueFormat1),
  12292. value2: this.parseValueRecord(valueFormat2)
  12293. };
  12294. }))
  12295. };
  12296. }
  12297. };
  12298. subtableParsers$1[3] = function parseLookup3() { return { error: 'GPOS Lookup 3 not supported' }; };
  12299. subtableParsers$1[4] = function parseLookup4() { return { error: 'GPOS Lookup 4 not supported' }; };
  12300. subtableParsers$1[5] = function parseLookup5() { return { error: 'GPOS Lookup 5 not supported' }; };
  12301. subtableParsers$1[6] = function parseLookup6() { return { error: 'GPOS Lookup 6 not supported' }; };
  12302. subtableParsers$1[7] = function parseLookup7() { return { error: 'GPOS Lookup 7 not supported' }; };
  12303. subtableParsers$1[8] = function parseLookup8() { return { error: 'GPOS Lookup 8 not supported' }; };
  12304. subtableParsers$1[9] = function parseLookup9() { return { error: 'GPOS Lookup 9 not supported' }; };
  12305. // https://docs.microsoft.com/en-us/typography/opentype/spec/gpos
  12306. function parseGposTable(data, start) {
  12307. start = start || 0;
  12308. var p = new Parser(data, start);
  12309. var tableVersion = p.parseVersion(1);
  12310. check.argument(tableVersion === 1 || tableVersion === 1.1, 'Unsupported GPOS table version ' + tableVersion);
  12311. if (tableVersion === 1) {
  12312. return {
  12313. version: tableVersion,
  12314. scripts: p.parseScriptList(),
  12315. features: p.parseFeatureList(),
  12316. lookups: p.parseLookupList(subtableParsers$1)
  12317. };
  12318. } else {
  12319. return {
  12320. version: tableVersion,
  12321. scripts: p.parseScriptList(),
  12322. features: p.parseFeatureList(),
  12323. lookups: p.parseLookupList(subtableParsers$1),
  12324. variations: p.parseFeatureVariationsList()
  12325. };
  12326. }
  12327. }
  12328. // GPOS Writing //////////////////////////////////////////////
  12329. // NOT SUPPORTED
  12330. var subtableMakers$1 = new Array(10);
  12331. function makeGposTable(gpos) {
  12332. return new table.Table('GPOS', [
  12333. {name: 'version', type: 'ULONG', value: 0x10000},
  12334. {name: 'scripts', type: 'TABLE', value: new table.ScriptList(gpos.scripts)},
  12335. {name: 'features', type: 'TABLE', value: new table.FeatureList(gpos.features)},
  12336. {name: 'lookups', type: 'TABLE', value: new table.LookupList(gpos.lookups, subtableMakers$1)}
  12337. ]);
  12338. }
  12339. var gpos = { parse: parseGposTable, make: makeGposTable };
  12340. // The `kern` table contains kerning pairs.
  12341. function parseWindowsKernTable(p) {
  12342. var pairs = {};
  12343. // Skip nTables.
  12344. p.skip('uShort');
  12345. var subtableVersion = p.parseUShort();
  12346. check.argument(subtableVersion === 0, 'Unsupported kern sub-table version.');
  12347. // Skip subtableLength, subtableCoverage
  12348. p.skip('uShort', 2);
  12349. var nPairs = p.parseUShort();
  12350. // Skip searchRange, entrySelector, rangeShift.
  12351. p.skip('uShort', 3);
  12352. for (var i = 0; i < nPairs; i += 1) {
  12353. var leftIndex = p.parseUShort();
  12354. var rightIndex = p.parseUShort();
  12355. var value = p.parseShort();
  12356. pairs[leftIndex + ',' + rightIndex] = value;
  12357. }
  12358. return pairs;
  12359. }
  12360. function parseMacKernTable(p) {
  12361. var pairs = {};
  12362. // The Mac kern table stores the version as a fixed (32 bits) but we only loaded the first 16 bits.
  12363. // Skip the rest.
  12364. p.skip('uShort');
  12365. var nTables = p.parseULong();
  12366. //check.argument(nTables === 1, 'Only 1 subtable is supported (got ' + nTables + ').');
  12367. if (nTables > 1) {
  12368. console.warn('Only the first kern subtable is supported.');
  12369. }
  12370. p.skip('uLong');
  12371. var coverage = p.parseUShort();
  12372. var subtableVersion = coverage & 0xFF;
  12373. p.skip('uShort');
  12374. if (subtableVersion === 0) {
  12375. var nPairs = p.parseUShort();
  12376. // Skip searchRange, entrySelector, rangeShift.
  12377. p.skip('uShort', 3);
  12378. for (var i = 0; i < nPairs; i += 1) {
  12379. var leftIndex = p.parseUShort();
  12380. var rightIndex = p.parseUShort();
  12381. var value = p.parseShort();
  12382. pairs[leftIndex + ',' + rightIndex] = value;
  12383. }
  12384. }
  12385. return pairs;
  12386. }
  12387. // Parse the `kern` table which contains kerning pairs.
  12388. function parseKernTable(data, start) {
  12389. var p = new parse.Parser(data, start);
  12390. var tableVersion = p.parseUShort();
  12391. if (tableVersion === 0) {
  12392. return parseWindowsKernTable(p);
  12393. } else if (tableVersion === 1) {
  12394. return parseMacKernTable(p);
  12395. } else {
  12396. throw new Error('Unsupported kern table version (' + tableVersion + ').');
  12397. }
  12398. }
  12399. var kern = { parse: parseKernTable };
  12400. // The `loca` table stores the offsets to the locations of the glyphs in the font.
  12401. // Parse the `loca` table. This table stores the offsets to the locations of the glyphs in the font,
  12402. // relative to the beginning of the glyphData table.
  12403. // The number of glyphs stored in the `loca` table is specified in the `maxp` table (under numGlyphs)
  12404. // The loca table has two versions: a short version where offsets are stored as uShorts, and a long
  12405. // version where offsets are stored as uLongs. The `head` table specifies which version to use
  12406. // (under indexToLocFormat).
  12407. function parseLocaTable(data, start, numGlyphs, shortVersion) {
  12408. var p = new parse.Parser(data, start);
  12409. var parseFn = shortVersion ? p.parseUShort : p.parseULong;
  12410. // There is an extra entry after the last index element to compute the length of the last glyph.
  12411. // That's why we use numGlyphs + 1.
  12412. var glyphOffsets = [];
  12413. for (var i = 0; i < numGlyphs + 1; i += 1) {
  12414. var glyphOffset = parseFn.call(p);
  12415. if (shortVersion) {
  12416. // The short table version stores the actual offset divided by 2.
  12417. glyphOffset *= 2;
  12418. }
  12419. glyphOffsets.push(glyphOffset);
  12420. }
  12421. return glyphOffsets;
  12422. }
  12423. var loca = { parse: parseLocaTable };
  12424. // opentype.js
  12425. /**
  12426. * The opentype library.
  12427. * @namespace opentype
  12428. */
  12429. // File loaders /////////////////////////////////////////////////////////
  12430. /**
  12431. * Loads a font from a file. The callback throws an error message as the first parameter if it fails
  12432. * and the font as an ArrayBuffer in the second parameter if it succeeds.
  12433. * @param {string} path - The path of the file
  12434. * @param {Function} callback - The function to call when the font load completes
  12435. */
  12436. function loadFromFile(path, callback) {
  12437. var fs = require('fs');
  12438. fs.readFile(path, function(err, buffer) {
  12439. if (err) {
  12440. return callback(err.message);
  12441. }
  12442. callback(null, nodeBufferToArrayBuffer(buffer));
  12443. });
  12444. }
  12445. /**
  12446. * Loads a font from a URL. The callback throws an error message as the first parameter if it fails
  12447. * and the font as an ArrayBuffer in the second parameter if it succeeds.
  12448. * @param {string} url - The URL of the font file.
  12449. * @param {Function} callback - The function to call when the font load completes
  12450. */
  12451. function loadFromUrl(url, callback) {
  12452. var request = new XMLHttpRequest();
  12453. request.open('get', url, true);
  12454. request.responseType = 'arraybuffer';
  12455. request.onload = function() {
  12456. if (request.response) {
  12457. return callback(null, request.response);
  12458. } else {
  12459. return callback('Font could not be loaded: ' + request.statusText);
  12460. }
  12461. };
  12462. request.onerror = function () {
  12463. callback('Font could not be loaded');
  12464. };
  12465. request.send();
  12466. }
  12467. // Table Directory Entries //////////////////////////////////////////////
  12468. /**
  12469. * Parses OpenType table entries.
  12470. * @param {DataView}
  12471. * @param {Number}
  12472. * @return {Object[]}
  12473. */
  12474. function parseOpenTypeTableEntries(data, numTables) {
  12475. var tableEntries = [];
  12476. var p = 12;
  12477. for (var i = 0; i < numTables; i += 1) {
  12478. var tag = parse.getTag(data, p);
  12479. var checksum = parse.getULong(data, p + 4);
  12480. var offset = parse.getULong(data, p + 8);
  12481. var length = parse.getULong(data, p + 12);
  12482. tableEntries.push({tag: tag, checksum: checksum, offset: offset, length: length, compression: false});
  12483. p += 16;
  12484. }
  12485. return tableEntries;
  12486. }
  12487. /**
  12488. * Parses WOFF table entries.
  12489. * @param {DataView}
  12490. * @param {Number}
  12491. * @return {Object[]}
  12492. */
  12493. function parseWOFFTableEntries(data, numTables) {
  12494. var tableEntries = [];
  12495. var p = 44; // offset to the first table directory entry.
  12496. for (var i = 0; i < numTables; i += 1) {
  12497. var tag = parse.getTag(data, p);
  12498. var offset = parse.getULong(data, p + 4);
  12499. var compLength = parse.getULong(data, p + 8);
  12500. var origLength = parse.getULong(data, p + 12);
  12501. var compression = (void 0);
  12502. if (compLength < origLength) {
  12503. compression = 'WOFF';
  12504. } else {
  12505. compression = false;
  12506. }
  12507. tableEntries.push({tag: tag, offset: offset, compression: compression,
  12508. compressedLength: compLength, length: origLength});
  12509. p += 20;
  12510. }
  12511. return tableEntries;
  12512. }
  12513. /**
  12514. * @typedef TableData
  12515. * @type Object
  12516. * @property {DataView} data - The DataView
  12517. * @property {number} offset - The data offset.
  12518. */
  12519. /**
  12520. * @param {DataView}
  12521. * @param {Object}
  12522. * @return {TableData}
  12523. */
  12524. function uncompressTable(data, tableEntry) {
  12525. if (tableEntry.compression === 'WOFF') {
  12526. var inBuffer = new Uint8Array(data.buffer, tableEntry.offset + 2, tableEntry.compressedLength - 2);
  12527. var outBuffer = new Uint8Array(tableEntry.length);
  12528. tinyInflate(inBuffer, outBuffer);
  12529. if (outBuffer.byteLength !== tableEntry.length) {
  12530. throw new Error('Decompression error: ' + tableEntry.tag + ' decompressed length doesn\'t match recorded length');
  12531. }
  12532. var view = new DataView(outBuffer.buffer, 0);
  12533. return {data: view, offset: 0};
  12534. } else {
  12535. return {data: data, offset: tableEntry.offset};
  12536. }
  12537. }
  12538. // Public API ///////////////////////////////////////////////////////////
  12539. /**
  12540. * Parse the OpenType file data (as an ArrayBuffer) and return a Font object.
  12541. * Throws an error if the font could not be parsed.
  12542. * @param {ArrayBuffer}
  12543. * @param {Object} opt - options for parsing
  12544. * @return {opentype.Font}
  12545. */
  12546. function parseBuffer(buffer, opt) {
  12547. opt = (opt === undefined || opt === null) ? {} : opt;
  12548. var indexToLocFormat;
  12549. var ltagTable;
  12550. // Since the constructor can also be called to create new fonts from scratch, we indicate this
  12551. // should be an empty font that we'll fill with our own data.
  12552. var font = new Font({empty: true});
  12553. // OpenType fonts use big endian byte ordering.
  12554. // We can't rely on typed array view types, because they operate with the endianness of the host computer.
  12555. // Instead we use DataViews where we can specify endianness.
  12556. var data = new DataView(buffer, 0);
  12557. var numTables;
  12558. var tableEntries = [];
  12559. var signature = parse.getTag(data, 0);
  12560. if (signature === String.fromCharCode(0, 1, 0, 0) || signature === 'true' || signature === 'typ1') {
  12561. font.outlinesFormat = 'truetype';
  12562. numTables = parse.getUShort(data, 4);
  12563. tableEntries = parseOpenTypeTableEntries(data, numTables);
  12564. } else if (signature === 'OTTO') {
  12565. font.outlinesFormat = 'cff';
  12566. numTables = parse.getUShort(data, 4);
  12567. tableEntries = parseOpenTypeTableEntries(data, numTables);
  12568. } else if (signature === 'wOFF') {
  12569. var flavor = parse.getTag(data, 4);
  12570. if (flavor === String.fromCharCode(0, 1, 0, 0)) {
  12571. font.outlinesFormat = 'truetype';
  12572. } else if (flavor === 'OTTO') {
  12573. font.outlinesFormat = 'cff';
  12574. } else {
  12575. throw new Error('Unsupported OpenType flavor ' + signature);
  12576. }
  12577. numTables = parse.getUShort(data, 12);
  12578. tableEntries = parseWOFFTableEntries(data, numTables);
  12579. } else {
  12580. throw new Error('Unsupported OpenType signature ' + signature);
  12581. }
  12582. var cffTableEntry;
  12583. var fvarTableEntry;
  12584. var glyfTableEntry;
  12585. var gdefTableEntry;
  12586. var gposTableEntry;
  12587. var gsubTableEntry;
  12588. var hmtxTableEntry;
  12589. var kernTableEntry;
  12590. var locaTableEntry;
  12591. var nameTableEntry;
  12592. var metaTableEntry;
  12593. var p;
  12594. for (var i = 0; i < numTables; i += 1) {
  12595. var tableEntry = tableEntries[i];
  12596. var table = (void 0);
  12597. switch (tableEntry.tag) {
  12598. case 'cmap':
  12599. table = uncompressTable(data, tableEntry);
  12600. font.tables.cmap = cmap.parse(table.data, table.offset);
  12601. font.encoding = new CmapEncoding(font.tables.cmap);
  12602. break;
  12603. case 'cvt ' :
  12604. table = uncompressTable(data, tableEntry);
  12605. p = new parse.Parser(table.data, table.offset);
  12606. font.tables.cvt = p.parseShortList(tableEntry.length / 2);
  12607. break;
  12608. case 'fvar':
  12609. fvarTableEntry = tableEntry;
  12610. break;
  12611. case 'fpgm' :
  12612. table = uncompressTable(data, tableEntry);
  12613. p = new parse.Parser(table.data, table.offset);
  12614. font.tables.fpgm = p.parseByteList(tableEntry.length);
  12615. break;
  12616. case 'head':
  12617. table = uncompressTable(data, tableEntry);
  12618. font.tables.head = head.parse(table.data, table.offset);
  12619. font.unitsPerEm = font.tables.head.unitsPerEm;
  12620. indexToLocFormat = font.tables.head.indexToLocFormat;
  12621. break;
  12622. case 'hhea':
  12623. table = uncompressTable(data, tableEntry);
  12624. font.tables.hhea = hhea.parse(table.data, table.offset);
  12625. font.ascender = font.tables.hhea.ascender;
  12626. font.descender = font.tables.hhea.descender;
  12627. font.numberOfHMetrics = font.tables.hhea.numberOfHMetrics;
  12628. break;
  12629. case 'hmtx':
  12630. hmtxTableEntry = tableEntry;
  12631. break;
  12632. case 'ltag':
  12633. table = uncompressTable(data, tableEntry);
  12634. ltagTable = ltag.parse(table.data, table.offset);
  12635. break;
  12636. case 'COLR':
  12637. table = uncompressTable(data, tableEntry);
  12638. font.tables.colr = colr.parse(table.data, table.offset);
  12639. break;
  12640. case 'CPAL':
  12641. table = uncompressTable(data, tableEntry);
  12642. font.tables.cpal = cpal.parse(table.data, table.offset);
  12643. break;
  12644. case 'maxp':
  12645. table = uncompressTable(data, tableEntry);
  12646. font.tables.maxp = maxp.parse(table.data, table.offset);
  12647. font.numGlyphs = font.tables.maxp.numGlyphs;
  12648. break;
  12649. case 'name':
  12650. nameTableEntry = tableEntry;
  12651. break;
  12652. case 'OS/2':
  12653. table = uncompressTable(data, tableEntry);
  12654. font.tables.os2 = os2.parse(table.data, table.offset);
  12655. break;
  12656. case 'post':
  12657. table = uncompressTable(data, tableEntry);
  12658. font.tables.post = post.parse(table.data, table.offset);
  12659. font.glyphNames = new GlyphNames(font.tables.post);
  12660. break;
  12661. case 'prep' :
  12662. table = uncompressTable(data, tableEntry);
  12663. p = new parse.Parser(table.data, table.offset);
  12664. font.tables.prep = p.parseByteList(tableEntry.length);
  12665. break;
  12666. case 'glyf':
  12667. glyfTableEntry = tableEntry;
  12668. break;
  12669. case 'loca':
  12670. locaTableEntry = tableEntry;
  12671. break;
  12672. case 'CFF ':
  12673. cffTableEntry = tableEntry;
  12674. break;
  12675. case 'kern':
  12676. kernTableEntry = tableEntry;
  12677. break;
  12678. case 'GDEF':
  12679. gdefTableEntry = tableEntry;
  12680. break;
  12681. case 'GPOS':
  12682. gposTableEntry = tableEntry;
  12683. break;
  12684. case 'GSUB':
  12685. gsubTableEntry = tableEntry;
  12686. break;
  12687. case 'meta':
  12688. metaTableEntry = tableEntry;
  12689. break;
  12690. }
  12691. }
  12692. var nameTable = uncompressTable(data, nameTableEntry);
  12693. font.tables.name = _name.parse(nameTable.data, nameTable.offset, ltagTable);
  12694. font.names = font.tables.name;
  12695. if (glyfTableEntry && locaTableEntry) {
  12696. var shortVersion = indexToLocFormat === 0;
  12697. var locaTable = uncompressTable(data, locaTableEntry);
  12698. var locaOffsets = loca.parse(locaTable.data, locaTable.offset, font.numGlyphs, shortVersion);
  12699. var glyfTable = uncompressTable(data, glyfTableEntry);
  12700. font.glyphs = glyf.parse(glyfTable.data, glyfTable.offset, locaOffsets, font, opt);
  12701. } else if (cffTableEntry) {
  12702. var cffTable = uncompressTable(data, cffTableEntry);
  12703. cff.parse(cffTable.data, cffTable.offset, font, opt);
  12704. } else {
  12705. throw new Error('Font doesn\'t contain TrueType or CFF outlines.');
  12706. }
  12707. var hmtxTable = uncompressTable(data, hmtxTableEntry);
  12708. hmtx.parse(font, hmtxTable.data, hmtxTable.offset, font.numberOfHMetrics, font.numGlyphs, font.glyphs, opt);
  12709. addGlyphNames(font, opt);
  12710. if (kernTableEntry) {
  12711. var kernTable = uncompressTable(data, kernTableEntry);
  12712. font.kerningPairs = kern.parse(kernTable.data, kernTable.offset);
  12713. } else {
  12714. font.kerningPairs = {};
  12715. }
  12716. if (gdefTableEntry) {
  12717. var gdefTable = uncompressTable(data, gdefTableEntry);
  12718. font.tables.gdef = gdef.parse(gdefTable.data, gdefTable.offset);
  12719. }
  12720. if (gposTableEntry) {
  12721. var gposTable = uncompressTable(data, gposTableEntry);
  12722. font.tables.gpos = gpos.parse(gposTable.data, gposTable.offset);
  12723. font.position.init();
  12724. }
  12725. if (gsubTableEntry) {
  12726. var gsubTable = uncompressTable(data, gsubTableEntry);
  12727. font.tables.gsub = gsub.parse(gsubTable.data, gsubTable.offset);
  12728. }
  12729. if (fvarTableEntry) {
  12730. var fvarTable = uncompressTable(data, fvarTableEntry);
  12731. font.tables.fvar = fvar.parse(fvarTable.data, fvarTable.offset, font.names);
  12732. }
  12733. if (metaTableEntry) {
  12734. var metaTable = uncompressTable(data, metaTableEntry);
  12735. font.tables.meta = meta.parse(metaTable.data, metaTable.offset);
  12736. font.metas = font.tables.meta;
  12737. }
  12738. return font;
  12739. }
  12740. /**
  12741. * Asynchronously load the font from a URL or a filesystem. When done, call the callback
  12742. * with two arguments `(err, font)`. The `err` will be null on success,
  12743. * the `font` is a Font object.
  12744. * We use the node.js callback convention so that
  12745. * opentype.js can integrate with frameworks like async.js.
  12746. * @alias opentype.load
  12747. * @param {string} url - The URL of the font to load.
  12748. * @param {Function} callback - The callback.
  12749. */
  12750. function load(url, callback, opt) {
  12751. opt = (opt === undefined || opt === null) ? {} : opt;
  12752. var isNode = typeof window === 'undefined';
  12753. var loadFn = isNode && !opt.isUrl ? loadFromFile : loadFromUrl;
  12754. return new Promise(function (resolve, reject) {
  12755. loadFn(url, function(err, arrayBuffer) {
  12756. if (err) {
  12757. if (callback) {
  12758. return callback(err);
  12759. } else {
  12760. reject(err);
  12761. }
  12762. }
  12763. var font;
  12764. try {
  12765. font = parseBuffer(arrayBuffer, opt);
  12766. } catch (e) {
  12767. if (callback) {
  12768. return callback(e, null);
  12769. } else {
  12770. reject(e);
  12771. }
  12772. }
  12773. if (callback) {
  12774. return callback(null, font);
  12775. } else {
  12776. resolve(font);
  12777. }
  12778. });
  12779. });
  12780. }
  12781. /**
  12782. * Synchronously load the font from a URL or file.
  12783. * When done, returns the font object or throws an error.
  12784. * @alias opentype.loadSync
  12785. * @param {string} url - The URL of the font to load.
  12786. * @param {Object} opt - opt.lowMemory
  12787. * @return {opentype.Font}
  12788. */
  12789. function loadSync(url, opt) {
  12790. var fs = require('fs');
  12791. var buffer = fs.readFileSync(url);
  12792. return parseBuffer(nodeBufferToArrayBuffer(buffer), opt);
  12793. }
  12794. var opentype = /*#__PURE__*/Object.freeze({
  12795. __proto__: null,
  12796. Font: Font,
  12797. Glyph: Glyph,
  12798. Path: Path,
  12799. BoundingBox: BoundingBox,
  12800. _parse: parse,
  12801. parse: parseBuffer,
  12802. load: load,
  12803. loadSync: loadSync
  12804. });
  12805. export default opentype;
  12806. export { BoundingBox, Font, Glyph, Path, parse as _parse, load, loadSync, parseBuffer as parse };