cff_parser.js 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * JavaScript code in this page
  4. *
  5. * Copyright 2022 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * JavaScript code in this page
  21. */
  22. "use strict";
  23. Object.defineProperty(exports, "__esModule", {
  24. value: true
  25. });
  26. exports.CFFTopDict = exports.CFFStrings = exports.CFFStandardStrings = exports.CFFPrivateDict = exports.CFFParser = exports.CFFIndex = exports.CFFHeader = exports.CFFFDSelect = exports.CFFCompiler = exports.CFFCharset = exports.CFF = void 0;
  27. var _util = require("../shared/util.js");
  28. var _charsets = require("./charsets.js");
  29. var _encodings = require("./encodings.js");
  30. const MAX_SUBR_NESTING = 10;
  31. const CFFStandardStrings = [".notdef", "space", "exclam", "quotedbl", "numbersign", "dollar", "percent", "ampersand", "quoteright", "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", "quoteleft", "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", "exclamdown", "cent", "sterling", "fraction", "yen", "florin", "section", "currency", "quotesingle", "quotedblleft", "guillemotleft", "guilsinglleft", "guilsinglright", "fi", "fl", "endash", "dagger", "daggerdbl", "periodcentered", "paragraph", "bullet", "quotesinglbase", "quotedblbase", "quotedblright", "guillemotright", "ellipsis", "perthousand", "questiondown", "grave", "acute", "circumflex", "tilde", "macron", "breve", "dotaccent", "dieresis", "ring", "cedilla", "hungarumlaut", "ogonek", "caron", "emdash", "AE", "ordfeminine", "Lslash", "Oslash", "OE", "ordmasculine", "ae", "dotlessi", "lslash", "oslash", "oe", "germandbls", "onesuperior", "logicalnot", "mu", "trademark", "Eth", "onehalf", "plusminus", "Thorn", "onequarter", "divide", "brokenbar", "degree", "thorn", "threequarters", "twosuperior", "registered", "minus", "eth", "multiply", "threesuperior", "copyright", "Aacute", "Acircumflex", "Adieresis", "Agrave", "Aring", "Atilde", "Ccedilla", "Eacute", "Ecircumflex", "Edieresis", "Egrave", "Iacute", "Icircumflex", "Idieresis", "Igrave", "Ntilde", "Oacute", "Ocircumflex", "Odieresis", "Ograve", "Otilde", "Scaron", "Uacute", "Ucircumflex", "Udieresis", "Ugrave", "Yacute", "Ydieresis", "Zcaron", "aacute", "acircumflex", "adieresis", "agrave", "aring", "atilde", "ccedilla", "eacute", "ecircumflex", "edieresis", "egrave", "iacute", "icircumflex", "idieresis", "igrave", "ntilde", "oacute", "ocircumflex", "odieresis", "ograve", "otilde", "scaron", "uacute", "ucircumflex", "udieresis", "ugrave", "yacute", "ydieresis", "zcaron", "exclamsmall", "Hungarumlautsmall", "dollaroldstyle", "dollarsuperior", "ampersandsmall", "Acutesmall", "parenleftsuperior", "parenrightsuperior", "twodotenleader", "onedotenleader", "zerooldstyle", "oneoldstyle", "twooldstyle", "threeoldstyle", "fouroldstyle", "fiveoldstyle", "sixoldstyle", "sevenoldstyle", "eightoldstyle", "nineoldstyle", "commasuperior", "threequartersemdash", "periodsuperior", "questionsmall", "asuperior", "bsuperior", "centsuperior", "dsuperior", "esuperior", "isuperior", "lsuperior", "msuperior", "nsuperior", "osuperior", "rsuperior", "ssuperior", "tsuperior", "ff", "ffi", "ffl", "parenleftinferior", "parenrightinferior", "Circumflexsmall", "hyphensuperior", "Gravesmall", "Asmall", "Bsmall", "Csmall", "Dsmall", "Esmall", "Fsmall", "Gsmall", "Hsmall", "Ismall", "Jsmall", "Ksmall", "Lsmall", "Msmall", "Nsmall", "Osmall", "Psmall", "Qsmall", "Rsmall", "Ssmall", "Tsmall", "Usmall", "Vsmall", "Wsmall", "Xsmall", "Ysmall", "Zsmall", "colonmonetary", "onefitted", "rupiah", "Tildesmall", "exclamdownsmall", "centoldstyle", "Lslashsmall", "Scaronsmall", "Zcaronsmall", "Dieresissmall", "Brevesmall", "Caronsmall", "Dotaccentsmall", "Macronsmall", "figuredash", "hypheninferior", "Ogoneksmall", "Ringsmall", "Cedillasmall", "questiondownsmall", "oneeighth", "threeeighths", "fiveeighths", "seveneighths", "onethird", "twothirds", "zerosuperior", "foursuperior", "fivesuperior", "sixsuperior", "sevensuperior", "eightsuperior", "ninesuperior", "zeroinferior", "oneinferior", "twoinferior", "threeinferior", "fourinferior", "fiveinferior", "sixinferior", "seveninferior", "eightinferior", "nineinferior", "centinferior", "dollarinferior", "periodinferior", "commainferior", "Agravesmall", "Aacutesmall", "Acircumflexsmall", "Atildesmall", "Adieresissmall", "Aringsmall", "AEsmall", "Ccedillasmall", "Egravesmall", "Eacutesmall", "Ecircumflexsmall", "Edieresissmall", "Igravesmall", "Iacutesmall", "Icircumflexsmall", "Idieresissmall", "Ethsmall", "Ntildesmall", "Ogravesmall", "Oacutesmall", "Ocircumflexsmall", "Otildesmall", "Odieresissmall", "OEsmall", "Oslashsmall", "Ugravesmall", "Uacutesmall", "Ucircumflexsmall", "Udieresissmall", "Yacutesmall", "Thornsmall", "Ydieresissmall", "001.000", "001.001", "001.002", "001.003", "Black", "Bold", "Book", "Light", "Medium", "Regular", "Roman", "Semibold"];
  32. exports.CFFStandardStrings = CFFStandardStrings;
  33. const NUM_STANDARD_CFF_STRINGS = 391;
  34. const CharstringValidationData = [null, {
  35. id: "hstem",
  36. min: 2,
  37. stackClearing: true,
  38. stem: true
  39. }, null, {
  40. id: "vstem",
  41. min: 2,
  42. stackClearing: true,
  43. stem: true
  44. }, {
  45. id: "vmoveto",
  46. min: 1,
  47. stackClearing: true
  48. }, {
  49. id: "rlineto",
  50. min: 2,
  51. resetStack: true
  52. }, {
  53. id: "hlineto",
  54. min: 1,
  55. resetStack: true
  56. }, {
  57. id: "vlineto",
  58. min: 1,
  59. resetStack: true
  60. }, {
  61. id: "rrcurveto",
  62. min: 6,
  63. resetStack: true
  64. }, null, {
  65. id: "callsubr",
  66. min: 1,
  67. undefStack: true
  68. }, {
  69. id: "return",
  70. min: 0,
  71. undefStack: true
  72. }, null, null, {
  73. id: "endchar",
  74. min: 0,
  75. stackClearing: true
  76. }, null, null, null, {
  77. id: "hstemhm",
  78. min: 2,
  79. stackClearing: true,
  80. stem: true
  81. }, {
  82. id: "hintmask",
  83. min: 0,
  84. stackClearing: true
  85. }, {
  86. id: "cntrmask",
  87. min: 0,
  88. stackClearing: true
  89. }, {
  90. id: "rmoveto",
  91. min: 2,
  92. stackClearing: true
  93. }, {
  94. id: "hmoveto",
  95. min: 1,
  96. stackClearing: true
  97. }, {
  98. id: "vstemhm",
  99. min: 2,
  100. stackClearing: true,
  101. stem: true
  102. }, {
  103. id: "rcurveline",
  104. min: 8,
  105. resetStack: true
  106. }, {
  107. id: "rlinecurve",
  108. min: 8,
  109. resetStack: true
  110. }, {
  111. id: "vvcurveto",
  112. min: 4,
  113. resetStack: true
  114. }, {
  115. id: "hhcurveto",
  116. min: 4,
  117. resetStack: true
  118. }, null, {
  119. id: "callgsubr",
  120. min: 1,
  121. undefStack: true
  122. }, {
  123. id: "vhcurveto",
  124. min: 4,
  125. resetStack: true
  126. }, {
  127. id: "hvcurveto",
  128. min: 4,
  129. resetStack: true
  130. }];
  131. const CharstringValidationData12 = [null, null, null, {
  132. id: "and",
  133. min: 2,
  134. stackDelta: -1
  135. }, {
  136. id: "or",
  137. min: 2,
  138. stackDelta: -1
  139. }, {
  140. id: "not",
  141. min: 1,
  142. stackDelta: 0
  143. }, null, null, null, {
  144. id: "abs",
  145. min: 1,
  146. stackDelta: 0
  147. }, {
  148. id: "add",
  149. min: 2,
  150. stackDelta: -1,
  151. stackFn(stack, index) {
  152. stack[index - 2] = stack[index - 2] + stack[index - 1];
  153. }
  154. }, {
  155. id: "sub",
  156. min: 2,
  157. stackDelta: -1,
  158. stackFn(stack, index) {
  159. stack[index - 2] = stack[index - 2] - stack[index - 1];
  160. }
  161. }, {
  162. id: "div",
  163. min: 2,
  164. stackDelta: -1,
  165. stackFn(stack, index) {
  166. stack[index - 2] = stack[index - 2] / stack[index - 1];
  167. }
  168. }, null, {
  169. id: "neg",
  170. min: 1,
  171. stackDelta: 0,
  172. stackFn(stack, index) {
  173. stack[index - 1] = -stack[index - 1];
  174. }
  175. }, {
  176. id: "eq",
  177. min: 2,
  178. stackDelta: -1
  179. }, null, null, {
  180. id: "drop",
  181. min: 1,
  182. stackDelta: -1
  183. }, null, {
  184. id: "put",
  185. min: 2,
  186. stackDelta: -2
  187. }, {
  188. id: "get",
  189. min: 1,
  190. stackDelta: 0
  191. }, {
  192. id: "ifelse",
  193. min: 4,
  194. stackDelta: -3
  195. }, {
  196. id: "random",
  197. min: 0,
  198. stackDelta: 1
  199. }, {
  200. id: "mul",
  201. min: 2,
  202. stackDelta: -1,
  203. stackFn(stack, index) {
  204. stack[index - 2] = stack[index - 2] * stack[index - 1];
  205. }
  206. }, null, {
  207. id: "sqrt",
  208. min: 1,
  209. stackDelta: 0
  210. }, {
  211. id: "dup",
  212. min: 1,
  213. stackDelta: 1
  214. }, {
  215. id: "exch",
  216. min: 2,
  217. stackDelta: 0
  218. }, {
  219. id: "index",
  220. min: 2,
  221. stackDelta: 0
  222. }, {
  223. id: "roll",
  224. min: 3,
  225. stackDelta: -2
  226. }, null, null, null, {
  227. id: "hflex",
  228. min: 7,
  229. resetStack: true
  230. }, {
  231. id: "flex",
  232. min: 13,
  233. resetStack: true
  234. }, {
  235. id: "hflex1",
  236. min: 9,
  237. resetStack: true
  238. }, {
  239. id: "flex1",
  240. min: 11,
  241. resetStack: true
  242. }];
  243. class CFFParser {
  244. constructor(file, properties, seacAnalysisEnabled) {
  245. this.bytes = file.getBytes();
  246. this.properties = properties;
  247. this.seacAnalysisEnabled = !!seacAnalysisEnabled;
  248. }
  249. parse() {
  250. const properties = this.properties;
  251. const cff = new CFF();
  252. this.cff = cff;
  253. const header = this.parseHeader();
  254. const nameIndex = this.parseIndex(header.endPos);
  255. const topDictIndex = this.parseIndex(nameIndex.endPos);
  256. const stringIndex = this.parseIndex(topDictIndex.endPos);
  257. const globalSubrIndex = this.parseIndex(stringIndex.endPos);
  258. const topDictParsed = this.parseDict(topDictIndex.obj.get(0));
  259. const topDict = this.createDict(CFFTopDict, topDictParsed, cff.strings);
  260. cff.header = header.obj;
  261. cff.names = this.parseNameIndex(nameIndex.obj);
  262. cff.strings = this.parseStringIndex(stringIndex.obj);
  263. cff.topDict = topDict;
  264. cff.globalSubrIndex = globalSubrIndex.obj;
  265. this.parsePrivateDict(cff.topDict);
  266. cff.isCIDFont = topDict.hasName("ROS");
  267. const charStringOffset = topDict.getByName("CharStrings");
  268. const charStringIndex = this.parseIndex(charStringOffset).obj;
  269. const fontMatrix = topDict.getByName("FontMatrix");
  270. if (fontMatrix) {
  271. properties.fontMatrix = fontMatrix;
  272. }
  273. const fontBBox = topDict.getByName("FontBBox");
  274. if (fontBBox) {
  275. properties.ascent = Math.max(fontBBox[3], fontBBox[1]);
  276. properties.descent = Math.min(fontBBox[1], fontBBox[3]);
  277. properties.ascentScaled = true;
  278. }
  279. let charset, encoding;
  280. if (cff.isCIDFont) {
  281. const fdArrayIndex = this.parseIndex(topDict.getByName("FDArray")).obj;
  282. for (let i = 0, ii = fdArrayIndex.count; i < ii; ++i) {
  283. const dictRaw = fdArrayIndex.get(i);
  284. const fontDict = this.createDict(CFFTopDict, this.parseDict(dictRaw), cff.strings);
  285. this.parsePrivateDict(fontDict);
  286. cff.fdArray.push(fontDict);
  287. }
  288. encoding = null;
  289. charset = this.parseCharsets(topDict.getByName("charset"), charStringIndex.count, cff.strings, true);
  290. cff.fdSelect = this.parseFDSelect(topDict.getByName("FDSelect"), charStringIndex.count);
  291. } else {
  292. charset = this.parseCharsets(topDict.getByName("charset"), charStringIndex.count, cff.strings, false);
  293. encoding = this.parseEncoding(topDict.getByName("Encoding"), properties, cff.strings, charset.charset);
  294. }
  295. cff.charset = charset;
  296. cff.encoding = encoding;
  297. const charStringsAndSeacs = this.parseCharStrings({
  298. charStrings: charStringIndex,
  299. localSubrIndex: topDict.privateDict.subrsIndex,
  300. globalSubrIndex: globalSubrIndex.obj,
  301. fdSelect: cff.fdSelect,
  302. fdArray: cff.fdArray,
  303. privateDict: topDict.privateDict
  304. });
  305. cff.charStrings = charStringsAndSeacs.charStrings;
  306. cff.seacs = charStringsAndSeacs.seacs;
  307. cff.widths = charStringsAndSeacs.widths;
  308. return cff;
  309. }
  310. parseHeader() {
  311. let bytes = this.bytes;
  312. const bytesLength = bytes.length;
  313. let offset = 0;
  314. while (offset < bytesLength && bytes[offset] !== 1) {
  315. ++offset;
  316. }
  317. if (offset >= bytesLength) {
  318. throw new _util.FormatError("Invalid CFF header");
  319. }
  320. if (offset !== 0) {
  321. (0, _util.info)("cff data is shifted");
  322. bytes = bytes.subarray(offset);
  323. this.bytes = bytes;
  324. }
  325. const major = bytes[0];
  326. const minor = bytes[1];
  327. const hdrSize = bytes[2];
  328. const offSize = bytes[3];
  329. const header = new CFFHeader(major, minor, hdrSize, offSize);
  330. return {
  331. obj: header,
  332. endPos: hdrSize
  333. };
  334. }
  335. parseDict(dict) {
  336. let pos = 0;
  337. function parseOperand() {
  338. let value = dict[pos++];
  339. if (value === 30) {
  340. return parseFloatOperand();
  341. } else if (value === 28) {
  342. value = dict[pos++];
  343. value = (value << 24 | dict[pos++] << 16) >> 16;
  344. return value;
  345. } else if (value === 29) {
  346. value = dict[pos++];
  347. value = value << 8 | dict[pos++];
  348. value = value << 8 | dict[pos++];
  349. value = value << 8 | dict[pos++];
  350. return value;
  351. } else if (value >= 32 && value <= 246) {
  352. return value - 139;
  353. } else if (value >= 247 && value <= 250) {
  354. return (value - 247) * 256 + dict[pos++] + 108;
  355. } else if (value >= 251 && value <= 254) {
  356. return -((value - 251) * 256) - dict[pos++] - 108;
  357. }
  358. (0, _util.warn)('CFFParser_parseDict: "' + value + '" is a reserved command.');
  359. return NaN;
  360. }
  361. function parseFloatOperand() {
  362. let str = "";
  363. const eof = 15;
  364. const lookup = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", "E", "E-", null, "-"];
  365. const length = dict.length;
  366. while (pos < length) {
  367. const b = dict[pos++];
  368. const b1 = b >> 4;
  369. const b2 = b & 15;
  370. if (b1 === eof) {
  371. break;
  372. }
  373. str += lookup[b1];
  374. if (b2 === eof) {
  375. break;
  376. }
  377. str += lookup[b2];
  378. }
  379. return parseFloat(str);
  380. }
  381. let operands = [];
  382. const entries = [];
  383. pos = 0;
  384. const end = dict.length;
  385. while (pos < end) {
  386. let b = dict[pos];
  387. if (b <= 21) {
  388. if (b === 12) {
  389. b = b << 8 | dict[++pos];
  390. }
  391. entries.push([b, operands]);
  392. operands = [];
  393. ++pos;
  394. } else {
  395. operands.push(parseOperand());
  396. }
  397. }
  398. return entries;
  399. }
  400. parseIndex(pos) {
  401. const cffIndex = new CFFIndex();
  402. const bytes = this.bytes;
  403. const count = bytes[pos++] << 8 | bytes[pos++];
  404. const offsets = [];
  405. let end = pos;
  406. let i, ii;
  407. if (count !== 0) {
  408. const offsetSize = bytes[pos++];
  409. const startPos = pos + (count + 1) * offsetSize - 1;
  410. for (i = 0, ii = count + 1; i < ii; ++i) {
  411. let offset = 0;
  412. for (let j = 0; j < offsetSize; ++j) {
  413. offset <<= 8;
  414. offset += bytes[pos++];
  415. }
  416. offsets.push(startPos + offset);
  417. }
  418. end = offsets[count];
  419. }
  420. for (i = 0, ii = offsets.length - 1; i < ii; ++i) {
  421. const offsetStart = offsets[i];
  422. const offsetEnd = offsets[i + 1];
  423. cffIndex.add(bytes.subarray(offsetStart, offsetEnd));
  424. }
  425. return {
  426. obj: cffIndex,
  427. endPos: end
  428. };
  429. }
  430. parseNameIndex(index) {
  431. const names = [];
  432. for (let i = 0, ii = index.count; i < ii; ++i) {
  433. const name = index.get(i);
  434. names.push((0, _util.bytesToString)(name));
  435. }
  436. return names;
  437. }
  438. parseStringIndex(index) {
  439. const strings = new CFFStrings();
  440. for (let i = 0, ii = index.count; i < ii; ++i) {
  441. const data = index.get(i);
  442. strings.add((0, _util.bytesToString)(data));
  443. }
  444. return strings;
  445. }
  446. createDict(Type, dict, strings) {
  447. const cffDict = new Type(strings);
  448. for (const [key, value] of dict) {
  449. cffDict.setByKey(key, value);
  450. }
  451. return cffDict;
  452. }
  453. parseCharString(state, data, localSubrIndex, globalSubrIndex) {
  454. if (!data || state.callDepth > MAX_SUBR_NESTING) {
  455. return false;
  456. }
  457. let stackSize = state.stackSize;
  458. const stack = state.stack;
  459. const length = data.length;
  460. for (let j = 0; j < length;) {
  461. const value = data[j++];
  462. let validationCommand = null;
  463. if (value === 12) {
  464. const q = data[j++];
  465. if (q === 0) {
  466. data[j - 2] = 139;
  467. data[j - 1] = 22;
  468. stackSize = 0;
  469. } else {
  470. validationCommand = CharstringValidationData12[q];
  471. }
  472. } else if (value === 28) {
  473. stack[stackSize] = (data[j] << 24 | data[j + 1] << 16) >> 16;
  474. j += 2;
  475. stackSize++;
  476. } else if (value === 14) {
  477. if (stackSize >= 4) {
  478. stackSize -= 4;
  479. if (this.seacAnalysisEnabled) {
  480. state.seac = stack.slice(stackSize, stackSize + 4);
  481. return false;
  482. }
  483. }
  484. validationCommand = CharstringValidationData[value];
  485. } else if (value >= 32 && value <= 246) {
  486. stack[stackSize] = value - 139;
  487. stackSize++;
  488. } else if (value >= 247 && value <= 254) {
  489. stack[stackSize] = value < 251 ? (value - 247 << 8) + data[j] + 108 : -(value - 251 << 8) - data[j] - 108;
  490. j++;
  491. stackSize++;
  492. } else if (value === 255) {
  493. stack[stackSize] = (data[j] << 24 | data[j + 1] << 16 | data[j + 2] << 8 | data[j + 3]) / 65536;
  494. j += 4;
  495. stackSize++;
  496. } else if (value === 19 || value === 20) {
  497. state.hints += stackSize >> 1;
  498. j += state.hints + 7 >> 3;
  499. stackSize %= 2;
  500. validationCommand = CharstringValidationData[value];
  501. } else if (value === 10 || value === 29) {
  502. let subrsIndex;
  503. if (value === 10) {
  504. subrsIndex = localSubrIndex;
  505. } else {
  506. subrsIndex = globalSubrIndex;
  507. }
  508. if (!subrsIndex) {
  509. validationCommand = CharstringValidationData[value];
  510. (0, _util.warn)("Missing subrsIndex for " + validationCommand.id);
  511. return false;
  512. }
  513. let bias = 32768;
  514. if (subrsIndex.count < 1240) {
  515. bias = 107;
  516. } else if (subrsIndex.count < 33900) {
  517. bias = 1131;
  518. }
  519. const subrNumber = stack[--stackSize] + bias;
  520. if (subrNumber < 0 || subrNumber >= subrsIndex.count || isNaN(subrNumber)) {
  521. validationCommand = CharstringValidationData[value];
  522. (0, _util.warn)("Out of bounds subrIndex for " + validationCommand.id);
  523. return false;
  524. }
  525. state.stackSize = stackSize;
  526. state.callDepth++;
  527. const valid = this.parseCharString(state, subrsIndex.get(subrNumber), localSubrIndex, globalSubrIndex);
  528. if (!valid) {
  529. return false;
  530. }
  531. state.callDepth--;
  532. stackSize = state.stackSize;
  533. continue;
  534. } else if (value === 11) {
  535. state.stackSize = stackSize;
  536. return true;
  537. } else if (value === 0 && j === data.length) {
  538. data[j - 1] = 14;
  539. validationCommand = CharstringValidationData[14];
  540. } else {
  541. validationCommand = CharstringValidationData[value];
  542. }
  543. if (validationCommand) {
  544. if (validationCommand.stem) {
  545. state.hints += stackSize >> 1;
  546. if (value === 3 || value === 23) {
  547. state.hasVStems = true;
  548. } else if (state.hasVStems && (value === 1 || value === 18)) {
  549. (0, _util.warn)("CFF stem hints are in wrong order");
  550. data[j - 1] = value === 1 ? 3 : 23;
  551. }
  552. }
  553. if ("min" in validationCommand) {
  554. if (!state.undefStack && stackSize < validationCommand.min) {
  555. (0, _util.warn)("Not enough parameters for " + validationCommand.id + "; actual: " + stackSize + ", expected: " + validationCommand.min);
  556. if (stackSize === 0) {
  557. data[j - 1] = 14;
  558. return true;
  559. }
  560. return false;
  561. }
  562. }
  563. if (state.firstStackClearing && validationCommand.stackClearing) {
  564. state.firstStackClearing = false;
  565. stackSize -= validationCommand.min;
  566. if (stackSize >= 2 && validationCommand.stem) {
  567. stackSize %= 2;
  568. } else if (stackSize > 1) {
  569. (0, _util.warn)("Found too many parameters for stack-clearing command");
  570. }
  571. if (stackSize > 0) {
  572. state.width = stack[stackSize - 1];
  573. }
  574. }
  575. if ("stackDelta" in validationCommand) {
  576. if ("stackFn" in validationCommand) {
  577. validationCommand.stackFn(stack, stackSize);
  578. }
  579. stackSize += validationCommand.stackDelta;
  580. } else if (validationCommand.stackClearing) {
  581. stackSize = 0;
  582. } else if (validationCommand.resetStack) {
  583. stackSize = 0;
  584. state.undefStack = false;
  585. } else if (validationCommand.undefStack) {
  586. stackSize = 0;
  587. state.undefStack = true;
  588. state.firstStackClearing = false;
  589. }
  590. }
  591. }
  592. state.stackSize = stackSize;
  593. return true;
  594. }
  595. parseCharStrings({
  596. charStrings,
  597. localSubrIndex,
  598. globalSubrIndex,
  599. fdSelect,
  600. fdArray,
  601. privateDict
  602. }) {
  603. const seacs = [];
  604. const widths = [];
  605. const count = charStrings.count;
  606. for (let i = 0; i < count; i++) {
  607. const charstring = charStrings.get(i);
  608. const state = {
  609. callDepth: 0,
  610. stackSize: 0,
  611. stack: [],
  612. undefStack: true,
  613. hints: 0,
  614. firstStackClearing: true,
  615. seac: null,
  616. width: null,
  617. hasVStems: false
  618. };
  619. let valid = true;
  620. let localSubrToUse = null;
  621. let privateDictToUse = privateDict;
  622. if (fdSelect && fdArray.length) {
  623. const fdIndex = fdSelect.getFDIndex(i);
  624. if (fdIndex === -1) {
  625. (0, _util.warn)("Glyph index is not in fd select.");
  626. valid = false;
  627. }
  628. if (fdIndex >= fdArray.length) {
  629. (0, _util.warn)("Invalid fd index for glyph index.");
  630. valid = false;
  631. }
  632. if (valid) {
  633. privateDictToUse = fdArray[fdIndex].privateDict;
  634. localSubrToUse = privateDictToUse.subrsIndex;
  635. }
  636. } else if (localSubrIndex) {
  637. localSubrToUse = localSubrIndex;
  638. }
  639. if (valid) {
  640. valid = this.parseCharString(state, charstring, localSubrToUse, globalSubrIndex);
  641. }
  642. if (state.width !== null) {
  643. const nominalWidth = privateDictToUse.getByName("nominalWidthX");
  644. widths[i] = nominalWidth + state.width;
  645. } else {
  646. const defaultWidth = privateDictToUse.getByName("defaultWidthX");
  647. widths[i] = defaultWidth;
  648. }
  649. if (state.seac !== null) {
  650. seacs[i] = state.seac;
  651. }
  652. if (!valid) {
  653. charStrings.set(i, new Uint8Array([14]));
  654. }
  655. }
  656. return {
  657. charStrings,
  658. seacs,
  659. widths
  660. };
  661. }
  662. emptyPrivateDictionary(parentDict) {
  663. const privateDict = this.createDict(CFFPrivateDict, [], parentDict.strings);
  664. parentDict.setByKey(18, [0, 0]);
  665. parentDict.privateDict = privateDict;
  666. }
  667. parsePrivateDict(parentDict) {
  668. if (!parentDict.hasName("Private")) {
  669. this.emptyPrivateDictionary(parentDict);
  670. return;
  671. }
  672. const privateOffset = parentDict.getByName("Private");
  673. if (!Array.isArray(privateOffset) || privateOffset.length !== 2) {
  674. parentDict.removeByName("Private");
  675. return;
  676. }
  677. const size = privateOffset[0];
  678. const offset = privateOffset[1];
  679. if (size === 0 || offset >= this.bytes.length) {
  680. this.emptyPrivateDictionary(parentDict);
  681. return;
  682. }
  683. const privateDictEnd = offset + size;
  684. const dictData = this.bytes.subarray(offset, privateDictEnd);
  685. const dict = this.parseDict(dictData);
  686. const privateDict = this.createDict(CFFPrivateDict, dict, parentDict.strings);
  687. parentDict.privateDict = privateDict;
  688. if (!privateDict.getByName("Subrs")) {
  689. return;
  690. }
  691. const subrsOffset = privateDict.getByName("Subrs");
  692. const relativeOffset = offset + subrsOffset;
  693. if (subrsOffset === 0 || relativeOffset >= this.bytes.length) {
  694. this.emptyPrivateDictionary(parentDict);
  695. return;
  696. }
  697. const subrsIndex = this.parseIndex(relativeOffset);
  698. privateDict.subrsIndex = subrsIndex.obj;
  699. }
  700. parseCharsets(pos, length, strings, cid) {
  701. if (pos === 0) {
  702. return new CFFCharset(true, CFFCharsetPredefinedTypes.ISO_ADOBE, _charsets.ISOAdobeCharset);
  703. } else if (pos === 1) {
  704. return new CFFCharset(true, CFFCharsetPredefinedTypes.EXPERT, _charsets.ExpertCharset);
  705. } else if (pos === 2) {
  706. return new CFFCharset(true, CFFCharsetPredefinedTypes.EXPERT_SUBSET, _charsets.ExpertSubsetCharset);
  707. }
  708. const bytes = this.bytes;
  709. const start = pos;
  710. const format = bytes[pos++];
  711. const charset = [cid ? 0 : ".notdef"];
  712. let id, count, i;
  713. length -= 1;
  714. switch (format) {
  715. case 0:
  716. for (i = 0; i < length; i++) {
  717. id = bytes[pos++] << 8 | bytes[pos++];
  718. charset.push(cid ? id : strings.get(id));
  719. }
  720. break;
  721. case 1:
  722. while (charset.length <= length) {
  723. id = bytes[pos++] << 8 | bytes[pos++];
  724. count = bytes[pos++];
  725. for (i = 0; i <= count; i++) {
  726. charset.push(cid ? id++ : strings.get(id++));
  727. }
  728. }
  729. break;
  730. case 2:
  731. while (charset.length <= length) {
  732. id = bytes[pos++] << 8 | bytes[pos++];
  733. count = bytes[pos++] << 8 | bytes[pos++];
  734. for (i = 0; i <= count; i++) {
  735. charset.push(cid ? id++ : strings.get(id++));
  736. }
  737. }
  738. break;
  739. default:
  740. throw new _util.FormatError("Unknown charset format");
  741. }
  742. const end = pos;
  743. const raw = bytes.subarray(start, end);
  744. return new CFFCharset(false, format, charset, raw);
  745. }
  746. parseEncoding(pos, properties, strings, charset) {
  747. const encoding = Object.create(null);
  748. const bytes = this.bytes;
  749. let predefined = false;
  750. let format, i, ii;
  751. let raw = null;
  752. function readSupplement() {
  753. const supplementsCount = bytes[pos++];
  754. for (i = 0; i < supplementsCount; i++) {
  755. const code = bytes[pos++];
  756. const sid = (bytes[pos++] << 8) + (bytes[pos++] & 0xff);
  757. encoding[code] = charset.indexOf(strings.get(sid));
  758. }
  759. }
  760. if (pos === 0 || pos === 1) {
  761. predefined = true;
  762. format = pos;
  763. const baseEncoding = pos ? _encodings.ExpertEncoding : _encodings.StandardEncoding;
  764. for (i = 0, ii = charset.length; i < ii; i++) {
  765. const index = baseEncoding.indexOf(charset[i]);
  766. if (index !== -1) {
  767. encoding[index] = i;
  768. }
  769. }
  770. } else {
  771. const dataStart = pos;
  772. format = bytes[pos++];
  773. switch (format & 0x7f) {
  774. case 0:
  775. const glyphsCount = bytes[pos++];
  776. for (i = 1; i <= glyphsCount; i++) {
  777. encoding[bytes[pos++]] = i;
  778. }
  779. break;
  780. case 1:
  781. const rangesCount = bytes[pos++];
  782. let gid = 1;
  783. for (i = 0; i < rangesCount; i++) {
  784. const start = bytes[pos++];
  785. const left = bytes[pos++];
  786. for (let j = start; j <= start + left; j++) {
  787. encoding[j] = gid++;
  788. }
  789. }
  790. break;
  791. default:
  792. throw new _util.FormatError(`Unknown encoding format: ${format} in CFF`);
  793. }
  794. const dataEnd = pos;
  795. if (format & 0x80) {
  796. bytes[dataStart] &= 0x7f;
  797. readSupplement();
  798. }
  799. raw = bytes.subarray(dataStart, dataEnd);
  800. }
  801. format &= 0x7f;
  802. return new CFFEncoding(predefined, format, encoding, raw);
  803. }
  804. parseFDSelect(pos, length) {
  805. const bytes = this.bytes;
  806. const format = bytes[pos++];
  807. const fdSelect = [];
  808. let i;
  809. switch (format) {
  810. case 0:
  811. for (i = 0; i < length; ++i) {
  812. const id = bytes[pos++];
  813. fdSelect.push(id);
  814. }
  815. break;
  816. case 3:
  817. const rangesCount = bytes[pos++] << 8 | bytes[pos++];
  818. for (i = 0; i < rangesCount; ++i) {
  819. let first = bytes[pos++] << 8 | bytes[pos++];
  820. if (i === 0 && first !== 0) {
  821. (0, _util.warn)("parseFDSelect: The first range must have a first GID of 0" + " -- trying to recover.");
  822. first = 0;
  823. }
  824. const fdIndex = bytes[pos++];
  825. const next = bytes[pos] << 8 | bytes[pos + 1];
  826. for (let j = first; j < next; ++j) {
  827. fdSelect.push(fdIndex);
  828. }
  829. }
  830. pos += 2;
  831. break;
  832. default:
  833. throw new _util.FormatError(`parseFDSelect: Unknown format "${format}".`);
  834. }
  835. if (fdSelect.length !== length) {
  836. throw new _util.FormatError("parseFDSelect: Invalid font data.");
  837. }
  838. return new CFFFDSelect(format, fdSelect);
  839. }
  840. }
  841. exports.CFFParser = CFFParser;
  842. class CFF {
  843. constructor() {
  844. this.header = null;
  845. this.names = [];
  846. this.topDict = null;
  847. this.strings = new CFFStrings();
  848. this.globalSubrIndex = null;
  849. this.encoding = null;
  850. this.charset = null;
  851. this.charStrings = null;
  852. this.fdArray = [];
  853. this.fdSelect = null;
  854. this.isCIDFont = false;
  855. }
  856. duplicateFirstGlyph() {
  857. if (this.charStrings.count >= 65535) {
  858. (0, _util.warn)("Not enough space in charstrings to duplicate first glyph.");
  859. return;
  860. }
  861. const glyphZero = this.charStrings.get(0);
  862. this.charStrings.add(glyphZero);
  863. if (this.isCIDFont) {
  864. this.fdSelect.fdSelect.push(this.fdSelect.fdSelect[0]);
  865. }
  866. }
  867. hasGlyphId(id) {
  868. if (id < 0 || id >= this.charStrings.count) {
  869. return false;
  870. }
  871. const glyph = this.charStrings.get(id);
  872. return glyph.length > 0;
  873. }
  874. }
  875. exports.CFF = CFF;
  876. class CFFHeader {
  877. constructor(major, minor, hdrSize, offSize) {
  878. this.major = major;
  879. this.minor = minor;
  880. this.hdrSize = hdrSize;
  881. this.offSize = offSize;
  882. }
  883. }
  884. exports.CFFHeader = CFFHeader;
  885. class CFFStrings {
  886. constructor() {
  887. this.strings = [];
  888. }
  889. get(index) {
  890. if (index >= 0 && index <= NUM_STANDARD_CFF_STRINGS - 1) {
  891. return CFFStandardStrings[index];
  892. }
  893. if (index - NUM_STANDARD_CFF_STRINGS <= this.strings.length) {
  894. return this.strings[index - NUM_STANDARD_CFF_STRINGS];
  895. }
  896. return CFFStandardStrings[0];
  897. }
  898. getSID(str) {
  899. let index = CFFStandardStrings.indexOf(str);
  900. if (index !== -1) {
  901. return index;
  902. }
  903. index = this.strings.indexOf(str);
  904. if (index !== -1) {
  905. return index + NUM_STANDARD_CFF_STRINGS;
  906. }
  907. return -1;
  908. }
  909. add(value) {
  910. this.strings.push(value);
  911. }
  912. get count() {
  913. return this.strings.length;
  914. }
  915. }
  916. exports.CFFStrings = CFFStrings;
  917. class CFFIndex {
  918. constructor() {
  919. this.objects = [];
  920. this.length = 0;
  921. }
  922. add(data) {
  923. this.length += data.length;
  924. this.objects.push(data);
  925. }
  926. set(index, data) {
  927. this.length += data.length - this.objects[index].length;
  928. this.objects[index] = data;
  929. }
  930. get(index) {
  931. return this.objects[index];
  932. }
  933. get count() {
  934. return this.objects.length;
  935. }
  936. }
  937. exports.CFFIndex = CFFIndex;
  938. class CFFDict {
  939. constructor(tables, strings) {
  940. this.keyToNameMap = tables.keyToNameMap;
  941. this.nameToKeyMap = tables.nameToKeyMap;
  942. this.defaults = tables.defaults;
  943. this.types = tables.types;
  944. this.opcodes = tables.opcodes;
  945. this.order = tables.order;
  946. this.strings = strings;
  947. this.values = Object.create(null);
  948. }
  949. setByKey(key, value) {
  950. if (!(key in this.keyToNameMap)) {
  951. return false;
  952. }
  953. if (value.length === 0) {
  954. return true;
  955. }
  956. for (const val of value) {
  957. if (isNaN(val)) {
  958. (0, _util.warn)(`Invalid CFFDict value: "${value}" for key "${key}".`);
  959. return true;
  960. }
  961. }
  962. const type = this.types[key];
  963. if (type === "num" || type === "sid" || type === "offset") {
  964. value = value[0];
  965. }
  966. this.values[key] = value;
  967. return true;
  968. }
  969. setByName(name, value) {
  970. if (!(name in this.nameToKeyMap)) {
  971. throw new _util.FormatError(`Invalid dictionary name "${name}"`);
  972. }
  973. this.values[this.nameToKeyMap[name]] = value;
  974. }
  975. hasName(name) {
  976. return this.nameToKeyMap[name] in this.values;
  977. }
  978. getByName(name) {
  979. if (!(name in this.nameToKeyMap)) {
  980. throw new _util.FormatError(`Invalid dictionary name ${name}"`);
  981. }
  982. const key = this.nameToKeyMap[name];
  983. if (!(key in this.values)) {
  984. return this.defaults[key];
  985. }
  986. return this.values[key];
  987. }
  988. removeByName(name) {
  989. delete this.values[this.nameToKeyMap[name]];
  990. }
  991. static createTables(layout) {
  992. const tables = {
  993. keyToNameMap: {},
  994. nameToKeyMap: {},
  995. defaults: {},
  996. types: {},
  997. opcodes: {},
  998. order: []
  999. };
  1000. for (const entry of layout) {
  1001. const key = Array.isArray(entry[0]) ? (entry[0][0] << 8) + entry[0][1] : entry[0];
  1002. tables.keyToNameMap[key] = entry[1];
  1003. tables.nameToKeyMap[entry[1]] = key;
  1004. tables.types[key] = entry[2];
  1005. tables.defaults[key] = entry[3];
  1006. tables.opcodes[key] = Array.isArray(entry[0]) ? entry[0] : [entry[0]];
  1007. tables.order.push(key);
  1008. }
  1009. return tables;
  1010. }
  1011. }
  1012. const CFFTopDictLayout = [[[12, 30], "ROS", ["sid", "sid", "num"], null], [[12, 20], "SyntheticBase", "num", null], [0, "version", "sid", null], [1, "Notice", "sid", null], [[12, 0], "Copyright", "sid", null], [2, "FullName", "sid", null], [3, "FamilyName", "sid", null], [4, "Weight", "sid", null], [[12, 1], "isFixedPitch", "num", 0], [[12, 2], "ItalicAngle", "num", 0], [[12, 3], "UnderlinePosition", "num", -100], [[12, 4], "UnderlineThickness", "num", 50], [[12, 5], "PaintType", "num", 0], [[12, 6], "CharstringType", "num", 2], [[12, 7], "FontMatrix", ["num", "num", "num", "num", "num", "num"], [0.001, 0, 0, 0.001, 0, 0]], [13, "UniqueID", "num", null], [5, "FontBBox", ["num", "num", "num", "num"], [0, 0, 0, 0]], [[12, 8], "StrokeWidth", "num", 0], [14, "XUID", "array", null], [15, "charset", "offset", 0], [16, "Encoding", "offset", 0], [17, "CharStrings", "offset", 0], [18, "Private", ["offset", "offset"], null], [[12, 21], "PostScript", "sid", null], [[12, 22], "BaseFontName", "sid", null], [[12, 23], "BaseFontBlend", "delta", null], [[12, 31], "CIDFontVersion", "num", 0], [[12, 32], "CIDFontRevision", "num", 0], [[12, 33], "CIDFontType", "num", 0], [[12, 34], "CIDCount", "num", 8720], [[12, 35], "UIDBase", "num", null], [[12, 37], "FDSelect", "offset", null], [[12, 36], "FDArray", "offset", null], [[12, 38], "FontName", "sid", null]];
  1013. class CFFTopDict extends CFFDict {
  1014. static get tables() {
  1015. return (0, _util.shadow)(this, "tables", this.createTables(CFFTopDictLayout));
  1016. }
  1017. constructor(strings) {
  1018. super(CFFTopDict.tables, strings);
  1019. this.privateDict = null;
  1020. }
  1021. }
  1022. exports.CFFTopDict = CFFTopDict;
  1023. const CFFPrivateDictLayout = [[6, "BlueValues", "delta", null], [7, "OtherBlues", "delta", null], [8, "FamilyBlues", "delta", null], [9, "FamilyOtherBlues", "delta", null], [[12, 9], "BlueScale", "num", 0.039625], [[12, 10], "BlueShift", "num", 7], [[12, 11], "BlueFuzz", "num", 1], [10, "StdHW", "num", null], [11, "StdVW", "num", null], [[12, 12], "StemSnapH", "delta", null], [[12, 13], "StemSnapV", "delta", null], [[12, 14], "ForceBold", "num", 0], [[12, 17], "LanguageGroup", "num", 0], [[12, 18], "ExpansionFactor", "num", 0.06], [[12, 19], "initialRandomSeed", "num", 0], [20, "defaultWidthX", "num", 0], [21, "nominalWidthX", "num", 0], [19, "Subrs", "offset", null]];
  1024. class CFFPrivateDict extends CFFDict {
  1025. static get tables() {
  1026. return (0, _util.shadow)(this, "tables", this.createTables(CFFPrivateDictLayout));
  1027. }
  1028. constructor(strings) {
  1029. super(CFFPrivateDict.tables, strings);
  1030. this.subrsIndex = null;
  1031. }
  1032. }
  1033. exports.CFFPrivateDict = CFFPrivateDict;
  1034. const CFFCharsetPredefinedTypes = {
  1035. ISO_ADOBE: 0,
  1036. EXPERT: 1,
  1037. EXPERT_SUBSET: 2
  1038. };
  1039. class CFFCharset {
  1040. constructor(predefined, format, charset, raw) {
  1041. this.predefined = predefined;
  1042. this.format = format;
  1043. this.charset = charset;
  1044. this.raw = raw;
  1045. }
  1046. }
  1047. exports.CFFCharset = CFFCharset;
  1048. class CFFEncoding {
  1049. constructor(predefined, format, encoding, raw) {
  1050. this.predefined = predefined;
  1051. this.format = format;
  1052. this.encoding = encoding;
  1053. this.raw = raw;
  1054. }
  1055. }
  1056. class CFFFDSelect {
  1057. constructor(format, fdSelect) {
  1058. this.format = format;
  1059. this.fdSelect = fdSelect;
  1060. }
  1061. getFDIndex(glyphIndex) {
  1062. if (glyphIndex < 0 || glyphIndex >= this.fdSelect.length) {
  1063. return -1;
  1064. }
  1065. return this.fdSelect[glyphIndex];
  1066. }
  1067. }
  1068. exports.CFFFDSelect = CFFFDSelect;
  1069. class CFFOffsetTracker {
  1070. constructor() {
  1071. this.offsets = Object.create(null);
  1072. }
  1073. isTracking(key) {
  1074. return key in this.offsets;
  1075. }
  1076. track(key, location) {
  1077. if (key in this.offsets) {
  1078. throw new _util.FormatError(`Already tracking location of ${key}`);
  1079. }
  1080. this.offsets[key] = location;
  1081. }
  1082. offset(value) {
  1083. for (const key in this.offsets) {
  1084. this.offsets[key] += value;
  1085. }
  1086. }
  1087. setEntryLocation(key, values, output) {
  1088. if (!(key in this.offsets)) {
  1089. throw new _util.FormatError(`Not tracking location of ${key}`);
  1090. }
  1091. const data = output.data;
  1092. const dataOffset = this.offsets[key];
  1093. const size = 5;
  1094. for (let i = 0, ii = values.length; i < ii; ++i) {
  1095. const offset0 = i * size + dataOffset;
  1096. const offset1 = offset0 + 1;
  1097. const offset2 = offset0 + 2;
  1098. const offset3 = offset0 + 3;
  1099. const offset4 = offset0 + 4;
  1100. if (data[offset0] !== 0x1d || data[offset1] !== 0 || data[offset2] !== 0 || data[offset3] !== 0 || data[offset4] !== 0) {
  1101. throw new _util.FormatError("writing to an offset that is not empty");
  1102. }
  1103. const value = values[i];
  1104. data[offset0] = 0x1d;
  1105. data[offset1] = value >> 24 & 0xff;
  1106. data[offset2] = value >> 16 & 0xff;
  1107. data[offset3] = value >> 8 & 0xff;
  1108. data[offset4] = value & 0xff;
  1109. }
  1110. }
  1111. }
  1112. class CFFCompiler {
  1113. constructor(cff) {
  1114. this.cff = cff;
  1115. }
  1116. compile() {
  1117. const cff = this.cff;
  1118. const output = {
  1119. data: [],
  1120. length: 0,
  1121. add(data) {
  1122. this.data = this.data.concat(data);
  1123. this.length = this.data.length;
  1124. }
  1125. };
  1126. const header = this.compileHeader(cff.header);
  1127. output.add(header);
  1128. const nameIndex = this.compileNameIndex(cff.names);
  1129. output.add(nameIndex);
  1130. if (cff.isCIDFont) {
  1131. if (cff.topDict.hasName("FontMatrix")) {
  1132. const base = cff.topDict.getByName("FontMatrix");
  1133. cff.topDict.removeByName("FontMatrix");
  1134. for (const subDict of cff.fdArray) {
  1135. let matrix = base.slice(0);
  1136. if (subDict.hasName("FontMatrix")) {
  1137. matrix = _util.Util.transform(matrix, subDict.getByName("FontMatrix"));
  1138. }
  1139. subDict.setByName("FontMatrix", matrix);
  1140. }
  1141. }
  1142. }
  1143. const xuid = cff.topDict.getByName("XUID");
  1144. if (xuid && xuid.length > 16) {
  1145. cff.topDict.removeByName("XUID");
  1146. }
  1147. cff.topDict.setByName("charset", 0);
  1148. let compiled = this.compileTopDicts([cff.topDict], output.length, cff.isCIDFont);
  1149. output.add(compiled.output);
  1150. const topDictTracker = compiled.trackers[0];
  1151. const stringIndex = this.compileStringIndex(cff.strings.strings);
  1152. output.add(stringIndex);
  1153. const globalSubrIndex = this.compileIndex(cff.globalSubrIndex);
  1154. output.add(globalSubrIndex);
  1155. if (cff.encoding && cff.topDict.hasName("Encoding")) {
  1156. if (cff.encoding.predefined) {
  1157. topDictTracker.setEntryLocation("Encoding", [cff.encoding.format], output);
  1158. } else {
  1159. const encoding = this.compileEncoding(cff.encoding);
  1160. topDictTracker.setEntryLocation("Encoding", [output.length], output);
  1161. output.add(encoding);
  1162. }
  1163. }
  1164. const charset = this.compileCharset(cff.charset, cff.charStrings.count, cff.strings, cff.isCIDFont);
  1165. topDictTracker.setEntryLocation("charset", [output.length], output);
  1166. output.add(charset);
  1167. const charStrings = this.compileCharStrings(cff.charStrings);
  1168. topDictTracker.setEntryLocation("CharStrings", [output.length], output);
  1169. output.add(charStrings);
  1170. if (cff.isCIDFont) {
  1171. topDictTracker.setEntryLocation("FDSelect", [output.length], output);
  1172. const fdSelect = this.compileFDSelect(cff.fdSelect);
  1173. output.add(fdSelect);
  1174. compiled = this.compileTopDicts(cff.fdArray, output.length, true);
  1175. topDictTracker.setEntryLocation("FDArray", [output.length], output);
  1176. output.add(compiled.output);
  1177. const fontDictTrackers = compiled.trackers;
  1178. this.compilePrivateDicts(cff.fdArray, fontDictTrackers, output);
  1179. }
  1180. this.compilePrivateDicts([cff.topDict], [topDictTracker], output);
  1181. output.add([0]);
  1182. return output.data;
  1183. }
  1184. encodeNumber(value) {
  1185. if (Number.isInteger(value)) {
  1186. return this.encodeInteger(value);
  1187. }
  1188. return this.encodeFloat(value);
  1189. }
  1190. static get EncodeFloatRegExp() {
  1191. return (0, _util.shadow)(this, "EncodeFloatRegExp", /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/);
  1192. }
  1193. encodeFloat(num) {
  1194. let value = num.toString();
  1195. const m = CFFCompiler.EncodeFloatRegExp.exec(value);
  1196. if (m) {
  1197. const epsilon = parseFloat("1e" + ((m[2] ? +m[2] : 0) + m[1].length));
  1198. value = (Math.round(num * epsilon) / epsilon).toString();
  1199. }
  1200. let nibbles = "";
  1201. let i, ii;
  1202. for (i = 0, ii = value.length; i < ii; ++i) {
  1203. const a = value[i];
  1204. if (a === "e") {
  1205. nibbles += value[++i] === "-" ? "c" : "b";
  1206. } else if (a === ".") {
  1207. nibbles += "a";
  1208. } else if (a === "-") {
  1209. nibbles += "e";
  1210. } else {
  1211. nibbles += a;
  1212. }
  1213. }
  1214. nibbles += nibbles.length & 1 ? "f" : "ff";
  1215. const out = [30];
  1216. for (i = 0, ii = nibbles.length; i < ii; i += 2) {
  1217. out.push(parseInt(nibbles.substring(i, i + 2), 16));
  1218. }
  1219. return out;
  1220. }
  1221. encodeInteger(value) {
  1222. let code;
  1223. if (value >= -107 && value <= 107) {
  1224. code = [value + 139];
  1225. } else if (value >= 108 && value <= 1131) {
  1226. value -= 108;
  1227. code = [(value >> 8) + 247, value & 0xff];
  1228. } else if (value >= -1131 && value <= -108) {
  1229. value = -value - 108;
  1230. code = [(value >> 8) + 251, value & 0xff];
  1231. } else if (value >= -32768 && value <= 32767) {
  1232. code = [0x1c, value >> 8 & 0xff, value & 0xff];
  1233. } else {
  1234. code = [0x1d, value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff];
  1235. }
  1236. return code;
  1237. }
  1238. compileHeader(header) {
  1239. return [header.major, header.minor, 4, header.offSize];
  1240. }
  1241. compileNameIndex(names) {
  1242. const nameIndex = new CFFIndex();
  1243. for (const name of names) {
  1244. const length = Math.min(name.length, 127);
  1245. let sanitizedName = new Array(length);
  1246. for (let j = 0; j < length; j++) {
  1247. let char = name[j];
  1248. if (char < "!" || char > "~" || char === "[" || char === "]" || char === "(" || char === ")" || char === "{" || char === "}" || char === "<" || char === ">" || char === "/" || char === "%") {
  1249. char = "_";
  1250. }
  1251. sanitizedName[j] = char;
  1252. }
  1253. sanitizedName = sanitizedName.join("");
  1254. if (sanitizedName === "") {
  1255. sanitizedName = "Bad_Font_Name";
  1256. }
  1257. nameIndex.add((0, _util.stringToBytes)(sanitizedName));
  1258. }
  1259. return this.compileIndex(nameIndex);
  1260. }
  1261. compileTopDicts(dicts, length, removeCidKeys) {
  1262. const fontDictTrackers = [];
  1263. let fdArrayIndex = new CFFIndex();
  1264. for (const fontDict of dicts) {
  1265. if (removeCidKeys) {
  1266. fontDict.removeByName("CIDFontVersion");
  1267. fontDict.removeByName("CIDFontRevision");
  1268. fontDict.removeByName("CIDFontType");
  1269. fontDict.removeByName("CIDCount");
  1270. fontDict.removeByName("UIDBase");
  1271. }
  1272. const fontDictTracker = new CFFOffsetTracker();
  1273. const fontDictData = this.compileDict(fontDict, fontDictTracker);
  1274. fontDictTrackers.push(fontDictTracker);
  1275. fdArrayIndex.add(fontDictData);
  1276. fontDictTracker.offset(length);
  1277. }
  1278. fdArrayIndex = this.compileIndex(fdArrayIndex, fontDictTrackers);
  1279. return {
  1280. trackers: fontDictTrackers,
  1281. output: fdArrayIndex
  1282. };
  1283. }
  1284. compilePrivateDicts(dicts, trackers, output) {
  1285. for (let i = 0, ii = dicts.length; i < ii; ++i) {
  1286. const fontDict = dicts[i];
  1287. const privateDict = fontDict.privateDict;
  1288. if (!privateDict || !fontDict.hasName("Private")) {
  1289. throw new _util.FormatError("There must be a private dictionary.");
  1290. }
  1291. const privateDictTracker = new CFFOffsetTracker();
  1292. const privateDictData = this.compileDict(privateDict, privateDictTracker);
  1293. let outputLength = output.length;
  1294. privateDictTracker.offset(outputLength);
  1295. if (!privateDictData.length) {
  1296. outputLength = 0;
  1297. }
  1298. trackers[i].setEntryLocation("Private", [privateDictData.length, outputLength], output);
  1299. output.add(privateDictData);
  1300. if (privateDict.subrsIndex && privateDict.hasName("Subrs")) {
  1301. const subrs = this.compileIndex(privateDict.subrsIndex);
  1302. privateDictTracker.setEntryLocation("Subrs", [privateDictData.length], output);
  1303. output.add(subrs);
  1304. }
  1305. }
  1306. }
  1307. compileDict(dict, offsetTracker) {
  1308. const out = [];
  1309. for (const key of dict.order) {
  1310. if (!(key in dict.values)) {
  1311. continue;
  1312. }
  1313. let values = dict.values[key];
  1314. let types = dict.types[key];
  1315. if (!Array.isArray(types)) {
  1316. types = [types];
  1317. }
  1318. if (!Array.isArray(values)) {
  1319. values = [values];
  1320. }
  1321. if (values.length === 0) {
  1322. continue;
  1323. }
  1324. for (let j = 0, jj = types.length; j < jj; ++j) {
  1325. const type = types[j];
  1326. const value = values[j];
  1327. switch (type) {
  1328. case "num":
  1329. case "sid":
  1330. out.push(...this.encodeNumber(value));
  1331. break;
  1332. case "offset":
  1333. const name = dict.keyToNameMap[key];
  1334. if (!offsetTracker.isTracking(name)) {
  1335. offsetTracker.track(name, out.length);
  1336. }
  1337. out.push(0x1d, 0, 0, 0, 0);
  1338. break;
  1339. case "array":
  1340. case "delta":
  1341. out.push(...this.encodeNumber(value));
  1342. for (let k = 1, kk = values.length; k < kk; ++k) {
  1343. out.push(...this.encodeNumber(values[k]));
  1344. }
  1345. break;
  1346. default:
  1347. throw new _util.FormatError(`Unknown data type of ${type}`);
  1348. }
  1349. }
  1350. out.push(...dict.opcodes[key]);
  1351. }
  1352. return out;
  1353. }
  1354. compileStringIndex(strings) {
  1355. const stringIndex = new CFFIndex();
  1356. for (const string of strings) {
  1357. stringIndex.add((0, _util.stringToBytes)(string));
  1358. }
  1359. return this.compileIndex(stringIndex);
  1360. }
  1361. compileGlobalSubrIndex() {
  1362. const globalSubrIndex = this.cff.globalSubrIndex;
  1363. this.out.writeByteArray(this.compileIndex(globalSubrIndex));
  1364. }
  1365. compileCharStrings(charStrings) {
  1366. const charStringsIndex = new CFFIndex();
  1367. for (let i = 0; i < charStrings.count; i++) {
  1368. const glyph = charStrings.get(i);
  1369. if (glyph.length === 0) {
  1370. charStringsIndex.add(new Uint8Array([0x8b, 0x0e]));
  1371. continue;
  1372. }
  1373. charStringsIndex.add(glyph);
  1374. }
  1375. return this.compileIndex(charStringsIndex);
  1376. }
  1377. compileCharset(charset, numGlyphs, strings, isCIDFont) {
  1378. let out;
  1379. const numGlyphsLessNotDef = numGlyphs - 1;
  1380. if (isCIDFont) {
  1381. out = new Uint8Array([2, 0, 0, numGlyphsLessNotDef >> 8 & 0xff, numGlyphsLessNotDef & 0xff]);
  1382. } else {
  1383. const length = 1 + numGlyphsLessNotDef * 2;
  1384. out = new Uint8Array(length);
  1385. out[0] = 0;
  1386. let charsetIndex = 0;
  1387. const numCharsets = charset.charset.length;
  1388. let warned = false;
  1389. for (let i = 1; i < out.length; i += 2) {
  1390. let sid = 0;
  1391. if (charsetIndex < numCharsets) {
  1392. const name = charset.charset[charsetIndex++];
  1393. sid = strings.getSID(name);
  1394. if (sid === -1) {
  1395. sid = 0;
  1396. if (!warned) {
  1397. warned = true;
  1398. (0, _util.warn)(`Couldn't find ${name} in CFF strings`);
  1399. }
  1400. }
  1401. }
  1402. out[i] = sid >> 8 & 0xff;
  1403. out[i + 1] = sid & 0xff;
  1404. }
  1405. }
  1406. return this.compileTypedArray(out);
  1407. }
  1408. compileEncoding(encoding) {
  1409. return this.compileTypedArray(encoding.raw);
  1410. }
  1411. compileFDSelect(fdSelect) {
  1412. const format = fdSelect.format;
  1413. let out, i;
  1414. switch (format) {
  1415. case 0:
  1416. out = new Uint8Array(1 + fdSelect.fdSelect.length);
  1417. out[0] = format;
  1418. for (i = 0; i < fdSelect.fdSelect.length; i++) {
  1419. out[i + 1] = fdSelect.fdSelect[i];
  1420. }
  1421. break;
  1422. case 3:
  1423. const start = 0;
  1424. let lastFD = fdSelect.fdSelect[0];
  1425. const ranges = [format, 0, 0, start >> 8 & 0xff, start & 0xff, lastFD];
  1426. for (i = 1; i < fdSelect.fdSelect.length; i++) {
  1427. const currentFD = fdSelect.fdSelect[i];
  1428. if (currentFD !== lastFD) {
  1429. ranges.push(i >> 8 & 0xff, i & 0xff, currentFD);
  1430. lastFD = currentFD;
  1431. }
  1432. }
  1433. const numRanges = (ranges.length - 3) / 3;
  1434. ranges[1] = numRanges >> 8 & 0xff;
  1435. ranges[2] = numRanges & 0xff;
  1436. ranges.push(i >> 8 & 0xff, i & 0xff);
  1437. out = new Uint8Array(ranges);
  1438. break;
  1439. }
  1440. return this.compileTypedArray(out);
  1441. }
  1442. compileTypedArray(data) {
  1443. const out = [];
  1444. for (let i = 0, ii = data.length; i < ii; ++i) {
  1445. out[i] = data[i];
  1446. }
  1447. return out;
  1448. }
  1449. compileIndex(index, trackers = []) {
  1450. const objects = index.objects;
  1451. const count = objects.length;
  1452. if (count === 0) {
  1453. return [0, 0];
  1454. }
  1455. const data = [count >> 8 & 0xff, count & 0xff];
  1456. let lastOffset = 1,
  1457. i;
  1458. for (i = 0; i < count; ++i) {
  1459. lastOffset += objects[i].length;
  1460. }
  1461. let offsetSize;
  1462. if (lastOffset < 0x100) {
  1463. offsetSize = 1;
  1464. } else if (lastOffset < 0x10000) {
  1465. offsetSize = 2;
  1466. } else if (lastOffset < 0x1000000) {
  1467. offsetSize = 3;
  1468. } else {
  1469. offsetSize = 4;
  1470. }
  1471. data.push(offsetSize);
  1472. let relativeOffset = 1;
  1473. for (i = 0; i < count + 1; i++) {
  1474. if (offsetSize === 1) {
  1475. data.push(relativeOffset & 0xff);
  1476. } else if (offsetSize === 2) {
  1477. data.push(relativeOffset >> 8 & 0xff, relativeOffset & 0xff);
  1478. } else if (offsetSize === 3) {
  1479. data.push(relativeOffset >> 16 & 0xff, relativeOffset >> 8 & 0xff, relativeOffset & 0xff);
  1480. } else {
  1481. data.push(relativeOffset >>> 24 & 0xff, relativeOffset >> 16 & 0xff, relativeOffset >> 8 & 0xff, relativeOffset & 0xff);
  1482. }
  1483. if (objects[i]) {
  1484. relativeOffset += objects[i].length;
  1485. }
  1486. }
  1487. for (i = 0; i < count; i++) {
  1488. if (trackers[i]) {
  1489. trackers[i].offset(data.length);
  1490. }
  1491. data.push(...objects[i]);
  1492. }
  1493. return data;
  1494. }
  1495. }
  1496. exports.CFFCompiler = CFFCompiler;