fonts.js 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460
  1. /* Copyright 2017 Mozilla Foundation
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. 'use strict';
  16. var sharedUtil = require('../shared/util.js');
  17. var corePrimitives = require('./primitives.js');
  18. var coreStream = require('./stream.js');
  19. var coreGlyphList = require('./glyphlist.js');
  20. var coreFontRenderer = require('./font_renderer.js');
  21. var coreEncodings = require('./encodings.js');
  22. var coreStandardFonts = require('./standard_fonts.js');
  23. var coreUnicode = require('./unicode.js');
  24. var coreType1Parser = require('./type1_parser.js');
  25. var coreCFFParser = require('./cff_parser.js');
  26. var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
  27. var FontType = sharedUtil.FontType;
  28. var assert = sharedUtil.assert;
  29. var bytesToString = sharedUtil.bytesToString;
  30. var error = sharedUtil.error;
  31. var info = sharedUtil.info;
  32. var isArray = sharedUtil.isArray;
  33. var isInt = sharedUtil.isInt;
  34. var isNum = sharedUtil.isNum;
  35. var readUint32 = sharedUtil.readUint32;
  36. var shadow = sharedUtil.shadow;
  37. var string32 = sharedUtil.string32;
  38. var warn = sharedUtil.warn;
  39. var MissingDataException = sharedUtil.MissingDataException;
  40. var isSpace = sharedUtil.isSpace;
  41. var Stream = coreStream.Stream;
  42. var getGlyphsUnicode = coreGlyphList.getGlyphsUnicode;
  43. var getDingbatsGlyphsUnicode = coreGlyphList.getDingbatsGlyphsUnicode;
  44. var FontRendererFactory = coreFontRenderer.FontRendererFactory;
  45. var StandardEncoding = coreEncodings.StandardEncoding;
  46. var MacRomanEncoding = coreEncodings.MacRomanEncoding;
  47. var SymbolSetEncoding = coreEncodings.SymbolSetEncoding;
  48. var ZapfDingbatsEncoding = coreEncodings.ZapfDingbatsEncoding;
  49. var getEncoding = coreEncodings.getEncoding;
  50. var getStdFontMap = coreStandardFonts.getStdFontMap;
  51. var getNonStdFontMap = coreStandardFonts.getNonStdFontMap;
  52. var getGlyphMapForStandardFonts = coreStandardFonts.getGlyphMapForStandardFonts;
  53. var getSupplementalGlyphMapForArialBlack = coreStandardFonts.getSupplementalGlyphMapForArialBlack;
  54. var getUnicodeRangeFor = coreUnicode.getUnicodeRangeFor;
  55. var mapSpecialUnicodeValues = coreUnicode.mapSpecialUnicodeValues;
  56. var getUnicodeForGlyph = coreUnicode.getUnicodeForGlyph;
  57. var Type1Parser = coreType1Parser.Type1Parser;
  58. var CFFStandardStrings = coreCFFParser.CFFStandardStrings;
  59. var CFFParser = coreCFFParser.CFFParser;
  60. var CFFCompiler = coreCFFParser.CFFCompiler;
  61. var CFF = coreCFFParser.CFF;
  62. var CFFHeader = coreCFFParser.CFFHeader;
  63. var CFFTopDict = coreCFFParser.CFFTopDict;
  64. var CFFPrivateDict = coreCFFParser.CFFPrivateDict;
  65. var CFFStrings = coreCFFParser.CFFStrings;
  66. var CFFIndex = coreCFFParser.CFFIndex;
  67. var CFFCharset = coreCFFParser.CFFCharset;
  68. var PRIVATE_USE_OFFSET_START = 0xE000;
  69. var PRIVATE_USE_OFFSET_END = 0xF8FF;
  70. var SKIP_PRIVATE_USE_RANGE_F000_TO_F01F = false;
  71. var PDF_GLYPH_SPACE_UNITS = 1000;
  72. var SEAC_ANALYSIS_ENABLED = false;
  73. var FontFlags = {
  74. FixedPitch: 1,
  75. Serif: 2,
  76. Symbolic: 4,
  77. Script: 8,
  78. Nonsymbolic: 32,
  79. Italic: 64,
  80. AllCap: 65536,
  81. SmallCap: 131072,
  82. ForceBold: 262144
  83. };
  84. var MacStandardGlyphOrdering = ['.notdef', '.null', 'nonmarkingreturn', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', 'Adieresis', 'Aring', 'Ccedilla', 'Eacute', 'Ntilde', 'Odieresis', 'Udieresis', 'aacute', 'agrave', 'acircumflex', 'adieresis', 'atilde', 'aring', 'ccedilla', 'eacute', 'egrave', 'ecircumflex', 'edieresis', 'iacute', 'igrave', 'icircumflex', 'idieresis', 'ntilde', 'oacute', 'ograve', 'ocircumflex', 'odieresis', 'otilde', 'uacute', 'ugrave', 'ucircumflex', 'udieresis', 'dagger', 'degree', 'cent', 'sterling', 'section', 'bullet', 'paragraph', 'germandbls', 'registered', 'copyright', 'trademark', 'acute', 'dieresis', 'notequal', 'AE', 'Oslash', 'infinity', 'plusminus', 'lessequal', 'greaterequal', 'yen', 'mu', 'partialdiff', 'summation', 'product', 'pi', 'integral', 'ordfeminine', 'ordmasculine', 'Omega', 'ae', 'oslash', 'questiondown', 'exclamdown', 'logicalnot', 'radical', 'florin', 'approxequal', 'Delta', 'guillemotleft', 'guillemotright', 'ellipsis', 'nonbreakingspace', 'Agrave', 'Atilde', 'Otilde', 'OE', 'oe', 'endash', 'emdash', 'quotedblleft', 'quotedblright', 'quoteleft', 'quoteright', 'divide', 'lozenge', 'ydieresis', 'Ydieresis', 'fraction', 'currency', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'daggerdbl', 'periodcentered', 'quotesinglbase', 'quotedblbase', 'perthousand', 'Acircumflex', 'Ecircumflex', 'Aacute', 'Edieresis', 'Egrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Oacute', 'Ocircumflex', 'apple', 'Ograve', 'Uacute', 'Ucircumflex', 'Ugrave', 'dotlessi', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron', 'Lslash', 'lslash', 'Scaron', 'scaron', 'Zcaron', 'zcaron', 'brokenbar', 'Eth', 'eth', 'Yacute', 'yacute', 'Thorn', 'thorn', 'minus', 'multiply', 'onesuperior', 'twosuperior', 'threesuperior', 'onehalf', 'onequarter', 'threequarters', 'franc', 'Gbreve', 'gbreve', 'Idotaccent', 'Scedilla', 'scedilla', 'Cacute', 'cacute', 'Ccaron', 'ccaron', 'dcroat'];
  85. function adjustWidths(properties) {
  86. if (!properties.fontMatrix) {
  87. return;
  88. }
  89. if (properties.fontMatrix[0] === FONT_IDENTITY_MATRIX[0]) {
  90. return;
  91. }
  92. var scale = 0.001 / properties.fontMatrix[0];
  93. var glyphsWidths = properties.widths;
  94. for (var glyph in glyphsWidths) {
  95. glyphsWidths[glyph] *= scale;
  96. }
  97. properties.defaultWidth *= scale;
  98. }
  99. function adjustToUnicode(properties, builtInEncoding) {
  100. if (properties.hasIncludedToUnicodeMap) {
  101. return;
  102. }
  103. if (properties.hasEncoding) {
  104. return;
  105. }
  106. if (builtInEncoding === properties.defaultEncoding) {
  107. return;
  108. }
  109. if (properties.toUnicode instanceof IdentityToUnicodeMap) {
  110. return;
  111. }
  112. var toUnicode = [],
  113. glyphsUnicodeMap = getGlyphsUnicode();
  114. for (var charCode in builtInEncoding) {
  115. var glyphName = builtInEncoding[charCode];
  116. var unicode = getUnicodeForGlyph(glyphName, glyphsUnicodeMap);
  117. if (unicode !== -1) {
  118. toUnicode[charCode] = String.fromCharCode(unicode);
  119. }
  120. }
  121. properties.toUnicode.amend(toUnicode);
  122. }
  123. function getFontType(type, subtype) {
  124. switch (type) {
  125. case 'Type1':
  126. return subtype === 'Type1C' ? FontType.TYPE1C : FontType.TYPE1;
  127. case 'CIDFontType0':
  128. return subtype === 'CIDFontType0C' ? FontType.CIDFONTTYPE0C : FontType.CIDFONTTYPE0;
  129. case 'OpenType':
  130. return FontType.OPENTYPE;
  131. case 'TrueType':
  132. return FontType.TRUETYPE;
  133. case 'CIDFontType2':
  134. return FontType.CIDFONTTYPE2;
  135. case 'MMType1':
  136. return FontType.MMTYPE1;
  137. case 'Type0':
  138. return FontType.TYPE0;
  139. default:
  140. return FontType.UNKNOWN;
  141. }
  142. }
  143. function recoverGlyphName(name, glyphsUnicodeMap) {
  144. if (glyphsUnicodeMap[name] !== undefined) {
  145. return name;
  146. }
  147. var unicode = getUnicodeForGlyph(name, glyphsUnicodeMap);
  148. if (unicode !== -1) {
  149. for (var key in glyphsUnicodeMap) {
  150. if (glyphsUnicodeMap[key] === unicode) {
  151. return key;
  152. }
  153. }
  154. }
  155. info('Unable to recover a standard glyph name for: ' + name);
  156. return name;
  157. }
  158. var Glyph = function GlyphClosure() {
  159. function Glyph(fontChar, unicode, accent, width, vmetric, operatorListId, isSpace, isInFont) {
  160. this.fontChar = fontChar;
  161. this.unicode = unicode;
  162. this.accent = accent;
  163. this.width = width;
  164. this.vmetric = vmetric;
  165. this.operatorListId = operatorListId;
  166. this.isSpace = isSpace;
  167. this.isInFont = isInFont;
  168. }
  169. Glyph.prototype.matchesForCache = function (fontChar, unicode, accent, width, vmetric, operatorListId, isSpace, isInFont) {
  170. return this.fontChar === fontChar && this.unicode === unicode && this.accent === accent && this.width === width && this.vmetric === vmetric && this.operatorListId === operatorListId && this.isSpace === isSpace && this.isInFont === isInFont;
  171. };
  172. return Glyph;
  173. }();
  174. var ToUnicodeMap = function ToUnicodeMapClosure() {
  175. function ToUnicodeMap(cmap) {
  176. this._map = cmap;
  177. }
  178. ToUnicodeMap.prototype = {
  179. get length() {
  180. return this._map.length;
  181. },
  182. forEach: function forEach(callback) {
  183. for (var charCode in this._map) {
  184. callback(charCode, this._map[charCode].charCodeAt(0));
  185. }
  186. },
  187. has: function has(i) {
  188. return this._map[i] !== undefined;
  189. },
  190. get: function get(i) {
  191. return this._map[i];
  192. },
  193. charCodeOf: function charCodeOf(v) {
  194. return this._map.indexOf(v);
  195. },
  196. amend: function amend(map) {
  197. for (var charCode in map) {
  198. this._map[charCode] = map[charCode];
  199. }
  200. }
  201. };
  202. return ToUnicodeMap;
  203. }();
  204. var IdentityToUnicodeMap = function IdentityToUnicodeMapClosure() {
  205. function IdentityToUnicodeMap(firstChar, lastChar) {
  206. this.firstChar = firstChar;
  207. this.lastChar = lastChar;
  208. }
  209. IdentityToUnicodeMap.prototype = {
  210. get length() {
  211. return this.lastChar + 1 - this.firstChar;
  212. },
  213. forEach: function forEach(callback) {
  214. for (var i = this.firstChar, ii = this.lastChar; i <= ii; i++) {
  215. callback(i, i);
  216. }
  217. },
  218. has: function has(i) {
  219. return this.firstChar <= i && i <= this.lastChar;
  220. },
  221. get: function get(i) {
  222. if (this.firstChar <= i && i <= this.lastChar) {
  223. return String.fromCharCode(i);
  224. }
  225. return undefined;
  226. },
  227. charCodeOf: function charCodeOf(v) {
  228. return isInt(v) && v >= this.firstChar && v <= this.lastChar ? v : -1;
  229. },
  230. amend: function amend(map) {
  231. error('Should not call amend()');
  232. }
  233. };
  234. return IdentityToUnicodeMap;
  235. }();
  236. var OpenTypeFileBuilder = function OpenTypeFileBuilderClosure() {
  237. function writeInt16(dest, offset, num) {
  238. dest[offset] = num >> 8 & 0xFF;
  239. dest[offset + 1] = num & 0xFF;
  240. }
  241. function writeInt32(dest, offset, num) {
  242. dest[offset] = num >> 24 & 0xFF;
  243. dest[offset + 1] = num >> 16 & 0xFF;
  244. dest[offset + 2] = num >> 8 & 0xFF;
  245. dest[offset + 3] = num & 0xFF;
  246. }
  247. function writeData(dest, offset, data) {
  248. var i, ii;
  249. if (data instanceof Uint8Array) {
  250. dest.set(data, offset);
  251. } else if (typeof data === 'string') {
  252. for (i = 0, ii = data.length; i < ii; i++) {
  253. dest[offset++] = data.charCodeAt(i) & 0xFF;
  254. }
  255. } else {
  256. for (i = 0, ii = data.length; i < ii; i++) {
  257. dest[offset++] = data[i] & 0xFF;
  258. }
  259. }
  260. }
  261. function OpenTypeFileBuilder(sfnt) {
  262. this.sfnt = sfnt;
  263. this.tables = Object.create(null);
  264. }
  265. OpenTypeFileBuilder.getSearchParams = function OpenTypeFileBuilder_getSearchParams(entriesCount, entrySize) {
  266. var maxPower2 = 1,
  267. log2 = 0;
  268. while ((maxPower2 ^ entriesCount) > maxPower2) {
  269. maxPower2 <<= 1;
  270. log2++;
  271. }
  272. var searchRange = maxPower2 * entrySize;
  273. return {
  274. range: searchRange,
  275. entry: log2,
  276. rangeShift: entrySize * entriesCount - searchRange
  277. };
  278. };
  279. var OTF_HEADER_SIZE = 12;
  280. var OTF_TABLE_ENTRY_SIZE = 16;
  281. OpenTypeFileBuilder.prototype = {
  282. toArray: function OpenTypeFileBuilder_toArray() {
  283. var sfnt = this.sfnt;
  284. var tables = this.tables;
  285. var tablesNames = Object.keys(tables);
  286. tablesNames.sort();
  287. var numTables = tablesNames.length;
  288. var i, j, jj, table, tableName;
  289. var offset = OTF_HEADER_SIZE + numTables * OTF_TABLE_ENTRY_SIZE;
  290. var tableOffsets = [offset];
  291. for (i = 0; i < numTables; i++) {
  292. table = tables[tablesNames[i]];
  293. var paddedLength = (table.length + 3 & ~3) >>> 0;
  294. offset += paddedLength;
  295. tableOffsets.push(offset);
  296. }
  297. var file = new Uint8Array(offset);
  298. for (i = 0; i < numTables; i++) {
  299. table = tables[tablesNames[i]];
  300. writeData(file, tableOffsets[i], table);
  301. }
  302. if (sfnt === 'true') {
  303. sfnt = string32(0x00010000);
  304. }
  305. file[0] = sfnt.charCodeAt(0) & 0xFF;
  306. file[1] = sfnt.charCodeAt(1) & 0xFF;
  307. file[2] = sfnt.charCodeAt(2) & 0xFF;
  308. file[3] = sfnt.charCodeAt(3) & 0xFF;
  309. writeInt16(file, 4, numTables);
  310. var searchParams = OpenTypeFileBuilder.getSearchParams(numTables, 16);
  311. writeInt16(file, 6, searchParams.range);
  312. writeInt16(file, 8, searchParams.entry);
  313. writeInt16(file, 10, searchParams.rangeShift);
  314. offset = OTF_HEADER_SIZE;
  315. for (i = 0; i < numTables; i++) {
  316. tableName = tablesNames[i];
  317. file[offset] = tableName.charCodeAt(0) & 0xFF;
  318. file[offset + 1] = tableName.charCodeAt(1) & 0xFF;
  319. file[offset + 2] = tableName.charCodeAt(2) & 0xFF;
  320. file[offset + 3] = tableName.charCodeAt(3) & 0xFF;
  321. var checksum = 0;
  322. for (j = tableOffsets[i], jj = tableOffsets[i + 1]; j < jj; j += 4) {
  323. var quad = readUint32(file, j);
  324. checksum = checksum + quad >>> 0;
  325. }
  326. writeInt32(file, offset + 4, checksum);
  327. writeInt32(file, offset + 8, tableOffsets[i]);
  328. writeInt32(file, offset + 12, tables[tableName].length);
  329. offset += OTF_TABLE_ENTRY_SIZE;
  330. }
  331. return file;
  332. },
  333. addTable: function OpenTypeFileBuilder_addTable(tag, data) {
  334. if (tag in this.tables) {
  335. throw new Error('Table ' + tag + ' already exists');
  336. }
  337. this.tables[tag] = data;
  338. }
  339. };
  340. return OpenTypeFileBuilder;
  341. }();
  342. var ProblematicCharRanges = new Int32Array([0x0000, 0x0020, 0x007F, 0x00A1, 0x00AD, 0x00AE, 0x0600, 0x0780, 0x08A0, 0x10A0, 0x1780, 0x1800, 0x1C00, 0x1C50, 0x2000, 0x2010, 0x2011, 0x2012, 0x2028, 0x2030, 0x205F, 0x2070, 0x25CC, 0x25CD, 0x3000, 0x3001, 0xAA60, 0xAA80, 0xFFF0, 0x10000]);
  343. var Font = function FontClosure() {
  344. function Font(name, file, properties) {
  345. var charCode, glyphName, unicode;
  346. this.name = name;
  347. this.loadedName = properties.loadedName;
  348. this.isType3Font = properties.isType3Font;
  349. this.sizes = [];
  350. this.missingFile = false;
  351. this.glyphCache = Object.create(null);
  352. this.isSerifFont = !!(properties.flags & FontFlags.Serif);
  353. this.isSymbolicFont = !!(properties.flags & FontFlags.Symbolic);
  354. this.isMonospace = !!(properties.flags & FontFlags.FixedPitch);
  355. var type = properties.type;
  356. var subtype = properties.subtype;
  357. this.type = type;
  358. this.fallbackName = this.isMonospace ? 'monospace' : this.isSerifFont ? 'serif' : 'sans-serif';
  359. this.differences = properties.differences;
  360. this.widths = properties.widths;
  361. this.defaultWidth = properties.defaultWidth;
  362. this.composite = properties.composite;
  363. this.wideChars = properties.wideChars;
  364. this.cMap = properties.cMap;
  365. this.ascent = properties.ascent / PDF_GLYPH_SPACE_UNITS;
  366. this.descent = properties.descent / PDF_GLYPH_SPACE_UNITS;
  367. this.fontMatrix = properties.fontMatrix;
  368. this.bbox = properties.bbox;
  369. this.toUnicode = properties.toUnicode;
  370. this.toFontChar = [];
  371. if (properties.type === 'Type3') {
  372. for (charCode = 0; charCode < 256; charCode++) {
  373. this.toFontChar[charCode] = this.differences[charCode] || properties.defaultEncoding[charCode];
  374. }
  375. this.fontType = FontType.TYPE3;
  376. return;
  377. }
  378. this.cidEncoding = properties.cidEncoding;
  379. this.vertical = properties.vertical;
  380. if (this.vertical) {
  381. this.vmetrics = properties.vmetrics;
  382. this.defaultVMetrics = properties.defaultVMetrics;
  383. }
  384. var glyphsUnicodeMap;
  385. if (!file || file.isEmpty) {
  386. if (file) {
  387. warn('Font file is empty in "' + name + '" (' + this.loadedName + ')');
  388. }
  389. this.missingFile = true;
  390. var fontName = name.replace(/[,_]/g, '-');
  391. var stdFontMap = getStdFontMap(),
  392. nonStdFontMap = getNonStdFontMap();
  393. var isStandardFont = !!stdFontMap[fontName] || !!(nonStdFontMap[fontName] && stdFontMap[nonStdFontMap[fontName]]);
  394. fontName = stdFontMap[fontName] || nonStdFontMap[fontName] || fontName;
  395. this.bold = fontName.search(/bold/gi) !== -1;
  396. this.italic = fontName.search(/oblique/gi) !== -1 || fontName.search(/italic/gi) !== -1;
  397. this.black = name.search(/Black/g) !== -1;
  398. this.remeasure = Object.keys(this.widths).length > 0;
  399. if (isStandardFont && type === 'CIDFontType2' && properties.cidEncoding.indexOf('Identity-') === 0) {
  400. var GlyphMapForStandardFonts = getGlyphMapForStandardFonts();
  401. var map = [];
  402. for (charCode in GlyphMapForStandardFonts) {
  403. map[+charCode] = GlyphMapForStandardFonts[charCode];
  404. }
  405. if (/Arial-?Black/i.test(name)) {
  406. var SupplementalGlyphMapForArialBlack = getSupplementalGlyphMapForArialBlack();
  407. for (charCode in SupplementalGlyphMapForArialBlack) {
  408. map[+charCode] = SupplementalGlyphMapForArialBlack[charCode];
  409. }
  410. }
  411. var isIdentityUnicode = this.toUnicode instanceof IdentityToUnicodeMap;
  412. if (!isIdentityUnicode) {
  413. this.toUnicode.forEach(function (charCode, unicodeCharCode) {
  414. map[+charCode] = unicodeCharCode;
  415. });
  416. }
  417. this.toFontChar = map;
  418. this.toUnicode = new ToUnicodeMap(map);
  419. } else if (/Symbol/i.test(fontName)) {
  420. this.toFontChar = buildToFontChar(SymbolSetEncoding, getGlyphsUnicode(), properties.differences);
  421. } else if (/Dingbats/i.test(fontName)) {
  422. if (/Wingdings/i.test(name)) {
  423. warn('Non-embedded Wingdings font, falling back to ZapfDingbats.');
  424. }
  425. this.toFontChar = buildToFontChar(ZapfDingbatsEncoding, getDingbatsGlyphsUnicode(), properties.differences);
  426. } else if (isStandardFont) {
  427. this.toFontChar = buildToFontChar(properties.defaultEncoding, getGlyphsUnicode(), properties.differences);
  428. } else {
  429. glyphsUnicodeMap = getGlyphsUnicode();
  430. this.toUnicode.forEach(function (charCode, unicodeCharCode) {
  431. if (!this.composite) {
  432. glyphName = properties.differences[charCode] || properties.defaultEncoding[charCode];
  433. unicode = getUnicodeForGlyph(glyphName, glyphsUnicodeMap);
  434. if (unicode !== -1) {
  435. unicodeCharCode = unicode;
  436. }
  437. }
  438. this.toFontChar[charCode] = unicodeCharCode;
  439. }.bind(this));
  440. }
  441. this.loadedName = fontName.split('-')[0];
  442. this.loading = false;
  443. this.fontType = getFontType(type, subtype);
  444. return;
  445. }
  446. if (subtype === 'Type1C') {
  447. if (type !== 'Type1' && type !== 'MMType1') {
  448. if (isTrueTypeFile(file)) {
  449. subtype = 'TrueType';
  450. } else {
  451. type = 'Type1';
  452. }
  453. } else if (isOpenTypeFile(file)) {
  454. type = subtype = 'OpenType';
  455. }
  456. }
  457. if (subtype === 'CIDFontType0C' && type !== 'CIDFontType0') {
  458. type = 'CIDFontType0';
  459. }
  460. if (subtype === 'OpenType') {
  461. type = 'OpenType';
  462. }
  463. if (type === 'CIDFontType0') {
  464. if (isType1File(file)) {
  465. subtype = 'CIDFontType0';
  466. } else if (isOpenTypeFile(file)) {
  467. type = subtype = 'OpenType';
  468. } else {
  469. subtype = 'CIDFontType0C';
  470. }
  471. }
  472. var data;
  473. switch (type) {
  474. case 'MMType1':
  475. info('MMType1 font (' + name + '), falling back to Type1.');
  476. case 'Type1':
  477. case 'CIDFontType0':
  478. this.mimetype = 'font/opentype';
  479. var cff = subtype === 'Type1C' || subtype === 'CIDFontType0C' ? new CFFFont(file, properties) : new Type1Font(name, file, properties);
  480. adjustWidths(properties);
  481. data = this.convert(name, cff, properties);
  482. break;
  483. case 'OpenType':
  484. case 'TrueType':
  485. case 'CIDFontType2':
  486. this.mimetype = 'font/opentype';
  487. data = this.checkAndRepair(name, file, properties);
  488. if (this.isOpenType) {
  489. adjustWidths(properties);
  490. type = 'OpenType';
  491. }
  492. break;
  493. default:
  494. error('Font ' + type + ' is not supported');
  495. break;
  496. }
  497. this.data = data;
  498. this.fontType = getFontType(type, subtype);
  499. this.fontMatrix = properties.fontMatrix;
  500. this.widths = properties.widths;
  501. this.defaultWidth = properties.defaultWidth;
  502. this.toUnicode = properties.toUnicode;
  503. this.encoding = properties.baseEncoding;
  504. this.seacMap = properties.seacMap;
  505. this.loading = true;
  506. }
  507. Font.getFontID = function () {
  508. var ID = 1;
  509. return function Font_getFontID() {
  510. return String(ID++);
  511. };
  512. }();
  513. function int16(b0, b1) {
  514. return (b0 << 8) + b1;
  515. }
  516. function signedInt16(b0, b1) {
  517. var value = (b0 << 8) + b1;
  518. return value & 1 << 15 ? value - 0x10000 : value;
  519. }
  520. function int32(b0, b1, b2, b3) {
  521. return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;
  522. }
  523. function string16(value) {
  524. return String.fromCharCode(value >> 8 & 0xff, value & 0xff);
  525. }
  526. function safeString16(value) {
  527. value = value > 0x7FFF ? 0x7FFF : value < -0x8000 ? -0x8000 : value;
  528. return String.fromCharCode(value >> 8 & 0xff, value & 0xff);
  529. }
  530. function isTrueTypeFile(file) {
  531. var header = file.peekBytes(4);
  532. return readUint32(header, 0) === 0x00010000;
  533. }
  534. function isOpenTypeFile(file) {
  535. var header = file.peekBytes(4);
  536. return bytesToString(header) === 'OTTO';
  537. }
  538. function isType1File(file) {
  539. var header = file.peekBytes(2);
  540. if (header[0] === 0x25 && header[1] === 0x21) {
  541. return true;
  542. }
  543. if (header[0] === 0x80 && header[1] === 0x01) {
  544. return true;
  545. }
  546. return false;
  547. }
  548. function buildToFontChar(encoding, glyphsUnicodeMap, differences) {
  549. var toFontChar = [],
  550. unicode;
  551. for (var i = 0, ii = encoding.length; i < ii; i++) {
  552. unicode = getUnicodeForGlyph(encoding[i], glyphsUnicodeMap);
  553. if (unicode !== -1) {
  554. toFontChar[i] = unicode;
  555. }
  556. }
  557. for (var charCode in differences) {
  558. unicode = getUnicodeForGlyph(differences[charCode], glyphsUnicodeMap);
  559. if (unicode !== -1) {
  560. toFontChar[+charCode] = unicode;
  561. }
  562. }
  563. return toFontChar;
  564. }
  565. function isProblematicUnicodeLocation(code) {
  566. var i = 0,
  567. j = ProblematicCharRanges.length - 1;
  568. while (i < j) {
  569. var c = i + j + 1 >> 1;
  570. if (code < ProblematicCharRanges[c]) {
  571. j = c - 1;
  572. } else {
  573. i = c;
  574. }
  575. }
  576. return !(i & 1);
  577. }
  578. function adjustMapping(charCodeToGlyphId, properties) {
  579. var toUnicode = properties.toUnicode;
  580. var isSymbolic = !!(properties.flags & FontFlags.Symbolic);
  581. var isIdentityUnicode = properties.toUnicode instanceof IdentityToUnicodeMap;
  582. var newMap = Object.create(null);
  583. var toFontChar = [];
  584. var usedFontCharCodes = [];
  585. var nextAvailableFontCharCode = PRIVATE_USE_OFFSET_START;
  586. for (var originalCharCode in charCodeToGlyphId) {
  587. originalCharCode |= 0;
  588. var glyphId = charCodeToGlyphId[originalCharCode];
  589. var fontCharCode = originalCharCode;
  590. var hasUnicodeValue = false;
  591. if (!isIdentityUnicode && toUnicode.has(originalCharCode)) {
  592. hasUnicodeValue = true;
  593. var unicode = toUnicode.get(fontCharCode);
  594. if (unicode.length === 1) {
  595. fontCharCode = unicode.charCodeAt(0);
  596. }
  597. }
  598. if ((usedFontCharCodes[fontCharCode] !== undefined || isProblematicUnicodeLocation(fontCharCode) || isSymbolic && !hasUnicodeValue) && nextAvailableFontCharCode <= PRIVATE_USE_OFFSET_END) {
  599. do {
  600. fontCharCode = nextAvailableFontCharCode++;
  601. if (SKIP_PRIVATE_USE_RANGE_F000_TO_F01F && fontCharCode === 0xF000) {
  602. fontCharCode = 0xF020;
  603. nextAvailableFontCharCode = fontCharCode + 1;
  604. }
  605. } while (usedFontCharCodes[fontCharCode] !== undefined && nextAvailableFontCharCode <= PRIVATE_USE_OFFSET_END);
  606. }
  607. newMap[fontCharCode] = glyphId;
  608. toFontChar[originalCharCode] = fontCharCode;
  609. usedFontCharCodes[fontCharCode] = true;
  610. }
  611. return {
  612. toFontChar: toFontChar,
  613. charCodeToGlyphId: newMap,
  614. nextAvailableFontCharCode: nextAvailableFontCharCode
  615. };
  616. }
  617. function getRanges(glyphs, numGlyphs) {
  618. var codes = [];
  619. for (var charCode in glyphs) {
  620. if (glyphs[charCode] >= numGlyphs) {
  621. continue;
  622. }
  623. codes.push({
  624. fontCharCode: charCode | 0,
  625. glyphId: glyphs[charCode]
  626. });
  627. }
  628. codes.sort(function fontGetRangesSort(a, b) {
  629. return a.fontCharCode - b.fontCharCode;
  630. });
  631. var ranges = [];
  632. var length = codes.length;
  633. for (var n = 0; n < length;) {
  634. var start = codes[n].fontCharCode;
  635. var codeIndices = [codes[n].glyphId];
  636. ++n;
  637. var end = start;
  638. while (n < length && end + 1 === codes[n].fontCharCode) {
  639. codeIndices.push(codes[n].glyphId);
  640. ++end;
  641. ++n;
  642. if (end === 0xFFFF) {
  643. break;
  644. }
  645. }
  646. ranges.push([start, end, codeIndices]);
  647. }
  648. return ranges;
  649. }
  650. function createCmapTable(glyphs, numGlyphs) {
  651. var ranges = getRanges(glyphs, numGlyphs);
  652. var numTables = ranges[ranges.length - 1][1] > 0xFFFF ? 2 : 1;
  653. var cmap = '\x00\x00' + string16(numTables) + '\x00\x03' + '\x00\x01' + string32(4 + numTables * 8);
  654. var i, ii, j, jj;
  655. for (i = ranges.length - 1; i >= 0; --i) {
  656. if (ranges[i][0] <= 0xFFFF) {
  657. break;
  658. }
  659. }
  660. var bmpLength = i + 1;
  661. if (ranges[i][0] < 0xFFFF && ranges[i][1] === 0xFFFF) {
  662. ranges[i][1] = 0xFFFE;
  663. }
  664. var trailingRangesCount = ranges[i][1] < 0xFFFF ? 1 : 0;
  665. var segCount = bmpLength + trailingRangesCount;
  666. var searchParams = OpenTypeFileBuilder.getSearchParams(segCount, 2);
  667. var startCount = '';
  668. var endCount = '';
  669. var idDeltas = '';
  670. var idRangeOffsets = '';
  671. var glyphsIds = '';
  672. var bias = 0;
  673. var range, start, end, codes;
  674. for (i = 0, ii = bmpLength; i < ii; i++) {
  675. range = ranges[i];
  676. start = range[0];
  677. end = range[1];
  678. startCount += string16(start);
  679. endCount += string16(end);
  680. codes = range[2];
  681. var contiguous = true;
  682. for (j = 1, jj = codes.length; j < jj; ++j) {
  683. if (codes[j] !== codes[j - 1] + 1) {
  684. contiguous = false;
  685. break;
  686. }
  687. }
  688. if (!contiguous) {
  689. var offset = (segCount - i) * 2 + bias * 2;
  690. bias += end - start + 1;
  691. idDeltas += string16(0);
  692. idRangeOffsets += string16(offset);
  693. for (j = 0, jj = codes.length; j < jj; ++j) {
  694. glyphsIds += string16(codes[j]);
  695. }
  696. } else {
  697. var startCode = codes[0];
  698. idDeltas += string16(startCode - start & 0xFFFF);
  699. idRangeOffsets += string16(0);
  700. }
  701. }
  702. if (trailingRangesCount > 0) {
  703. endCount += '\xFF\xFF';
  704. startCount += '\xFF\xFF';
  705. idDeltas += '\x00\x01';
  706. idRangeOffsets += '\x00\x00';
  707. }
  708. var format314 = '\x00\x00' + string16(2 * segCount) + string16(searchParams.range) + string16(searchParams.entry) + string16(searchParams.rangeShift) + endCount + '\x00\x00' + startCount + idDeltas + idRangeOffsets + glyphsIds;
  709. var format31012 = '';
  710. var header31012 = '';
  711. if (numTables > 1) {
  712. cmap += '\x00\x03' + '\x00\x0A' + string32(4 + numTables * 8 + 4 + format314.length);
  713. format31012 = '';
  714. for (i = 0, ii = ranges.length; i < ii; i++) {
  715. range = ranges[i];
  716. start = range[0];
  717. codes = range[2];
  718. var code = codes[0];
  719. for (j = 1, jj = codes.length; j < jj; ++j) {
  720. if (codes[j] !== codes[j - 1] + 1) {
  721. end = range[0] + j - 1;
  722. format31012 += string32(start) + string32(end) + string32(code);
  723. start = end + 1;
  724. code = codes[j];
  725. }
  726. }
  727. format31012 += string32(start) + string32(range[1]) + string32(code);
  728. }
  729. header31012 = '\x00\x0C' + '\x00\x00' + string32(format31012.length + 16) + '\x00\x00\x00\x00' + string32(format31012.length / 12);
  730. }
  731. return cmap + '\x00\x04' + string16(format314.length + 4) + format314 + header31012 + format31012;
  732. }
  733. function validateOS2Table(os2) {
  734. var stream = new Stream(os2.data);
  735. var version = stream.getUint16();
  736. stream.getBytes(60);
  737. var selection = stream.getUint16();
  738. if (version < 4 && selection & 0x0300) {
  739. return false;
  740. }
  741. var firstChar = stream.getUint16();
  742. var lastChar = stream.getUint16();
  743. if (firstChar > lastChar) {
  744. return false;
  745. }
  746. stream.getBytes(6);
  747. var usWinAscent = stream.getUint16();
  748. if (usWinAscent === 0) {
  749. return false;
  750. }
  751. os2.data[8] = os2.data[9] = 0;
  752. return true;
  753. }
  754. function createOS2Table(properties, charstrings, override) {
  755. override = override || {
  756. unitsPerEm: 0,
  757. yMax: 0,
  758. yMin: 0,
  759. ascent: 0,
  760. descent: 0
  761. };
  762. var ulUnicodeRange1 = 0;
  763. var ulUnicodeRange2 = 0;
  764. var ulUnicodeRange3 = 0;
  765. var ulUnicodeRange4 = 0;
  766. var firstCharIndex = null;
  767. var lastCharIndex = 0;
  768. if (charstrings) {
  769. for (var code in charstrings) {
  770. code |= 0;
  771. if (firstCharIndex > code || !firstCharIndex) {
  772. firstCharIndex = code;
  773. }
  774. if (lastCharIndex < code) {
  775. lastCharIndex = code;
  776. }
  777. var position = getUnicodeRangeFor(code);
  778. if (position < 32) {
  779. ulUnicodeRange1 |= 1 << position;
  780. } else if (position < 64) {
  781. ulUnicodeRange2 |= 1 << position - 32;
  782. } else if (position < 96) {
  783. ulUnicodeRange3 |= 1 << position - 64;
  784. } else if (position < 123) {
  785. ulUnicodeRange4 |= 1 << position - 96;
  786. } else {
  787. error('Unicode ranges Bits > 123 are reserved for internal usage');
  788. }
  789. }
  790. } else {
  791. firstCharIndex = 0;
  792. lastCharIndex = 255;
  793. }
  794. var bbox = properties.bbox || [0, 0, 0, 0];
  795. var unitsPerEm = override.unitsPerEm || 1 / (properties.fontMatrix || FONT_IDENTITY_MATRIX)[0];
  796. var scale = properties.ascentScaled ? 1.0 : unitsPerEm / PDF_GLYPH_SPACE_UNITS;
  797. var typoAscent = override.ascent || Math.round(scale * (properties.ascent || bbox[3]));
  798. var typoDescent = override.descent || Math.round(scale * (properties.descent || bbox[1]));
  799. if (typoDescent > 0 && properties.descent > 0 && bbox[1] < 0) {
  800. typoDescent = -typoDescent;
  801. }
  802. var winAscent = override.yMax || typoAscent;
  803. var winDescent = -override.yMin || -typoDescent;
  804. return '\x00\x03' + '\x02\x24' + '\x01\xF4' + '\x00\x05' + '\x00\x00' + '\x02\x8A' + '\x02\xBB' + '\x00\x00' + '\x00\x8C' + '\x02\x8A' + '\x02\xBB' + '\x00\x00' + '\x01\xDF' + '\x00\x31' + '\x01\x02' + '\x00\x00' + '\x00\x00\x06' + String.fromCharCode(properties.fixedPitch ? 0x09 : 0x00) + '\x00\x00\x00\x00\x00\x00' + string32(ulUnicodeRange1) + string32(ulUnicodeRange2) + string32(ulUnicodeRange3) + string32(ulUnicodeRange4) + '\x2A\x32\x31\x2A' + string16(properties.italicAngle ? 1 : 0) + string16(firstCharIndex || properties.firstChar) + string16(lastCharIndex || properties.lastChar) + string16(typoAscent) + string16(typoDescent) + '\x00\x64' + string16(winAscent) + string16(winDescent) + '\x00\x00\x00\x00' + '\x00\x00\x00\x00' + string16(properties.xHeight) + string16(properties.capHeight) + string16(0) + string16(firstCharIndex || properties.firstChar) + '\x00\x03';
  805. }
  806. function createPostTable(properties) {
  807. var angle = Math.floor(properties.italicAngle * Math.pow(2, 16));
  808. return '\x00\x03\x00\x00' + string32(angle) + '\x00\x00' + '\x00\x00' + string32(properties.fixedPitch) + '\x00\x00\x00\x00' + '\x00\x00\x00\x00' + '\x00\x00\x00\x00' + '\x00\x00\x00\x00';
  809. }
  810. function createNameTable(name, proto) {
  811. if (!proto) {
  812. proto = [[], []];
  813. }
  814. var strings = [proto[0][0] || 'Original licence', proto[0][1] || name, proto[0][2] || 'Unknown', proto[0][3] || 'uniqueID', proto[0][4] || name, proto[0][5] || 'Version 0.11', proto[0][6] || '', proto[0][7] || 'Unknown', proto[0][8] || 'Unknown', proto[0][9] || 'Unknown'];
  815. var stringsUnicode = [];
  816. var i, ii, j, jj, str;
  817. for (i = 0, ii = strings.length; i < ii; i++) {
  818. str = proto[1][i] || strings[i];
  819. var strBufUnicode = [];
  820. for (j = 0, jj = str.length; j < jj; j++) {
  821. strBufUnicode.push(string16(str.charCodeAt(j)));
  822. }
  823. stringsUnicode.push(strBufUnicode.join(''));
  824. }
  825. var names = [strings, stringsUnicode];
  826. var platforms = ['\x00\x01', '\x00\x03'];
  827. var encodings = ['\x00\x00', '\x00\x01'];
  828. var languages = ['\x00\x00', '\x04\x09'];
  829. var namesRecordCount = strings.length * platforms.length;
  830. var nameTable = '\x00\x00' + string16(namesRecordCount) + string16(namesRecordCount * 12 + 6);
  831. var strOffset = 0;
  832. for (i = 0, ii = platforms.length; i < ii; i++) {
  833. var strs = names[i];
  834. for (j = 0, jj = strs.length; j < jj; j++) {
  835. str = strs[j];
  836. var nameRecord = platforms[i] + encodings[i] + languages[i] + string16(j) + string16(str.length) + string16(strOffset);
  837. nameTable += nameRecord;
  838. strOffset += str.length;
  839. }
  840. }
  841. nameTable += strings.join('') + stringsUnicode.join('');
  842. return nameTable;
  843. }
  844. Font.prototype = {
  845. name: null,
  846. font: null,
  847. mimetype: null,
  848. encoding: null,
  849. get renderer() {
  850. var renderer = FontRendererFactory.create(this, SEAC_ANALYSIS_ENABLED);
  851. return shadow(this, 'renderer', renderer);
  852. },
  853. exportData: function Font_exportData() {
  854. var data = {};
  855. for (var i in this) {
  856. if (this.hasOwnProperty(i)) {
  857. data[i] = this[i];
  858. }
  859. }
  860. return data;
  861. },
  862. checkAndRepair: function Font_checkAndRepair(name, font, properties) {
  863. function readTableEntry(file) {
  864. var tag = bytesToString(file.getBytes(4));
  865. var checksum = file.getInt32() >>> 0;
  866. var offset = file.getInt32() >>> 0;
  867. var length = file.getInt32() >>> 0;
  868. var previousPosition = file.pos;
  869. file.pos = file.start ? file.start : 0;
  870. file.skip(offset);
  871. var data = file.getBytes(length);
  872. file.pos = previousPosition;
  873. if (tag === 'head') {
  874. data[8] = data[9] = data[10] = data[11] = 0;
  875. data[17] |= 0x20;
  876. }
  877. return {
  878. tag: tag,
  879. checksum: checksum,
  880. length: length,
  881. offset: offset,
  882. data: data
  883. };
  884. }
  885. function readOpenTypeHeader(ttf) {
  886. return {
  887. version: bytesToString(ttf.getBytes(4)),
  888. numTables: ttf.getUint16(),
  889. searchRange: ttf.getUint16(),
  890. entrySelector: ttf.getUint16(),
  891. rangeShift: ttf.getUint16()
  892. };
  893. }
  894. function readCmapTable(cmap, font, isSymbolicFont, hasEncoding) {
  895. if (!cmap) {
  896. warn('No cmap table available.');
  897. return {
  898. platformId: -1,
  899. encodingId: -1,
  900. mappings: [],
  901. hasShortCmap: false
  902. };
  903. }
  904. var segment;
  905. var start = (font.start ? font.start : 0) + cmap.offset;
  906. font.pos = start;
  907. font.getUint16();
  908. var numTables = font.getUint16();
  909. var potentialTable;
  910. var canBreak = false;
  911. for (var i = 0; i < numTables; i++) {
  912. var platformId = font.getUint16();
  913. var encodingId = font.getUint16();
  914. var offset = font.getInt32() >>> 0;
  915. var useTable = false;
  916. if (platformId === 0 && encodingId === 0) {
  917. useTable = true;
  918. } else if (platformId === 1 && encodingId === 0) {
  919. useTable = true;
  920. } else if (platformId === 3 && encodingId === 1 && (hasEncoding || !potentialTable)) {
  921. useTable = true;
  922. if (!isSymbolicFont) {
  923. canBreak = true;
  924. }
  925. } else if (isSymbolicFont && platformId === 3 && encodingId === 0) {
  926. useTable = true;
  927. canBreak = true;
  928. }
  929. if (useTable) {
  930. potentialTable = {
  931. platformId: platformId,
  932. encodingId: encodingId,
  933. offset: offset
  934. };
  935. }
  936. if (canBreak) {
  937. break;
  938. }
  939. }
  940. if (potentialTable) {
  941. font.pos = start + potentialTable.offset;
  942. }
  943. if (!potentialTable || font.peekByte() === -1) {
  944. warn('Could not find a preferred cmap table.');
  945. return {
  946. platformId: -1,
  947. encodingId: -1,
  948. mappings: [],
  949. hasShortCmap: false
  950. };
  951. }
  952. var format = font.getUint16();
  953. font.getUint16();
  954. font.getUint16();
  955. var hasShortCmap = false;
  956. var mappings = [];
  957. var j, glyphId;
  958. if (format === 0) {
  959. for (j = 0; j < 256; j++) {
  960. var index = font.getByte();
  961. if (!index) {
  962. continue;
  963. }
  964. mappings.push({
  965. charCode: j,
  966. glyphId: index
  967. });
  968. }
  969. hasShortCmap = true;
  970. } else if (format === 4) {
  971. var segCount = font.getUint16() >> 1;
  972. font.getBytes(6);
  973. var segIndex,
  974. segments = [];
  975. for (segIndex = 0; segIndex < segCount; segIndex++) {
  976. segments.push({ end: font.getUint16() });
  977. }
  978. font.getUint16();
  979. for (segIndex = 0; segIndex < segCount; segIndex++) {
  980. segments[segIndex].start = font.getUint16();
  981. }
  982. for (segIndex = 0; segIndex < segCount; segIndex++) {
  983. segments[segIndex].delta = font.getUint16();
  984. }
  985. var offsetsCount = 0;
  986. for (segIndex = 0; segIndex < segCount; segIndex++) {
  987. segment = segments[segIndex];
  988. var rangeOffset = font.getUint16();
  989. if (!rangeOffset) {
  990. segment.offsetIndex = -1;
  991. continue;
  992. }
  993. var offsetIndex = (rangeOffset >> 1) - (segCount - segIndex);
  994. segment.offsetIndex = offsetIndex;
  995. offsetsCount = Math.max(offsetsCount, offsetIndex + segment.end - segment.start + 1);
  996. }
  997. var offsets = [];
  998. for (j = 0; j < offsetsCount; j++) {
  999. offsets.push(font.getUint16());
  1000. }
  1001. for (segIndex = 0; segIndex < segCount; segIndex++) {
  1002. segment = segments[segIndex];
  1003. start = segment.start;
  1004. var end = segment.end;
  1005. var delta = segment.delta;
  1006. offsetIndex = segment.offsetIndex;
  1007. for (j = start; j <= end; j++) {
  1008. if (j === 0xFFFF) {
  1009. continue;
  1010. }
  1011. glyphId = offsetIndex < 0 ? j : offsets[offsetIndex + j - start];
  1012. glyphId = glyphId + delta & 0xFFFF;
  1013. mappings.push({
  1014. charCode: j,
  1015. glyphId: glyphId
  1016. });
  1017. }
  1018. }
  1019. } else if (format === 6) {
  1020. var firstCode = font.getUint16();
  1021. var entryCount = font.getUint16();
  1022. for (j = 0; j < entryCount; j++) {
  1023. glyphId = font.getUint16();
  1024. var charCode = firstCode + j;
  1025. mappings.push({
  1026. charCode: charCode,
  1027. glyphId: glyphId
  1028. });
  1029. }
  1030. } else {
  1031. warn('cmap table has unsupported format: ' + format);
  1032. return {
  1033. platformId: -1,
  1034. encodingId: -1,
  1035. mappings: [],
  1036. hasShortCmap: false
  1037. };
  1038. }
  1039. mappings.sort(function (a, b) {
  1040. return a.charCode - b.charCode;
  1041. });
  1042. for (i = 1; i < mappings.length; i++) {
  1043. if (mappings[i - 1].charCode === mappings[i].charCode) {
  1044. mappings.splice(i, 1);
  1045. i--;
  1046. }
  1047. }
  1048. return {
  1049. platformId: potentialTable.platformId,
  1050. encodingId: potentialTable.encodingId,
  1051. mappings: mappings,
  1052. hasShortCmap: hasShortCmap
  1053. };
  1054. }
  1055. function sanitizeMetrics(font, header, metrics, numGlyphs) {
  1056. if (!header) {
  1057. if (metrics) {
  1058. metrics.data = null;
  1059. }
  1060. return;
  1061. }
  1062. font.pos = (font.start ? font.start : 0) + header.offset;
  1063. font.pos += header.length - 2;
  1064. var numOfMetrics = font.getUint16();
  1065. if (numOfMetrics > numGlyphs) {
  1066. info('The numOfMetrics (' + numOfMetrics + ') should not be ' + 'greater than the numGlyphs (' + numGlyphs + ')');
  1067. numOfMetrics = numGlyphs;
  1068. header.data[34] = (numOfMetrics & 0xff00) >> 8;
  1069. header.data[35] = numOfMetrics & 0x00ff;
  1070. }
  1071. var numOfSidebearings = numGlyphs - numOfMetrics;
  1072. var numMissing = numOfSidebearings - (metrics.length - numOfMetrics * 4 >> 1);
  1073. if (numMissing > 0) {
  1074. var entries = new Uint8Array(metrics.length + numMissing * 2);
  1075. entries.set(metrics.data);
  1076. metrics.data = entries;
  1077. }
  1078. }
  1079. function sanitizeGlyph(source, sourceStart, sourceEnd, dest, destStart, hintsValid) {
  1080. if (sourceEnd - sourceStart <= 12) {
  1081. return 0;
  1082. }
  1083. var glyf = source.subarray(sourceStart, sourceEnd);
  1084. var contoursCount = glyf[0] << 8 | glyf[1];
  1085. if (contoursCount & 0x8000) {
  1086. dest.set(glyf, destStart);
  1087. return glyf.length;
  1088. }
  1089. var i,
  1090. j = 10,
  1091. flagsCount = 0;
  1092. for (i = 0; i < contoursCount; i++) {
  1093. var endPoint = glyf[j] << 8 | glyf[j + 1];
  1094. flagsCount = endPoint + 1;
  1095. j += 2;
  1096. }
  1097. var instructionsStart = j;
  1098. var instructionsLength = glyf[j] << 8 | glyf[j + 1];
  1099. j += 2 + instructionsLength;
  1100. var instructionsEnd = j;
  1101. var coordinatesLength = 0;
  1102. for (i = 0; i < flagsCount; i++) {
  1103. var flag = glyf[j++];
  1104. if (flag & 0xC0) {
  1105. glyf[j - 1] = flag & 0x3F;
  1106. }
  1107. var xyLength = (flag & 2 ? 1 : flag & 16 ? 0 : 2) + (flag & 4 ? 1 : flag & 32 ? 0 : 2);
  1108. coordinatesLength += xyLength;
  1109. if (flag & 8) {
  1110. var repeat = glyf[j++];
  1111. i += repeat;
  1112. coordinatesLength += repeat * xyLength;
  1113. }
  1114. }
  1115. if (coordinatesLength === 0) {
  1116. return 0;
  1117. }
  1118. var glyphDataLength = j + coordinatesLength;
  1119. if (glyphDataLength > glyf.length) {
  1120. return 0;
  1121. }
  1122. if (!hintsValid && instructionsLength > 0) {
  1123. dest.set(glyf.subarray(0, instructionsStart), destStart);
  1124. dest.set([0, 0], destStart + instructionsStart);
  1125. dest.set(glyf.subarray(instructionsEnd, glyphDataLength), destStart + instructionsStart + 2);
  1126. glyphDataLength -= instructionsLength;
  1127. if (glyf.length - glyphDataLength > 3) {
  1128. glyphDataLength = glyphDataLength + 3 & ~3;
  1129. }
  1130. return glyphDataLength;
  1131. }
  1132. if (glyf.length - glyphDataLength > 3) {
  1133. glyphDataLength = glyphDataLength + 3 & ~3;
  1134. dest.set(glyf.subarray(0, glyphDataLength), destStart);
  1135. return glyphDataLength;
  1136. }
  1137. dest.set(glyf, destStart);
  1138. return glyf.length;
  1139. }
  1140. function sanitizeHead(head, numGlyphs, locaLength) {
  1141. var data = head.data;
  1142. var version = int32(data[0], data[1], data[2], data[3]);
  1143. if (version >> 16 !== 1) {
  1144. info('Attempting to fix invalid version in head table: ' + version);
  1145. data[0] = 0;
  1146. data[1] = 1;
  1147. data[2] = 0;
  1148. data[3] = 0;
  1149. }
  1150. var indexToLocFormat = int16(data[50], data[51]);
  1151. if (indexToLocFormat < 0 || indexToLocFormat > 1) {
  1152. info('Attempting to fix invalid indexToLocFormat in head table: ' + indexToLocFormat);
  1153. var numGlyphsPlusOne = numGlyphs + 1;
  1154. if (locaLength === numGlyphsPlusOne << 1) {
  1155. data[50] = 0;
  1156. data[51] = 0;
  1157. } else if (locaLength === numGlyphsPlusOne << 2) {
  1158. data[50] = 0;
  1159. data[51] = 1;
  1160. } else {
  1161. warn('Could not fix indexToLocFormat: ' + indexToLocFormat);
  1162. }
  1163. }
  1164. }
  1165. function sanitizeGlyphLocations(loca, glyf, numGlyphs, isGlyphLocationsLong, hintsValid, dupFirstEntry) {
  1166. var itemSize, itemDecode, itemEncode;
  1167. if (isGlyphLocationsLong) {
  1168. itemSize = 4;
  1169. itemDecode = function fontItemDecodeLong(data, offset) {
  1170. return data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3];
  1171. };
  1172. itemEncode = function fontItemEncodeLong(data, offset, value) {
  1173. data[offset] = value >>> 24 & 0xFF;
  1174. data[offset + 1] = value >> 16 & 0xFF;
  1175. data[offset + 2] = value >> 8 & 0xFF;
  1176. data[offset + 3] = value & 0xFF;
  1177. };
  1178. } else {
  1179. itemSize = 2;
  1180. itemDecode = function fontItemDecode(data, offset) {
  1181. return data[offset] << 9 | data[offset + 1] << 1;
  1182. };
  1183. itemEncode = function fontItemEncode(data, offset, value) {
  1184. data[offset] = value >> 9 & 0xFF;
  1185. data[offset + 1] = value >> 1 & 0xFF;
  1186. };
  1187. }
  1188. var locaData = loca.data;
  1189. var locaDataSize = itemSize * (1 + numGlyphs);
  1190. if (locaData.length !== locaDataSize) {
  1191. locaData = new Uint8Array(locaDataSize);
  1192. locaData.set(loca.data.subarray(0, locaDataSize));
  1193. loca.data = locaData;
  1194. }
  1195. var oldGlyfData = glyf.data;
  1196. var oldGlyfDataLength = oldGlyfData.length;
  1197. var newGlyfData = new Uint8Array(oldGlyfDataLength);
  1198. var startOffset = itemDecode(locaData, 0);
  1199. var writeOffset = 0;
  1200. var missingGlyphData = Object.create(null);
  1201. itemEncode(locaData, 0, writeOffset);
  1202. var i, j;
  1203. for (i = 0, j = itemSize; i < numGlyphs; i++, j += itemSize) {
  1204. var endOffset = itemDecode(locaData, j);
  1205. if (endOffset > oldGlyfDataLength && (oldGlyfDataLength + 3 & ~3) === endOffset) {
  1206. endOffset = oldGlyfDataLength;
  1207. }
  1208. if (endOffset > oldGlyfDataLength) {
  1209. itemEncode(locaData, j, writeOffset);
  1210. startOffset = endOffset;
  1211. continue;
  1212. }
  1213. if (startOffset === endOffset) {
  1214. missingGlyphData[i] = true;
  1215. }
  1216. var newLength = sanitizeGlyph(oldGlyfData, startOffset, endOffset, newGlyfData, writeOffset, hintsValid);
  1217. writeOffset += newLength;
  1218. itemEncode(locaData, j, writeOffset);
  1219. startOffset = endOffset;
  1220. }
  1221. if (writeOffset === 0) {
  1222. var simpleGlyph = new Uint8Array([0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 49, 0]);
  1223. for (i = 0, j = itemSize; i < numGlyphs; i++, j += itemSize) {
  1224. itemEncode(locaData, j, simpleGlyph.length);
  1225. }
  1226. glyf.data = simpleGlyph;
  1227. return missingGlyphData;
  1228. }
  1229. if (dupFirstEntry) {
  1230. var firstEntryLength = itemDecode(locaData, itemSize);
  1231. if (newGlyfData.length > firstEntryLength + writeOffset) {
  1232. glyf.data = newGlyfData.subarray(0, firstEntryLength + writeOffset);
  1233. } else {
  1234. glyf.data = new Uint8Array(firstEntryLength + writeOffset);
  1235. glyf.data.set(newGlyfData.subarray(0, writeOffset));
  1236. }
  1237. glyf.data.set(newGlyfData.subarray(0, firstEntryLength), writeOffset);
  1238. itemEncode(loca.data, locaData.length - itemSize, writeOffset + firstEntryLength);
  1239. } else {
  1240. glyf.data = newGlyfData.subarray(0, writeOffset);
  1241. }
  1242. return missingGlyphData;
  1243. }
  1244. function readPostScriptTable(post, properties, maxpNumGlyphs) {
  1245. var start = (font.start ? font.start : 0) + post.offset;
  1246. font.pos = start;
  1247. var length = post.length,
  1248. end = start + length;
  1249. var version = font.getInt32();
  1250. font.getBytes(28);
  1251. var glyphNames;
  1252. var valid = true;
  1253. var i;
  1254. switch (version) {
  1255. case 0x00010000:
  1256. glyphNames = MacStandardGlyphOrdering;
  1257. break;
  1258. case 0x00020000:
  1259. var numGlyphs = font.getUint16();
  1260. if (numGlyphs !== maxpNumGlyphs) {
  1261. valid = false;
  1262. break;
  1263. }
  1264. var glyphNameIndexes = [];
  1265. for (i = 0; i < numGlyphs; ++i) {
  1266. var index = font.getUint16();
  1267. if (index >= 32768) {
  1268. valid = false;
  1269. break;
  1270. }
  1271. glyphNameIndexes.push(index);
  1272. }
  1273. if (!valid) {
  1274. break;
  1275. }
  1276. var customNames = [];
  1277. var strBuf = [];
  1278. while (font.pos < end) {
  1279. var stringLength = font.getByte();
  1280. strBuf.length = stringLength;
  1281. for (i = 0; i < stringLength; ++i) {
  1282. strBuf[i] = String.fromCharCode(font.getByte());
  1283. }
  1284. customNames.push(strBuf.join(''));
  1285. }
  1286. glyphNames = [];
  1287. for (i = 0; i < numGlyphs; ++i) {
  1288. var j = glyphNameIndexes[i];
  1289. if (j < 258) {
  1290. glyphNames.push(MacStandardGlyphOrdering[j]);
  1291. continue;
  1292. }
  1293. glyphNames.push(customNames[j - 258]);
  1294. }
  1295. break;
  1296. case 0x00030000:
  1297. break;
  1298. default:
  1299. warn('Unknown/unsupported post table version ' + version);
  1300. valid = false;
  1301. if (properties.defaultEncoding) {
  1302. glyphNames = properties.defaultEncoding;
  1303. }
  1304. break;
  1305. }
  1306. properties.glyphNames = glyphNames;
  1307. return valid;
  1308. }
  1309. function readNameTable(nameTable) {
  1310. var start = (font.start ? font.start : 0) + nameTable.offset;
  1311. font.pos = start;
  1312. var names = [[], []];
  1313. var length = nameTable.length,
  1314. end = start + length;
  1315. var format = font.getUint16();
  1316. var FORMAT_0_HEADER_LENGTH = 6;
  1317. if (format !== 0 || length < FORMAT_0_HEADER_LENGTH) {
  1318. return names;
  1319. }
  1320. var numRecords = font.getUint16();
  1321. var stringsStart = font.getUint16();
  1322. var records = [];
  1323. var NAME_RECORD_LENGTH = 12;
  1324. var i, ii;
  1325. for (i = 0; i < numRecords && font.pos + NAME_RECORD_LENGTH <= end; i++) {
  1326. var r = {
  1327. platform: font.getUint16(),
  1328. encoding: font.getUint16(),
  1329. language: font.getUint16(),
  1330. name: font.getUint16(),
  1331. length: font.getUint16(),
  1332. offset: font.getUint16()
  1333. };
  1334. if (r.platform === 1 && r.encoding === 0 && r.language === 0 || r.platform === 3 && r.encoding === 1 && r.language === 0x409) {
  1335. records.push(r);
  1336. }
  1337. }
  1338. for (i = 0, ii = records.length; i < ii; i++) {
  1339. var record = records[i];
  1340. if (record.length <= 0) {
  1341. continue;
  1342. }
  1343. var pos = start + stringsStart + record.offset;
  1344. if (pos + record.length > end) {
  1345. continue;
  1346. }
  1347. font.pos = pos;
  1348. var nameIndex = record.name;
  1349. if (record.encoding) {
  1350. var str = '';
  1351. for (var j = 0, jj = record.length; j < jj; j += 2) {
  1352. str += String.fromCharCode(font.getUint16());
  1353. }
  1354. names[1][nameIndex] = str;
  1355. } else {
  1356. names[0][nameIndex] = bytesToString(font.getBytes(record.length));
  1357. }
  1358. }
  1359. return names;
  1360. }
  1361. var TTOpsStackDeltas = [0, 0, 0, 0, 0, 0, 0, 0, -2, -2, -2, -2, 0, 0, -2, -5, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, -1, 0, -1, -1, -1, -1, 1, -1, -999, 0, 1, 0, -1, -2, 0, -1, -2, -1, -1, 0, -1, -1, 0, 0, -999, -999, -1, -1, -1, -1, -2, -999, -2, -2, -999, 0, -2, -2, 0, 0, -2, 0, -2, 0, 0, 0, -2, -1, -1, 1, 1, 0, 0, -1, -1, -1, -1, -1, -1, -1, 0, 0, -1, 0, -1, -1, 0, -999, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -2, -999, -999, -999, -999, -999, -1, -1, -2, -2, 0, 0, 0, 0, -1, -1, -999, -2, -2, 0, 0, -1, -2, -2, 0, 0, 0, -1, -1, -1, -2];
  1362. function sanitizeTTProgram(table, ttContext) {
  1363. var data = table.data;
  1364. var i = 0,
  1365. j,
  1366. n,
  1367. b,
  1368. funcId,
  1369. pc,
  1370. lastEndf = 0,
  1371. lastDeff = 0;
  1372. var stack = [];
  1373. var callstack = [];
  1374. var functionsCalled = [];
  1375. var tooComplexToFollowFunctions = ttContext.tooComplexToFollowFunctions;
  1376. var inFDEF = false,
  1377. ifLevel = 0,
  1378. inELSE = 0;
  1379. for (var ii = data.length; i < ii;) {
  1380. var op = data[i++];
  1381. if (op === 0x40) {
  1382. n = data[i++];
  1383. if (inFDEF || inELSE) {
  1384. i += n;
  1385. } else {
  1386. for (j = 0; j < n; j++) {
  1387. stack.push(data[i++]);
  1388. }
  1389. }
  1390. } else if (op === 0x41) {
  1391. n = data[i++];
  1392. if (inFDEF || inELSE) {
  1393. i += n * 2;
  1394. } else {
  1395. for (j = 0; j < n; j++) {
  1396. b = data[i++];
  1397. stack.push(b << 8 | data[i++]);
  1398. }
  1399. }
  1400. } else if ((op & 0xF8) === 0xB0) {
  1401. n = op - 0xB0 + 1;
  1402. if (inFDEF || inELSE) {
  1403. i += n;
  1404. } else {
  1405. for (j = 0; j < n; j++) {
  1406. stack.push(data[i++]);
  1407. }
  1408. }
  1409. } else if ((op & 0xF8) === 0xB8) {
  1410. n = op - 0xB8 + 1;
  1411. if (inFDEF || inELSE) {
  1412. i += n * 2;
  1413. } else {
  1414. for (j = 0; j < n; j++) {
  1415. b = data[i++];
  1416. stack.push(b << 8 | data[i++]);
  1417. }
  1418. }
  1419. } else if (op === 0x2B && !tooComplexToFollowFunctions) {
  1420. if (!inFDEF && !inELSE) {
  1421. funcId = stack[stack.length - 1];
  1422. ttContext.functionsUsed[funcId] = true;
  1423. if (funcId in ttContext.functionsStackDeltas) {
  1424. stack.length += ttContext.functionsStackDeltas[funcId];
  1425. } else if (funcId in ttContext.functionsDefined && functionsCalled.indexOf(funcId) < 0) {
  1426. callstack.push({
  1427. data: data,
  1428. i: i,
  1429. stackTop: stack.length - 1
  1430. });
  1431. functionsCalled.push(funcId);
  1432. pc = ttContext.functionsDefined[funcId];
  1433. if (!pc) {
  1434. warn('TT: CALL non-existent function');
  1435. ttContext.hintsValid = false;
  1436. return;
  1437. }
  1438. data = pc.data;
  1439. i = pc.i;
  1440. }
  1441. }
  1442. } else if (op === 0x2C && !tooComplexToFollowFunctions) {
  1443. if (inFDEF || inELSE) {
  1444. warn('TT: nested FDEFs not allowed');
  1445. tooComplexToFollowFunctions = true;
  1446. }
  1447. inFDEF = true;
  1448. lastDeff = i;
  1449. funcId = stack.pop();
  1450. ttContext.functionsDefined[funcId] = {
  1451. data: data,
  1452. i: i
  1453. };
  1454. } else if (op === 0x2D) {
  1455. if (inFDEF) {
  1456. inFDEF = false;
  1457. lastEndf = i;
  1458. } else {
  1459. pc = callstack.pop();
  1460. if (!pc) {
  1461. warn('TT: ENDF bad stack');
  1462. ttContext.hintsValid = false;
  1463. return;
  1464. }
  1465. funcId = functionsCalled.pop();
  1466. data = pc.data;
  1467. i = pc.i;
  1468. ttContext.functionsStackDeltas[funcId] = stack.length - pc.stackTop;
  1469. }
  1470. } else if (op === 0x89) {
  1471. if (inFDEF || inELSE) {
  1472. warn('TT: nested IDEFs not allowed');
  1473. tooComplexToFollowFunctions = true;
  1474. }
  1475. inFDEF = true;
  1476. lastDeff = i;
  1477. } else if (op === 0x58) {
  1478. ++ifLevel;
  1479. } else if (op === 0x1B) {
  1480. inELSE = ifLevel;
  1481. } else if (op === 0x59) {
  1482. if (inELSE === ifLevel) {
  1483. inELSE = 0;
  1484. }
  1485. --ifLevel;
  1486. } else if (op === 0x1C) {
  1487. if (!inFDEF && !inELSE) {
  1488. var offset = stack[stack.length - 1];
  1489. if (offset > 0) {
  1490. i += offset - 1;
  1491. }
  1492. }
  1493. }
  1494. if (!inFDEF && !inELSE) {
  1495. var stackDelta = op <= 0x8E ? TTOpsStackDeltas[op] : op >= 0xC0 && op <= 0xDF ? -1 : op >= 0xE0 ? -2 : 0;
  1496. if (op >= 0x71 && op <= 0x75) {
  1497. n = stack.pop();
  1498. if (!isNaN(n)) {
  1499. stackDelta = -n * 2;
  1500. }
  1501. }
  1502. while (stackDelta < 0 && stack.length > 0) {
  1503. stack.pop();
  1504. stackDelta++;
  1505. }
  1506. while (stackDelta > 0) {
  1507. stack.push(NaN);
  1508. stackDelta--;
  1509. }
  1510. }
  1511. }
  1512. ttContext.tooComplexToFollowFunctions = tooComplexToFollowFunctions;
  1513. var content = [data];
  1514. if (i > data.length) {
  1515. content.push(new Uint8Array(i - data.length));
  1516. }
  1517. if (lastDeff > lastEndf) {
  1518. warn('TT: complementing a missing function tail');
  1519. content.push(new Uint8Array([0x22, 0x2D]));
  1520. }
  1521. foldTTTable(table, content);
  1522. }
  1523. function checkInvalidFunctions(ttContext, maxFunctionDefs) {
  1524. if (ttContext.tooComplexToFollowFunctions) {
  1525. return;
  1526. }
  1527. if (ttContext.functionsDefined.length > maxFunctionDefs) {
  1528. warn('TT: more functions defined than expected');
  1529. ttContext.hintsValid = false;
  1530. return;
  1531. }
  1532. for (var j = 0, jj = ttContext.functionsUsed.length; j < jj; j++) {
  1533. if (j > maxFunctionDefs) {
  1534. warn('TT: invalid function id: ' + j);
  1535. ttContext.hintsValid = false;
  1536. return;
  1537. }
  1538. if (ttContext.functionsUsed[j] && !ttContext.functionsDefined[j]) {
  1539. warn('TT: undefined function: ' + j);
  1540. ttContext.hintsValid = false;
  1541. return;
  1542. }
  1543. }
  1544. }
  1545. function foldTTTable(table, content) {
  1546. if (content.length > 1) {
  1547. var newLength = 0;
  1548. var j, jj;
  1549. for (j = 0, jj = content.length; j < jj; j++) {
  1550. newLength += content[j].length;
  1551. }
  1552. newLength = newLength + 3 & ~3;
  1553. var result = new Uint8Array(newLength);
  1554. var pos = 0;
  1555. for (j = 0, jj = content.length; j < jj; j++) {
  1556. result.set(content[j], pos);
  1557. pos += content[j].length;
  1558. }
  1559. table.data = result;
  1560. table.length = newLength;
  1561. }
  1562. }
  1563. function sanitizeTTPrograms(fpgm, prep, cvt, maxFunctionDefs) {
  1564. var ttContext = {
  1565. functionsDefined: [],
  1566. functionsUsed: [],
  1567. functionsStackDeltas: [],
  1568. tooComplexToFollowFunctions: false,
  1569. hintsValid: true
  1570. };
  1571. if (fpgm) {
  1572. sanitizeTTProgram(fpgm, ttContext);
  1573. }
  1574. if (prep) {
  1575. sanitizeTTProgram(prep, ttContext);
  1576. }
  1577. if (fpgm) {
  1578. checkInvalidFunctions(ttContext, maxFunctionDefs);
  1579. }
  1580. if (cvt && cvt.length & 1) {
  1581. var cvtData = new Uint8Array(cvt.length + 1);
  1582. cvtData.set(cvt.data);
  1583. cvt.data = cvtData;
  1584. }
  1585. return ttContext.hintsValid;
  1586. }
  1587. font = new Stream(new Uint8Array(font.getBytes()));
  1588. var VALID_TABLES = ['OS/2', 'cmap', 'head', 'hhea', 'hmtx', 'maxp', 'name', 'post', 'loca', 'glyf', 'fpgm', 'prep', 'cvt ', 'CFF '];
  1589. var header = readOpenTypeHeader(font);
  1590. var numTables = header.numTables;
  1591. var cff, cffFile;
  1592. var tables = Object.create(null);
  1593. tables['OS/2'] = null;
  1594. tables['cmap'] = null;
  1595. tables['head'] = null;
  1596. tables['hhea'] = null;
  1597. tables['hmtx'] = null;
  1598. tables['maxp'] = null;
  1599. tables['name'] = null;
  1600. tables['post'] = null;
  1601. var table;
  1602. for (var i = 0; i < numTables; i++) {
  1603. table = readTableEntry(font);
  1604. if (VALID_TABLES.indexOf(table.tag) < 0) {
  1605. continue;
  1606. }
  1607. if (table.length === 0) {
  1608. continue;
  1609. }
  1610. tables[table.tag] = table;
  1611. }
  1612. var isTrueType = !tables['CFF '];
  1613. if (!isTrueType) {
  1614. if (header.version === 'OTTO' && !properties.composite || !tables['head'] || !tables['hhea'] || !tables['maxp'] || !tables['post']) {
  1615. cffFile = new Stream(tables['CFF '].data);
  1616. cff = new CFFFont(cffFile, properties);
  1617. adjustWidths(properties);
  1618. return this.convert(name, cff, properties);
  1619. }
  1620. delete tables['glyf'];
  1621. delete tables['loca'];
  1622. delete tables['fpgm'];
  1623. delete tables['prep'];
  1624. delete tables['cvt '];
  1625. this.isOpenType = true;
  1626. } else {
  1627. if (!tables['loca']) {
  1628. error('Required "loca" table is not found');
  1629. }
  1630. if (!tables['glyf']) {
  1631. warn('Required "glyf" table is not found -- trying to recover.');
  1632. tables['glyf'] = {
  1633. tag: 'glyf',
  1634. data: new Uint8Array(0)
  1635. };
  1636. }
  1637. this.isOpenType = false;
  1638. }
  1639. if (!tables['maxp']) {
  1640. error('Required "maxp" table is not found');
  1641. }
  1642. font.pos = (font.start || 0) + tables['maxp'].offset;
  1643. var version = font.getInt32();
  1644. var numGlyphs = font.getUint16();
  1645. var maxFunctionDefs = 0;
  1646. if (version >= 0x00010000 && tables['maxp'].length >= 22) {
  1647. font.pos += 8;
  1648. var maxZones = font.getUint16();
  1649. if (maxZones > 2) {
  1650. tables['maxp'].data[14] = 0;
  1651. tables['maxp'].data[15] = 2;
  1652. }
  1653. font.pos += 4;
  1654. maxFunctionDefs = font.getUint16();
  1655. }
  1656. var dupFirstEntry = false;
  1657. if (properties.type === 'CIDFontType2' && properties.toUnicode && properties.toUnicode.get(0) > '\0') {
  1658. dupFirstEntry = true;
  1659. numGlyphs++;
  1660. tables['maxp'].data[4] = numGlyphs >> 8;
  1661. tables['maxp'].data[5] = numGlyphs & 255;
  1662. }
  1663. var hintsValid = sanitizeTTPrograms(tables['fpgm'], tables['prep'], tables['cvt '], maxFunctionDefs);
  1664. if (!hintsValid) {
  1665. delete tables['fpgm'];
  1666. delete tables['prep'];
  1667. delete tables['cvt '];
  1668. }
  1669. sanitizeMetrics(font, tables['hhea'], tables['hmtx'], numGlyphs);
  1670. if (!tables['head']) {
  1671. error('Required "head" table is not found');
  1672. }
  1673. sanitizeHead(tables['head'], numGlyphs, isTrueType ? tables['loca'].length : 0);
  1674. var missingGlyphs = Object.create(null);
  1675. if (isTrueType) {
  1676. var isGlyphLocationsLong = int16(tables['head'].data[50], tables['head'].data[51]);
  1677. missingGlyphs = sanitizeGlyphLocations(tables['loca'], tables['glyf'], numGlyphs, isGlyphLocationsLong, hintsValid, dupFirstEntry);
  1678. }
  1679. if (!tables['hhea']) {
  1680. error('Required "hhea" table is not found');
  1681. }
  1682. if (tables['hhea'].data[10] === 0 && tables['hhea'].data[11] === 0) {
  1683. tables['hhea'].data[10] = 0xFF;
  1684. tables['hhea'].data[11] = 0xFF;
  1685. }
  1686. var metricsOverride = {
  1687. unitsPerEm: int16(tables['head'].data[18], tables['head'].data[19]),
  1688. yMax: int16(tables['head'].data[42], tables['head'].data[43]),
  1689. yMin: signedInt16(tables['head'].data[38], tables['head'].data[39]),
  1690. ascent: int16(tables['hhea'].data[4], tables['hhea'].data[5]),
  1691. descent: signedInt16(tables['hhea'].data[6], tables['hhea'].data[7])
  1692. };
  1693. this.ascent = metricsOverride.ascent / metricsOverride.unitsPerEm;
  1694. this.descent = metricsOverride.descent / metricsOverride.unitsPerEm;
  1695. if (tables['post']) {
  1696. var valid = readPostScriptTable(tables['post'], properties, numGlyphs);
  1697. if (!valid) {
  1698. tables['post'] = null;
  1699. }
  1700. }
  1701. var charCodeToGlyphId = [],
  1702. charCode;
  1703. var toUnicode = properties.toUnicode,
  1704. widths = properties.widths;
  1705. var skipToUnicode = toUnicode instanceof IdentityToUnicodeMap || toUnicode.length === 0x10000;
  1706. function hasGlyph(glyphId, charCode, widthCode) {
  1707. if (!missingGlyphs[glyphId]) {
  1708. return true;
  1709. }
  1710. if (!skipToUnicode && charCode >= 0 && toUnicode.has(charCode)) {
  1711. return true;
  1712. }
  1713. if (widths && widthCode >= 0 && isNum(widths[widthCode])) {
  1714. return true;
  1715. }
  1716. return false;
  1717. }
  1718. if (properties.composite) {
  1719. var cidToGidMap = properties.cidToGidMap || [];
  1720. var isCidToGidMapEmpty = cidToGidMap.length === 0;
  1721. properties.cMap.forEach(function (charCode, cid) {
  1722. assert(cid <= 0xffff, 'Max size of CID is 65,535');
  1723. var glyphId = -1;
  1724. if (isCidToGidMapEmpty) {
  1725. glyphId = cid;
  1726. } else if (cidToGidMap[cid] !== undefined) {
  1727. glyphId = cidToGidMap[cid];
  1728. }
  1729. if (glyphId >= 0 && glyphId < numGlyphs && hasGlyph(glyphId, charCode, cid)) {
  1730. charCodeToGlyphId[charCode] = glyphId;
  1731. }
  1732. });
  1733. if (dupFirstEntry && (isCidToGidMapEmpty || !charCodeToGlyphId[0])) {
  1734. charCodeToGlyphId[0] = numGlyphs - 1;
  1735. }
  1736. } else {
  1737. var cmapTable = readCmapTable(tables['cmap'], font, this.isSymbolicFont, properties.hasEncoding);
  1738. var cmapPlatformId = cmapTable.platformId;
  1739. var cmapEncodingId = cmapTable.encodingId;
  1740. var cmapMappings = cmapTable.mappings;
  1741. var cmapMappingsLength = cmapMappings.length;
  1742. if (properties.hasEncoding && (cmapPlatformId === 3 && cmapEncodingId === 1 || cmapPlatformId === 1 && cmapEncodingId === 0) || cmapPlatformId === -1 && cmapEncodingId === -1 && !!getEncoding(properties.baseEncodingName)) {
  1743. var baseEncoding = [];
  1744. if (properties.baseEncodingName === 'MacRomanEncoding' || properties.baseEncodingName === 'WinAnsiEncoding') {
  1745. baseEncoding = getEncoding(properties.baseEncodingName);
  1746. }
  1747. var glyphsUnicodeMap = getGlyphsUnicode();
  1748. for (charCode = 0; charCode < 256; charCode++) {
  1749. var glyphName, standardGlyphName;
  1750. if (this.differences && charCode in this.differences) {
  1751. glyphName = this.differences[charCode];
  1752. } else if (charCode in baseEncoding && baseEncoding[charCode] !== '') {
  1753. glyphName = baseEncoding[charCode];
  1754. } else {
  1755. glyphName = StandardEncoding[charCode];
  1756. }
  1757. if (!glyphName) {
  1758. continue;
  1759. }
  1760. standardGlyphName = recoverGlyphName(glyphName, glyphsUnicodeMap);
  1761. var unicodeOrCharCode,
  1762. isUnicode = false;
  1763. if (cmapPlatformId === 3 && cmapEncodingId === 1) {
  1764. unicodeOrCharCode = glyphsUnicodeMap[standardGlyphName];
  1765. isUnicode = true;
  1766. } else if (cmapPlatformId === 1 && cmapEncodingId === 0) {
  1767. unicodeOrCharCode = MacRomanEncoding.indexOf(standardGlyphName);
  1768. }
  1769. var found = false;
  1770. for (i = 0; i < cmapMappingsLength; ++i) {
  1771. if (cmapMappings[i].charCode !== unicodeOrCharCode) {
  1772. continue;
  1773. }
  1774. var code = isUnicode ? charCode : unicodeOrCharCode;
  1775. if (hasGlyph(cmapMappings[i].glyphId, code, -1)) {
  1776. charCodeToGlyphId[charCode] = cmapMappings[i].glyphId;
  1777. found = true;
  1778. break;
  1779. }
  1780. }
  1781. if (!found && properties.glyphNames) {
  1782. var glyphId = properties.glyphNames.indexOf(glyphName);
  1783. if (glyphId === -1 && standardGlyphName !== glyphName) {
  1784. glyphId = properties.glyphNames.indexOf(standardGlyphName);
  1785. }
  1786. if (glyphId > 0 && hasGlyph(glyphId, -1, -1)) {
  1787. charCodeToGlyphId[charCode] = glyphId;
  1788. found = true;
  1789. }
  1790. }
  1791. if (!found) {
  1792. charCodeToGlyphId[charCode] = 0;
  1793. }
  1794. }
  1795. } else if (cmapPlatformId === 0 && cmapEncodingId === 0) {
  1796. for (i = 0; i < cmapMappingsLength; ++i) {
  1797. charCodeToGlyphId[cmapMappings[i].charCode] = cmapMappings[i].glyphId;
  1798. }
  1799. } else {
  1800. for (i = 0; i < cmapMappingsLength; ++i) {
  1801. charCode = cmapMappings[i].charCode & 0xFF;
  1802. charCodeToGlyphId[charCode] = cmapMappings[i].glyphId;
  1803. }
  1804. }
  1805. }
  1806. if (charCodeToGlyphId.length === 0) {
  1807. charCodeToGlyphId[0] = 0;
  1808. }
  1809. var newMapping = adjustMapping(charCodeToGlyphId, properties);
  1810. this.toFontChar = newMapping.toFontChar;
  1811. tables['cmap'] = {
  1812. tag: 'cmap',
  1813. data: createCmapTable(newMapping.charCodeToGlyphId, numGlyphs)
  1814. };
  1815. if (!tables['OS/2'] || !validateOS2Table(tables['OS/2'])) {
  1816. tables['OS/2'] = {
  1817. tag: 'OS/2',
  1818. data: createOS2Table(properties, newMapping.charCodeToGlyphId, metricsOverride)
  1819. };
  1820. }
  1821. if (!tables['post']) {
  1822. tables['post'] = {
  1823. tag: 'post',
  1824. data: createPostTable(properties)
  1825. };
  1826. }
  1827. if (!isTrueType) {
  1828. try {
  1829. cffFile = new Stream(tables['CFF '].data);
  1830. var parser = new CFFParser(cffFile, properties, SEAC_ANALYSIS_ENABLED);
  1831. cff = parser.parse();
  1832. var compiler = new CFFCompiler(cff);
  1833. tables['CFF '].data = compiler.compile();
  1834. } catch (e) {
  1835. warn('Failed to compile font ' + properties.loadedName);
  1836. }
  1837. }
  1838. if (!tables['name']) {
  1839. tables['name'] = {
  1840. tag: 'name',
  1841. data: createNameTable(this.name)
  1842. };
  1843. } else {
  1844. var namePrototype = readNameTable(tables['name']);
  1845. tables['name'].data = createNameTable(name, namePrototype);
  1846. }
  1847. var builder = new OpenTypeFileBuilder(header.version);
  1848. for (var tableTag in tables) {
  1849. builder.addTable(tableTag, tables[tableTag].data);
  1850. }
  1851. return builder.toArray();
  1852. },
  1853. convert: function Font_convert(fontName, font, properties) {
  1854. properties.fixedPitch = false;
  1855. if (properties.builtInEncoding) {
  1856. adjustToUnicode(properties, properties.builtInEncoding);
  1857. }
  1858. var mapping = font.getGlyphMapping(properties);
  1859. var newMapping = adjustMapping(mapping, properties);
  1860. this.toFontChar = newMapping.toFontChar;
  1861. var numGlyphs = font.numGlyphs;
  1862. function getCharCodes(charCodeToGlyphId, glyphId) {
  1863. var charCodes = null;
  1864. for (var charCode in charCodeToGlyphId) {
  1865. if (glyphId === charCodeToGlyphId[charCode]) {
  1866. if (!charCodes) {
  1867. charCodes = [];
  1868. }
  1869. charCodes.push(charCode | 0);
  1870. }
  1871. }
  1872. return charCodes;
  1873. }
  1874. function createCharCode(charCodeToGlyphId, glyphId) {
  1875. for (var charCode in charCodeToGlyphId) {
  1876. if (glyphId === charCodeToGlyphId[charCode]) {
  1877. return charCode | 0;
  1878. }
  1879. }
  1880. newMapping.charCodeToGlyphId[newMapping.nextAvailableFontCharCode] = glyphId;
  1881. return newMapping.nextAvailableFontCharCode++;
  1882. }
  1883. var seacs = font.seacs;
  1884. if (SEAC_ANALYSIS_ENABLED && seacs && seacs.length) {
  1885. var matrix = properties.fontMatrix || FONT_IDENTITY_MATRIX;
  1886. var charset = font.getCharset();
  1887. var seacMap = Object.create(null);
  1888. for (var glyphId in seacs) {
  1889. glyphId |= 0;
  1890. var seac = seacs[glyphId];
  1891. var baseGlyphName = StandardEncoding[seac[2]];
  1892. var accentGlyphName = StandardEncoding[seac[3]];
  1893. var baseGlyphId = charset.indexOf(baseGlyphName);
  1894. var accentGlyphId = charset.indexOf(accentGlyphName);
  1895. if (baseGlyphId < 0 || accentGlyphId < 0) {
  1896. continue;
  1897. }
  1898. var accentOffset = {
  1899. x: seac[0] * matrix[0] + seac[1] * matrix[2] + matrix[4],
  1900. y: seac[0] * matrix[1] + seac[1] * matrix[3] + matrix[5]
  1901. };
  1902. var charCodes = getCharCodes(mapping, glyphId);
  1903. if (!charCodes) {
  1904. continue;
  1905. }
  1906. for (var i = 0, ii = charCodes.length; i < ii; i++) {
  1907. var charCode = charCodes[i];
  1908. var charCodeToGlyphId = newMapping.charCodeToGlyphId;
  1909. var baseFontCharCode = createCharCode(charCodeToGlyphId, baseGlyphId);
  1910. var accentFontCharCode = createCharCode(charCodeToGlyphId, accentGlyphId);
  1911. seacMap[charCode] = {
  1912. baseFontCharCode: baseFontCharCode,
  1913. accentFontCharCode: accentFontCharCode,
  1914. accentOffset: accentOffset
  1915. };
  1916. }
  1917. }
  1918. properties.seacMap = seacMap;
  1919. }
  1920. var unitsPerEm = 1 / (properties.fontMatrix || FONT_IDENTITY_MATRIX)[0];
  1921. var builder = new OpenTypeFileBuilder('\x4F\x54\x54\x4F');
  1922. builder.addTable('CFF ', font.data);
  1923. builder.addTable('OS/2', createOS2Table(properties, newMapping.charCodeToGlyphId));
  1924. builder.addTable('cmap', createCmapTable(newMapping.charCodeToGlyphId, numGlyphs));
  1925. builder.addTable('head', '\x00\x01\x00\x00' + '\x00\x00\x10\x00' + '\x00\x00\x00\x00' + '\x5F\x0F\x3C\xF5' + '\x00\x00' + safeString16(unitsPerEm) + '\x00\x00\x00\x00\x9e\x0b\x7e\x27' + '\x00\x00\x00\x00\x9e\x0b\x7e\x27' + '\x00\x00' + safeString16(properties.descent) + '\x0F\xFF' + safeString16(properties.ascent) + string16(properties.italicAngle ? 2 : 0) + '\x00\x11' + '\x00\x00' + '\x00\x00' + '\x00\x00');
  1926. builder.addTable('hhea', '\x00\x01\x00\x00' + safeString16(properties.ascent) + safeString16(properties.descent) + '\x00\x00' + '\xFF\xFF' + '\x00\x00' + '\x00\x00' + '\x00\x00' + safeString16(properties.capHeight) + safeString16(Math.tan(properties.italicAngle) * properties.xHeight) + '\x00\x00' + '\x00\x00' + '\x00\x00' + '\x00\x00' + '\x00\x00' + '\x00\x00' + string16(numGlyphs));
  1927. builder.addTable('hmtx', function fontFieldsHmtx() {
  1928. var charstrings = font.charstrings;
  1929. var cffWidths = font.cff ? font.cff.widths : null;
  1930. var hmtx = '\x00\x00\x00\x00';
  1931. for (var i = 1, ii = numGlyphs; i < ii; i++) {
  1932. var width = 0;
  1933. if (charstrings) {
  1934. var charstring = charstrings[i - 1];
  1935. width = 'width' in charstring ? charstring.width : 0;
  1936. } else if (cffWidths) {
  1937. width = Math.ceil(cffWidths[i] || 0);
  1938. }
  1939. hmtx += string16(width) + string16(0);
  1940. }
  1941. return hmtx;
  1942. }());
  1943. builder.addTable('maxp', '\x00\x00\x50\x00' + string16(numGlyphs));
  1944. builder.addTable('name', createNameTable(fontName));
  1945. builder.addTable('post', createPostTable(properties));
  1946. return builder.toArray();
  1947. },
  1948. get spaceWidth() {
  1949. if ('_shadowWidth' in this) {
  1950. return this._shadowWidth;
  1951. }
  1952. var possibleSpaceReplacements = ['space', 'minus', 'one', 'i', 'I'];
  1953. var width;
  1954. for (var i = 0, ii = possibleSpaceReplacements.length; i < ii; i++) {
  1955. var glyphName = possibleSpaceReplacements[i];
  1956. if (glyphName in this.widths) {
  1957. width = this.widths[glyphName];
  1958. break;
  1959. }
  1960. var glyphsUnicodeMap = getGlyphsUnicode();
  1961. var glyphUnicode = glyphsUnicodeMap[glyphName];
  1962. var charcode = 0;
  1963. if (this.composite) {
  1964. if (this.cMap.contains(glyphUnicode)) {
  1965. charcode = this.cMap.lookup(glyphUnicode);
  1966. }
  1967. }
  1968. if (!charcode && this.toUnicode) {
  1969. charcode = this.toUnicode.charCodeOf(glyphUnicode);
  1970. }
  1971. if (charcode <= 0) {
  1972. charcode = glyphUnicode;
  1973. }
  1974. width = this.widths[charcode];
  1975. if (width) {
  1976. break;
  1977. }
  1978. }
  1979. width = width || this.defaultWidth;
  1980. this._shadowWidth = width;
  1981. return width;
  1982. },
  1983. charToGlyph: function Font_charToGlyph(charcode, isSpace) {
  1984. var fontCharCode, width, operatorListId;
  1985. var widthCode = charcode;
  1986. if (this.cMap && this.cMap.contains(charcode)) {
  1987. widthCode = this.cMap.lookup(charcode);
  1988. }
  1989. width = this.widths[widthCode];
  1990. width = isNum(width) ? width : this.defaultWidth;
  1991. var vmetric = this.vmetrics && this.vmetrics[widthCode];
  1992. var unicode = this.toUnicode.get(charcode) || charcode;
  1993. if (typeof unicode === 'number') {
  1994. unicode = String.fromCharCode(unicode);
  1995. }
  1996. var isInFont = charcode in this.toFontChar;
  1997. fontCharCode = this.toFontChar[charcode] || charcode;
  1998. if (this.missingFile) {
  1999. fontCharCode = mapSpecialUnicodeValues(fontCharCode);
  2000. }
  2001. if (this.isType3Font) {
  2002. operatorListId = fontCharCode;
  2003. }
  2004. var accent = null;
  2005. if (this.seacMap && this.seacMap[charcode]) {
  2006. isInFont = true;
  2007. var seac = this.seacMap[charcode];
  2008. fontCharCode = seac.baseFontCharCode;
  2009. accent = {
  2010. fontChar: String.fromCharCode(seac.accentFontCharCode),
  2011. offset: seac.accentOffset
  2012. };
  2013. }
  2014. var fontChar = String.fromCharCode(fontCharCode);
  2015. var glyph = this.glyphCache[charcode];
  2016. if (!glyph || !glyph.matchesForCache(fontChar, unicode, accent, width, vmetric, operatorListId, isSpace, isInFont)) {
  2017. glyph = new Glyph(fontChar, unicode, accent, width, vmetric, operatorListId, isSpace, isInFont);
  2018. this.glyphCache[charcode] = glyph;
  2019. }
  2020. return glyph;
  2021. },
  2022. charsToGlyphs: function Font_charsToGlyphs(chars) {
  2023. var charsCache = this.charsCache;
  2024. var glyphs, glyph, charcode;
  2025. if (charsCache) {
  2026. glyphs = charsCache[chars];
  2027. if (glyphs) {
  2028. return glyphs;
  2029. }
  2030. }
  2031. if (!charsCache) {
  2032. charsCache = this.charsCache = Object.create(null);
  2033. }
  2034. glyphs = [];
  2035. var charsCacheKey = chars;
  2036. var i = 0,
  2037. ii;
  2038. if (this.cMap) {
  2039. var c = Object.create(null);
  2040. while (i < chars.length) {
  2041. this.cMap.readCharCode(chars, i, c);
  2042. charcode = c.charcode;
  2043. var length = c.length;
  2044. i += length;
  2045. var isSpace = length === 1 && chars.charCodeAt(i - 1) === 0x20;
  2046. glyph = this.charToGlyph(charcode, isSpace);
  2047. glyphs.push(glyph);
  2048. }
  2049. } else {
  2050. for (i = 0, ii = chars.length; i < ii; ++i) {
  2051. charcode = chars.charCodeAt(i);
  2052. glyph = this.charToGlyph(charcode, charcode === 0x20);
  2053. glyphs.push(glyph);
  2054. }
  2055. }
  2056. return charsCache[charsCacheKey] = glyphs;
  2057. }
  2058. };
  2059. return Font;
  2060. }();
  2061. var ErrorFont = function ErrorFontClosure() {
  2062. function ErrorFont(error) {
  2063. this.error = error;
  2064. this.loadedName = 'g_font_error';
  2065. this.loading = false;
  2066. }
  2067. ErrorFont.prototype = {
  2068. charsToGlyphs: function ErrorFont_charsToGlyphs() {
  2069. return [];
  2070. },
  2071. exportData: function ErrorFont_exportData() {
  2072. return { error: this.error };
  2073. }
  2074. };
  2075. return ErrorFont;
  2076. }();
  2077. function type1FontGlyphMapping(properties, builtInEncoding, glyphNames) {
  2078. var charCodeToGlyphId = Object.create(null);
  2079. var glyphId, charCode, baseEncoding;
  2080. var isSymbolicFont = !!(properties.flags & FontFlags.Symbolic);
  2081. if (properties.baseEncodingName) {
  2082. baseEncoding = getEncoding(properties.baseEncodingName);
  2083. for (charCode = 0; charCode < baseEncoding.length; charCode++) {
  2084. glyphId = glyphNames.indexOf(baseEncoding[charCode]);
  2085. if (glyphId >= 0) {
  2086. charCodeToGlyphId[charCode] = glyphId;
  2087. } else {
  2088. charCodeToGlyphId[charCode] = 0;
  2089. }
  2090. }
  2091. } else if (isSymbolicFont) {
  2092. for (charCode in builtInEncoding) {
  2093. charCodeToGlyphId[charCode] = builtInEncoding[charCode];
  2094. }
  2095. } else {
  2096. baseEncoding = StandardEncoding;
  2097. for (charCode = 0; charCode < baseEncoding.length; charCode++) {
  2098. glyphId = glyphNames.indexOf(baseEncoding[charCode]);
  2099. if (glyphId >= 0) {
  2100. charCodeToGlyphId[charCode] = glyphId;
  2101. } else {
  2102. charCodeToGlyphId[charCode] = 0;
  2103. }
  2104. }
  2105. }
  2106. var differences = properties.differences,
  2107. glyphsUnicodeMap;
  2108. if (differences) {
  2109. for (charCode in differences) {
  2110. var glyphName = differences[charCode];
  2111. glyphId = glyphNames.indexOf(glyphName);
  2112. if (glyphId === -1) {
  2113. if (!glyphsUnicodeMap) {
  2114. glyphsUnicodeMap = getGlyphsUnicode();
  2115. }
  2116. var standardGlyphName = recoverGlyphName(glyphName, glyphsUnicodeMap);
  2117. if (standardGlyphName !== glyphName) {
  2118. glyphId = glyphNames.indexOf(standardGlyphName);
  2119. }
  2120. }
  2121. if (glyphId >= 0) {
  2122. charCodeToGlyphId[charCode] = glyphId;
  2123. } else {
  2124. charCodeToGlyphId[charCode] = 0;
  2125. }
  2126. }
  2127. }
  2128. return charCodeToGlyphId;
  2129. }
  2130. var Type1Font = function Type1FontClosure() {
  2131. function findBlock(streamBytes, signature, startIndex) {
  2132. var streamBytesLength = streamBytes.length;
  2133. var signatureLength = signature.length;
  2134. var scanLength = streamBytesLength - signatureLength;
  2135. var i = startIndex,
  2136. j,
  2137. found = false;
  2138. while (i < scanLength) {
  2139. j = 0;
  2140. while (j < signatureLength && streamBytes[i + j] === signature[j]) {
  2141. j++;
  2142. }
  2143. if (j >= signatureLength) {
  2144. i += j;
  2145. while (i < streamBytesLength && isSpace(streamBytes[i])) {
  2146. i++;
  2147. }
  2148. found = true;
  2149. break;
  2150. }
  2151. i++;
  2152. }
  2153. return {
  2154. found: found,
  2155. length: i
  2156. };
  2157. }
  2158. function getHeaderBlock(stream, suggestedLength) {
  2159. var EEXEC_SIGNATURE = [0x65, 0x65, 0x78, 0x65, 0x63];
  2160. var streamStartPos = stream.pos;
  2161. var headerBytes, headerBytesLength, block;
  2162. try {
  2163. headerBytes = stream.getBytes(suggestedLength);
  2164. headerBytesLength = headerBytes.length;
  2165. } catch (ex) {
  2166. if (ex instanceof MissingDataException) {
  2167. throw ex;
  2168. }
  2169. }
  2170. if (headerBytesLength === suggestedLength) {
  2171. block = findBlock(headerBytes, EEXEC_SIGNATURE, suggestedLength - 2 * EEXEC_SIGNATURE.length);
  2172. if (block.found && block.length === suggestedLength) {
  2173. return {
  2174. stream: new Stream(headerBytes),
  2175. length: suggestedLength
  2176. };
  2177. }
  2178. }
  2179. warn('Invalid "Length1" property in Type1 font -- trying to recover.');
  2180. stream.pos = streamStartPos;
  2181. var SCAN_BLOCK_LENGTH = 2048;
  2182. var actualLength;
  2183. while (true) {
  2184. var scanBytes = stream.peekBytes(SCAN_BLOCK_LENGTH);
  2185. block = findBlock(scanBytes, EEXEC_SIGNATURE, 0);
  2186. if (block.length === 0) {
  2187. break;
  2188. }
  2189. stream.pos += block.length;
  2190. if (block.found) {
  2191. actualLength = stream.pos - streamStartPos;
  2192. break;
  2193. }
  2194. }
  2195. stream.pos = streamStartPos;
  2196. if (actualLength) {
  2197. return {
  2198. stream: new Stream(stream.getBytes(actualLength)),
  2199. length: actualLength
  2200. };
  2201. }
  2202. warn('Unable to recover "Length1" property in Type1 font -- using as is.');
  2203. return {
  2204. stream: new Stream(stream.getBytes(suggestedLength)),
  2205. length: suggestedLength
  2206. };
  2207. }
  2208. function getEexecBlock(stream, suggestedLength) {
  2209. var eexecBytes = stream.getBytes();
  2210. return {
  2211. stream: new Stream(eexecBytes),
  2212. length: eexecBytes.length
  2213. };
  2214. }
  2215. function Type1Font(name, file, properties) {
  2216. var PFB_HEADER_SIZE = 6;
  2217. var headerBlockLength = properties.length1;
  2218. var eexecBlockLength = properties.length2;
  2219. var pfbHeader = file.peekBytes(PFB_HEADER_SIZE);
  2220. var pfbHeaderPresent = pfbHeader[0] === 0x80 && pfbHeader[1] === 0x01;
  2221. if (pfbHeaderPresent) {
  2222. file.skip(PFB_HEADER_SIZE);
  2223. headerBlockLength = pfbHeader[5] << 24 | pfbHeader[4] << 16 | pfbHeader[3] << 8 | pfbHeader[2];
  2224. }
  2225. var headerBlock = getHeaderBlock(file, headerBlockLength);
  2226. headerBlockLength = headerBlock.length;
  2227. var headerBlockParser = new Type1Parser(headerBlock.stream, false, SEAC_ANALYSIS_ENABLED);
  2228. headerBlockParser.extractFontHeader(properties);
  2229. if (pfbHeaderPresent) {
  2230. pfbHeader = file.getBytes(PFB_HEADER_SIZE);
  2231. eexecBlockLength = pfbHeader[5] << 24 | pfbHeader[4] << 16 | pfbHeader[3] << 8 | pfbHeader[2];
  2232. }
  2233. var eexecBlock = getEexecBlock(file, eexecBlockLength);
  2234. eexecBlockLength = eexecBlock.length;
  2235. var eexecBlockParser = new Type1Parser(eexecBlock.stream, true, SEAC_ANALYSIS_ENABLED);
  2236. var data = eexecBlockParser.extractFontProgram();
  2237. for (var info in data.properties) {
  2238. properties[info] = data.properties[info];
  2239. }
  2240. var charstrings = data.charstrings;
  2241. var type2Charstrings = this.getType2Charstrings(charstrings);
  2242. var subrs = this.getType2Subrs(data.subrs);
  2243. this.charstrings = charstrings;
  2244. this.data = this.wrap(name, type2Charstrings, this.charstrings, subrs, properties);
  2245. this.seacs = this.getSeacs(data.charstrings);
  2246. }
  2247. Type1Font.prototype = {
  2248. get numGlyphs() {
  2249. return this.charstrings.length + 1;
  2250. },
  2251. getCharset: function Type1Font_getCharset() {
  2252. var charset = ['.notdef'];
  2253. var charstrings = this.charstrings;
  2254. for (var glyphId = 0; glyphId < charstrings.length; glyphId++) {
  2255. charset.push(charstrings[glyphId].glyphName);
  2256. }
  2257. return charset;
  2258. },
  2259. getGlyphMapping: function Type1Font_getGlyphMapping(properties) {
  2260. var charstrings = this.charstrings;
  2261. var glyphNames = ['.notdef'],
  2262. glyphId;
  2263. for (glyphId = 0; glyphId < charstrings.length; glyphId++) {
  2264. glyphNames.push(charstrings[glyphId].glyphName);
  2265. }
  2266. var encoding = properties.builtInEncoding;
  2267. if (encoding) {
  2268. var builtInEncoding = Object.create(null);
  2269. for (var charCode in encoding) {
  2270. glyphId = glyphNames.indexOf(encoding[charCode]);
  2271. if (glyphId >= 0) {
  2272. builtInEncoding[charCode] = glyphId;
  2273. }
  2274. }
  2275. }
  2276. return type1FontGlyphMapping(properties, builtInEncoding, glyphNames);
  2277. },
  2278. getSeacs: function Type1Font_getSeacs(charstrings) {
  2279. var i, ii;
  2280. var seacMap = [];
  2281. for (i = 0, ii = charstrings.length; i < ii; i++) {
  2282. var charstring = charstrings[i];
  2283. if (charstring.seac) {
  2284. seacMap[i + 1] = charstring.seac;
  2285. }
  2286. }
  2287. return seacMap;
  2288. },
  2289. getType2Charstrings: function Type1Font_getType2Charstrings(type1Charstrings) {
  2290. var type2Charstrings = [];
  2291. for (var i = 0, ii = type1Charstrings.length; i < ii; i++) {
  2292. type2Charstrings.push(type1Charstrings[i].charstring);
  2293. }
  2294. return type2Charstrings;
  2295. },
  2296. getType2Subrs: function Type1Font_getType2Subrs(type1Subrs) {
  2297. var bias = 0;
  2298. var count = type1Subrs.length;
  2299. if (count < 1133) {
  2300. bias = 107;
  2301. } else if (count < 33769) {
  2302. bias = 1131;
  2303. } else {
  2304. bias = 32768;
  2305. }
  2306. var type2Subrs = [];
  2307. var i;
  2308. for (i = 0; i < bias; i++) {
  2309. type2Subrs.push([0x0B]);
  2310. }
  2311. for (i = 0; i < count; i++) {
  2312. type2Subrs.push(type1Subrs[i]);
  2313. }
  2314. return type2Subrs;
  2315. },
  2316. wrap: function Type1Font_wrap(name, glyphs, charstrings, subrs, properties) {
  2317. var cff = new CFF();
  2318. cff.header = new CFFHeader(1, 0, 4, 4);
  2319. cff.names = [name];
  2320. var topDict = new CFFTopDict();
  2321. topDict.setByName('version', 391);
  2322. topDict.setByName('Notice', 392);
  2323. topDict.setByName('FullName', 393);
  2324. topDict.setByName('FamilyName', 394);
  2325. topDict.setByName('Weight', 395);
  2326. topDict.setByName('Encoding', null);
  2327. topDict.setByName('FontMatrix', properties.fontMatrix);
  2328. topDict.setByName('FontBBox', properties.bbox);
  2329. topDict.setByName('charset', null);
  2330. topDict.setByName('CharStrings', null);
  2331. topDict.setByName('Private', null);
  2332. cff.topDict = topDict;
  2333. var strings = new CFFStrings();
  2334. strings.add('Version 0.11');
  2335. strings.add('See original notice');
  2336. strings.add(name);
  2337. strings.add(name);
  2338. strings.add('Medium');
  2339. cff.strings = strings;
  2340. cff.globalSubrIndex = new CFFIndex();
  2341. var count = glyphs.length;
  2342. var charsetArray = [0];
  2343. var i, ii;
  2344. for (i = 0; i < count; i++) {
  2345. var index = CFFStandardStrings.indexOf(charstrings[i].glyphName);
  2346. if (index === -1) {
  2347. index = 0;
  2348. }
  2349. charsetArray.push(index >> 8 & 0xff, index & 0xff);
  2350. }
  2351. cff.charset = new CFFCharset(false, 0, [], charsetArray);
  2352. var charStringsIndex = new CFFIndex();
  2353. charStringsIndex.add([0x8B, 0x0E]);
  2354. for (i = 0; i < count; i++) {
  2355. var glyph = glyphs[i];
  2356. if (glyph.length === 0) {
  2357. charStringsIndex.add([0x8B, 0x0E]);
  2358. continue;
  2359. }
  2360. charStringsIndex.add(glyph);
  2361. }
  2362. cff.charStrings = charStringsIndex;
  2363. var privateDict = new CFFPrivateDict();
  2364. privateDict.setByName('Subrs', null);
  2365. var fields = ['BlueValues', 'OtherBlues', 'FamilyBlues', 'FamilyOtherBlues', 'StemSnapH', 'StemSnapV', 'BlueShift', 'BlueFuzz', 'BlueScale', 'LanguageGroup', 'ExpansionFactor', 'ForceBold', 'StdHW', 'StdVW'];
  2366. for (i = 0, ii = fields.length; i < ii; i++) {
  2367. var field = fields[i];
  2368. if (!(field in properties.privateData)) {
  2369. continue;
  2370. }
  2371. var value = properties.privateData[field];
  2372. if (isArray(value)) {
  2373. for (var j = value.length - 1; j > 0; j--) {
  2374. value[j] -= value[j - 1];
  2375. }
  2376. }
  2377. privateDict.setByName(field, value);
  2378. }
  2379. cff.topDict.privateDict = privateDict;
  2380. var subrIndex = new CFFIndex();
  2381. for (i = 0, ii = subrs.length; i < ii; i++) {
  2382. subrIndex.add(subrs[i]);
  2383. }
  2384. privateDict.subrsIndex = subrIndex;
  2385. var compiler = new CFFCompiler(cff);
  2386. return compiler.compile();
  2387. }
  2388. };
  2389. return Type1Font;
  2390. }();
  2391. var CFFFont = function CFFFontClosure() {
  2392. function CFFFont(file, properties) {
  2393. this.properties = properties;
  2394. var parser = new CFFParser(file, properties, SEAC_ANALYSIS_ENABLED);
  2395. this.cff = parser.parse();
  2396. var compiler = new CFFCompiler(this.cff);
  2397. this.seacs = this.cff.seacs;
  2398. try {
  2399. this.data = compiler.compile();
  2400. } catch (e) {
  2401. warn('Failed to compile font ' + properties.loadedName);
  2402. this.data = file;
  2403. }
  2404. }
  2405. CFFFont.prototype = {
  2406. get numGlyphs() {
  2407. return this.cff.charStrings.count;
  2408. },
  2409. getCharset: function CFFFont_getCharset() {
  2410. return this.cff.charset.charset;
  2411. },
  2412. getGlyphMapping: function CFFFont_getGlyphMapping() {
  2413. var cff = this.cff;
  2414. var properties = this.properties;
  2415. var charsets = cff.charset.charset;
  2416. var charCodeToGlyphId;
  2417. var glyphId;
  2418. if (properties.composite) {
  2419. charCodeToGlyphId = Object.create(null);
  2420. if (cff.isCIDFont) {
  2421. for (glyphId = 0; glyphId < charsets.length; glyphId++) {
  2422. var cid = charsets[glyphId];
  2423. var charCode = properties.cMap.charCodeOf(cid);
  2424. charCodeToGlyphId[charCode] = glyphId;
  2425. }
  2426. } else {
  2427. for (glyphId = 0; glyphId < cff.charStrings.count; glyphId++) {
  2428. charCodeToGlyphId[glyphId] = glyphId;
  2429. }
  2430. }
  2431. return charCodeToGlyphId;
  2432. }
  2433. var encoding = cff.encoding ? cff.encoding.encoding : null;
  2434. charCodeToGlyphId = type1FontGlyphMapping(properties, encoding, charsets);
  2435. return charCodeToGlyphId;
  2436. }
  2437. };
  2438. return CFFFont;
  2439. }();
  2440. (function checkSeacSupport() {
  2441. if (typeof navigator !== 'undefined' && /Windows/.test(navigator.userAgent)) {
  2442. SEAC_ANALYSIS_ENABLED = true;
  2443. }
  2444. })();
  2445. (function checkChromeWindows() {
  2446. if (typeof navigator !== 'undefined' && /Windows.*Chrome/.test(navigator.userAgent)) {
  2447. SKIP_PRIVATE_USE_RANGE_F000_TO_F01F = true;
  2448. }
  2449. })();
  2450. exports.SEAC_ANALYSIS_ENABLED = SEAC_ANALYSIS_ENABLED;
  2451. exports.PRIVATE_USE_OFFSET_START = PRIVATE_USE_OFFSET_START;
  2452. exports.PRIVATE_USE_OFFSET_END = PRIVATE_USE_OFFSET_END;
  2453. exports.ErrorFont = ErrorFont;
  2454. exports.Font = Font;
  2455. exports.FontFlags = FontFlags;
  2456. exports.IdentityToUnicodeMap = IdentityToUnicodeMap;
  2457. exports.ProblematicCharRanges = ProblematicCharRanges;
  2458. exports.ToUnicodeMap = ToUnicodeMap;
  2459. exports.getFontType = getFontType;