fonts.js 92 KB

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