fonts.js 92 KB

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