cff_parser.js 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505
  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. let 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 if (value === 9) {
  541. data.copyWithin(j - 1, j, -1);
  542. j -= 1;
  543. length -= 1;
  544. continue;
  545. } else {
  546. validationCommand = CharstringValidationData[value];
  547. }
  548. if (validationCommand) {
  549. if (validationCommand.stem) {
  550. state.hints += stackSize >> 1;
  551. if (value === 3 || value === 23) {
  552. state.hasVStems = true;
  553. } else if (state.hasVStems && (value === 1 || value === 18)) {
  554. (0, _util.warn)("CFF stem hints are in wrong order");
  555. data[j - 1] = value === 1 ? 3 : 23;
  556. }
  557. }
  558. if ("min" in validationCommand) {
  559. if (!state.undefStack && stackSize < validationCommand.min) {
  560. (0, _util.warn)("Not enough parameters for " + validationCommand.id + "; actual: " + stackSize + ", expected: " + validationCommand.min);
  561. if (stackSize === 0) {
  562. data[j - 1] = 14;
  563. return true;
  564. }
  565. return false;
  566. }
  567. }
  568. if (state.firstStackClearing && validationCommand.stackClearing) {
  569. state.firstStackClearing = false;
  570. stackSize -= validationCommand.min;
  571. if (stackSize >= 2 && validationCommand.stem) {
  572. stackSize %= 2;
  573. } else if (stackSize > 1) {
  574. (0, _util.warn)("Found too many parameters for stack-clearing command");
  575. }
  576. if (stackSize > 0) {
  577. state.width = stack[stackSize - 1];
  578. }
  579. }
  580. if ("stackDelta" in validationCommand) {
  581. if ("stackFn" in validationCommand) {
  582. validationCommand.stackFn(stack, stackSize);
  583. }
  584. stackSize += validationCommand.stackDelta;
  585. } else if (validationCommand.stackClearing) {
  586. stackSize = 0;
  587. } else if (validationCommand.resetStack) {
  588. stackSize = 0;
  589. state.undefStack = false;
  590. } else if (validationCommand.undefStack) {
  591. stackSize = 0;
  592. state.undefStack = true;
  593. state.firstStackClearing = false;
  594. }
  595. }
  596. }
  597. if (length < data.length) {
  598. data.fill(14, length);
  599. }
  600. state.stackSize = stackSize;
  601. return true;
  602. }
  603. parseCharStrings({
  604. charStrings,
  605. localSubrIndex,
  606. globalSubrIndex,
  607. fdSelect,
  608. fdArray,
  609. privateDict
  610. }) {
  611. const seacs = [];
  612. const widths = [];
  613. const count = charStrings.count;
  614. for (let i = 0; i < count; i++) {
  615. const charstring = charStrings.get(i);
  616. const state = {
  617. callDepth: 0,
  618. stackSize: 0,
  619. stack: [],
  620. undefStack: true,
  621. hints: 0,
  622. firstStackClearing: true,
  623. seac: null,
  624. width: null,
  625. hasVStems: false
  626. };
  627. let valid = true;
  628. let localSubrToUse = null;
  629. let privateDictToUse = privateDict;
  630. if (fdSelect && fdArray.length) {
  631. const fdIndex = fdSelect.getFDIndex(i);
  632. if (fdIndex === -1) {
  633. (0, _util.warn)("Glyph index is not in fd select.");
  634. valid = false;
  635. }
  636. if (fdIndex >= fdArray.length) {
  637. (0, _util.warn)("Invalid fd index for glyph index.");
  638. valid = false;
  639. }
  640. if (valid) {
  641. privateDictToUse = fdArray[fdIndex].privateDict;
  642. localSubrToUse = privateDictToUse.subrsIndex;
  643. }
  644. } else if (localSubrIndex) {
  645. localSubrToUse = localSubrIndex;
  646. }
  647. if (valid) {
  648. valid = this.parseCharString(state, charstring, localSubrToUse, globalSubrIndex);
  649. }
  650. if (state.width !== null) {
  651. const nominalWidth = privateDictToUse.getByName("nominalWidthX");
  652. widths[i] = nominalWidth + state.width;
  653. } else {
  654. const defaultWidth = privateDictToUse.getByName("defaultWidthX");
  655. widths[i] = defaultWidth;
  656. }
  657. if (state.seac !== null) {
  658. seacs[i] = state.seac;
  659. }
  660. if (!valid) {
  661. charStrings.set(i, new Uint8Array([14]));
  662. }
  663. }
  664. return {
  665. charStrings,
  666. seacs,
  667. widths
  668. };
  669. }
  670. emptyPrivateDictionary(parentDict) {
  671. const privateDict = this.createDict(CFFPrivateDict, [], parentDict.strings);
  672. parentDict.setByKey(18, [0, 0]);
  673. parentDict.privateDict = privateDict;
  674. }
  675. parsePrivateDict(parentDict) {
  676. if (!parentDict.hasName("Private")) {
  677. this.emptyPrivateDictionary(parentDict);
  678. return;
  679. }
  680. const privateOffset = parentDict.getByName("Private");
  681. if (!Array.isArray(privateOffset) || privateOffset.length !== 2) {
  682. parentDict.removeByName("Private");
  683. return;
  684. }
  685. const size = privateOffset[0];
  686. const offset = privateOffset[1];
  687. if (size === 0 || offset >= this.bytes.length) {
  688. this.emptyPrivateDictionary(parentDict);
  689. return;
  690. }
  691. const privateDictEnd = offset + size;
  692. const dictData = this.bytes.subarray(offset, privateDictEnd);
  693. const dict = this.parseDict(dictData);
  694. const privateDict = this.createDict(CFFPrivateDict, dict, parentDict.strings);
  695. parentDict.privateDict = privateDict;
  696. if (!privateDict.getByName("Subrs")) {
  697. return;
  698. }
  699. const subrsOffset = privateDict.getByName("Subrs");
  700. const relativeOffset = offset + subrsOffset;
  701. if (subrsOffset === 0 || relativeOffset >= this.bytes.length) {
  702. this.emptyPrivateDictionary(parentDict);
  703. return;
  704. }
  705. const subrsIndex = this.parseIndex(relativeOffset);
  706. privateDict.subrsIndex = subrsIndex.obj;
  707. }
  708. parseCharsets(pos, length, strings, cid) {
  709. if (pos === 0) {
  710. return new CFFCharset(true, CFFCharsetPredefinedTypes.ISO_ADOBE, _charsets.ISOAdobeCharset);
  711. } else if (pos === 1) {
  712. return new CFFCharset(true, CFFCharsetPredefinedTypes.EXPERT, _charsets.ExpertCharset);
  713. } else if (pos === 2) {
  714. return new CFFCharset(true, CFFCharsetPredefinedTypes.EXPERT_SUBSET, _charsets.ExpertSubsetCharset);
  715. }
  716. const bytes = this.bytes;
  717. const start = pos;
  718. const format = bytes[pos++];
  719. const charset = [cid ? 0 : ".notdef"];
  720. let id, count, i;
  721. length -= 1;
  722. switch (format) {
  723. case 0:
  724. for (i = 0; i < length; i++) {
  725. id = bytes[pos++] << 8 | bytes[pos++];
  726. charset.push(cid ? id : strings.get(id));
  727. }
  728. break;
  729. case 1:
  730. while (charset.length <= length) {
  731. id = bytes[pos++] << 8 | bytes[pos++];
  732. count = bytes[pos++];
  733. for (i = 0; i <= count; i++) {
  734. charset.push(cid ? id++ : strings.get(id++));
  735. }
  736. }
  737. break;
  738. case 2:
  739. while (charset.length <= length) {
  740. id = bytes[pos++] << 8 | bytes[pos++];
  741. count = bytes[pos++] << 8 | bytes[pos++];
  742. for (i = 0; i <= count; i++) {
  743. charset.push(cid ? id++ : strings.get(id++));
  744. }
  745. }
  746. break;
  747. default:
  748. throw new _util.FormatError("Unknown charset format");
  749. }
  750. const end = pos;
  751. const raw = bytes.subarray(start, end);
  752. return new CFFCharset(false, format, charset, raw);
  753. }
  754. parseEncoding(pos, properties, strings, charset) {
  755. const encoding = Object.create(null);
  756. const bytes = this.bytes;
  757. let predefined = false;
  758. let format, i, ii;
  759. let raw = null;
  760. function readSupplement() {
  761. const supplementsCount = bytes[pos++];
  762. for (i = 0; i < supplementsCount; i++) {
  763. const code = bytes[pos++];
  764. const sid = (bytes[pos++] << 8) + (bytes[pos++] & 0xff);
  765. encoding[code] = charset.indexOf(strings.get(sid));
  766. }
  767. }
  768. if (pos === 0 || pos === 1) {
  769. predefined = true;
  770. format = pos;
  771. const baseEncoding = pos ? _encodings.ExpertEncoding : _encodings.StandardEncoding;
  772. for (i = 0, ii = charset.length; i < ii; i++) {
  773. const index = baseEncoding.indexOf(charset[i]);
  774. if (index !== -1) {
  775. encoding[index] = i;
  776. }
  777. }
  778. } else {
  779. const dataStart = pos;
  780. format = bytes[pos++];
  781. switch (format & 0x7f) {
  782. case 0:
  783. const glyphsCount = bytes[pos++];
  784. for (i = 1; i <= glyphsCount; i++) {
  785. encoding[bytes[pos++]] = i;
  786. }
  787. break;
  788. case 1:
  789. const rangesCount = bytes[pos++];
  790. let gid = 1;
  791. for (i = 0; i < rangesCount; i++) {
  792. const start = bytes[pos++];
  793. const left = bytes[pos++];
  794. for (let j = start; j <= start + left; j++) {
  795. encoding[j] = gid++;
  796. }
  797. }
  798. break;
  799. default:
  800. throw new _util.FormatError(`Unknown encoding format: ${format} in CFF`);
  801. }
  802. const dataEnd = pos;
  803. if (format & 0x80) {
  804. bytes[dataStart] &= 0x7f;
  805. readSupplement();
  806. }
  807. raw = bytes.subarray(dataStart, dataEnd);
  808. }
  809. format &= 0x7f;
  810. return new CFFEncoding(predefined, format, encoding, raw);
  811. }
  812. parseFDSelect(pos, length) {
  813. const bytes = this.bytes;
  814. const format = bytes[pos++];
  815. const fdSelect = [];
  816. let i;
  817. switch (format) {
  818. case 0:
  819. for (i = 0; i < length; ++i) {
  820. const id = bytes[pos++];
  821. fdSelect.push(id);
  822. }
  823. break;
  824. case 3:
  825. const rangesCount = bytes[pos++] << 8 | bytes[pos++];
  826. for (i = 0; i < rangesCount; ++i) {
  827. let first = bytes[pos++] << 8 | bytes[pos++];
  828. if (i === 0 && first !== 0) {
  829. (0, _util.warn)("parseFDSelect: The first range must have a first GID of 0" + " -- trying to recover.");
  830. first = 0;
  831. }
  832. const fdIndex = bytes[pos++];
  833. const next = bytes[pos] << 8 | bytes[pos + 1];
  834. for (let j = first; j < next; ++j) {
  835. fdSelect.push(fdIndex);
  836. }
  837. }
  838. pos += 2;
  839. break;
  840. default:
  841. throw new _util.FormatError(`parseFDSelect: Unknown format "${format}".`);
  842. }
  843. if (fdSelect.length !== length) {
  844. throw new _util.FormatError("parseFDSelect: Invalid font data.");
  845. }
  846. return new CFFFDSelect(format, fdSelect);
  847. }
  848. }
  849. exports.CFFParser = CFFParser;
  850. class CFF {
  851. constructor() {
  852. this.header = null;
  853. this.names = [];
  854. this.topDict = null;
  855. this.strings = new CFFStrings();
  856. this.globalSubrIndex = null;
  857. this.encoding = null;
  858. this.charset = null;
  859. this.charStrings = null;
  860. this.fdArray = [];
  861. this.fdSelect = null;
  862. this.isCIDFont = false;
  863. }
  864. duplicateFirstGlyph() {
  865. if (this.charStrings.count >= 65535) {
  866. (0, _util.warn)("Not enough space in charstrings to duplicate first glyph.");
  867. return;
  868. }
  869. const glyphZero = this.charStrings.get(0);
  870. this.charStrings.add(glyphZero);
  871. if (this.isCIDFont) {
  872. this.fdSelect.fdSelect.push(this.fdSelect.fdSelect[0]);
  873. }
  874. }
  875. hasGlyphId(id) {
  876. if (id < 0 || id >= this.charStrings.count) {
  877. return false;
  878. }
  879. const glyph = this.charStrings.get(id);
  880. return glyph.length > 0;
  881. }
  882. }
  883. exports.CFF = CFF;
  884. class CFFHeader {
  885. constructor(major, minor, hdrSize, offSize) {
  886. this.major = major;
  887. this.minor = minor;
  888. this.hdrSize = hdrSize;
  889. this.offSize = offSize;
  890. }
  891. }
  892. exports.CFFHeader = CFFHeader;
  893. class CFFStrings {
  894. constructor() {
  895. this.strings = [];
  896. }
  897. get(index) {
  898. if (index >= 0 && index <= NUM_STANDARD_CFF_STRINGS - 1) {
  899. return CFFStandardStrings[index];
  900. }
  901. if (index - NUM_STANDARD_CFF_STRINGS <= this.strings.length) {
  902. return this.strings[index - NUM_STANDARD_CFF_STRINGS];
  903. }
  904. return CFFStandardStrings[0];
  905. }
  906. getSID(str) {
  907. let index = CFFStandardStrings.indexOf(str);
  908. if (index !== -1) {
  909. return index;
  910. }
  911. index = this.strings.indexOf(str);
  912. if (index !== -1) {
  913. return index + NUM_STANDARD_CFF_STRINGS;
  914. }
  915. return -1;
  916. }
  917. add(value) {
  918. this.strings.push(value);
  919. }
  920. get count() {
  921. return this.strings.length;
  922. }
  923. }
  924. exports.CFFStrings = CFFStrings;
  925. class CFFIndex {
  926. constructor() {
  927. this.objects = [];
  928. this.length = 0;
  929. }
  930. add(data) {
  931. this.length += data.length;
  932. this.objects.push(data);
  933. }
  934. set(index, data) {
  935. this.length += data.length - this.objects[index].length;
  936. this.objects[index] = data;
  937. }
  938. get(index) {
  939. return this.objects[index];
  940. }
  941. get count() {
  942. return this.objects.length;
  943. }
  944. }
  945. exports.CFFIndex = CFFIndex;
  946. class CFFDict {
  947. constructor(tables, strings) {
  948. this.keyToNameMap = tables.keyToNameMap;
  949. this.nameToKeyMap = tables.nameToKeyMap;
  950. this.defaults = tables.defaults;
  951. this.types = tables.types;
  952. this.opcodes = tables.opcodes;
  953. this.order = tables.order;
  954. this.strings = strings;
  955. this.values = Object.create(null);
  956. }
  957. setByKey(key, value) {
  958. if (!(key in this.keyToNameMap)) {
  959. return false;
  960. }
  961. if (value.length === 0) {
  962. return true;
  963. }
  964. for (const val of value) {
  965. if (isNaN(val)) {
  966. (0, _util.warn)(`Invalid CFFDict value: "${value}" for key "${key}".`);
  967. return true;
  968. }
  969. }
  970. const type = this.types[key];
  971. if (type === "num" || type === "sid" || type === "offset") {
  972. value = value[0];
  973. }
  974. this.values[key] = value;
  975. return true;
  976. }
  977. setByName(name, value) {
  978. if (!(name in this.nameToKeyMap)) {
  979. throw new _util.FormatError(`Invalid dictionary name "${name}"`);
  980. }
  981. this.values[this.nameToKeyMap[name]] = value;
  982. }
  983. hasName(name) {
  984. return this.nameToKeyMap[name] in this.values;
  985. }
  986. getByName(name) {
  987. if (!(name in this.nameToKeyMap)) {
  988. throw new _util.FormatError(`Invalid dictionary name ${name}"`);
  989. }
  990. const key = this.nameToKeyMap[name];
  991. if (!(key in this.values)) {
  992. return this.defaults[key];
  993. }
  994. return this.values[key];
  995. }
  996. removeByName(name) {
  997. delete this.values[this.nameToKeyMap[name]];
  998. }
  999. static createTables(layout) {
  1000. const tables = {
  1001. keyToNameMap: {},
  1002. nameToKeyMap: {},
  1003. defaults: {},
  1004. types: {},
  1005. opcodes: {},
  1006. order: []
  1007. };
  1008. for (const entry of layout) {
  1009. const key = Array.isArray(entry[0]) ? (entry[0][0] << 8) + entry[0][1] : entry[0];
  1010. tables.keyToNameMap[key] = entry[1];
  1011. tables.nameToKeyMap[entry[1]] = key;
  1012. tables.types[key] = entry[2];
  1013. tables.defaults[key] = entry[3];
  1014. tables.opcodes[key] = Array.isArray(entry[0]) ? entry[0] : [entry[0]];
  1015. tables.order.push(key);
  1016. }
  1017. return tables;
  1018. }
  1019. }
  1020. 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]];
  1021. class CFFTopDict extends CFFDict {
  1022. static get tables() {
  1023. return (0, _util.shadow)(this, "tables", this.createTables(CFFTopDictLayout));
  1024. }
  1025. constructor(strings) {
  1026. super(CFFTopDict.tables, strings);
  1027. this.privateDict = null;
  1028. }
  1029. }
  1030. exports.CFFTopDict = CFFTopDict;
  1031. 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]];
  1032. class CFFPrivateDict extends CFFDict {
  1033. static get tables() {
  1034. return (0, _util.shadow)(this, "tables", this.createTables(CFFPrivateDictLayout));
  1035. }
  1036. constructor(strings) {
  1037. super(CFFPrivateDict.tables, strings);
  1038. this.subrsIndex = null;
  1039. }
  1040. }
  1041. exports.CFFPrivateDict = CFFPrivateDict;
  1042. const CFFCharsetPredefinedTypes = {
  1043. ISO_ADOBE: 0,
  1044. EXPERT: 1,
  1045. EXPERT_SUBSET: 2
  1046. };
  1047. class CFFCharset {
  1048. constructor(predefined, format, charset, raw) {
  1049. this.predefined = predefined;
  1050. this.format = format;
  1051. this.charset = charset;
  1052. this.raw = raw;
  1053. }
  1054. }
  1055. exports.CFFCharset = CFFCharset;
  1056. class CFFEncoding {
  1057. constructor(predefined, format, encoding, raw) {
  1058. this.predefined = predefined;
  1059. this.format = format;
  1060. this.encoding = encoding;
  1061. this.raw = raw;
  1062. }
  1063. }
  1064. class CFFFDSelect {
  1065. constructor(format, fdSelect) {
  1066. this.format = format;
  1067. this.fdSelect = fdSelect;
  1068. }
  1069. getFDIndex(glyphIndex) {
  1070. if (glyphIndex < 0 || glyphIndex >= this.fdSelect.length) {
  1071. return -1;
  1072. }
  1073. return this.fdSelect[glyphIndex];
  1074. }
  1075. }
  1076. exports.CFFFDSelect = CFFFDSelect;
  1077. class CFFOffsetTracker {
  1078. constructor() {
  1079. this.offsets = Object.create(null);
  1080. }
  1081. isTracking(key) {
  1082. return key in this.offsets;
  1083. }
  1084. track(key, location) {
  1085. if (key in this.offsets) {
  1086. throw new _util.FormatError(`Already tracking location of ${key}`);
  1087. }
  1088. this.offsets[key] = location;
  1089. }
  1090. offset(value) {
  1091. for (const key in this.offsets) {
  1092. this.offsets[key] += value;
  1093. }
  1094. }
  1095. setEntryLocation(key, values, output) {
  1096. if (!(key in this.offsets)) {
  1097. throw new _util.FormatError(`Not tracking location of ${key}`);
  1098. }
  1099. const data = output.data;
  1100. const dataOffset = this.offsets[key];
  1101. const size = 5;
  1102. for (let i = 0, ii = values.length; i < ii; ++i) {
  1103. const offset0 = i * size + dataOffset;
  1104. const offset1 = offset0 + 1;
  1105. const offset2 = offset0 + 2;
  1106. const offset3 = offset0 + 3;
  1107. const offset4 = offset0 + 4;
  1108. if (data[offset0] !== 0x1d || data[offset1] !== 0 || data[offset2] !== 0 || data[offset3] !== 0 || data[offset4] !== 0) {
  1109. throw new _util.FormatError("writing to an offset that is not empty");
  1110. }
  1111. const value = values[i];
  1112. data[offset0] = 0x1d;
  1113. data[offset1] = value >> 24 & 0xff;
  1114. data[offset2] = value >> 16 & 0xff;
  1115. data[offset3] = value >> 8 & 0xff;
  1116. data[offset4] = value & 0xff;
  1117. }
  1118. }
  1119. }
  1120. class CFFCompiler {
  1121. constructor(cff) {
  1122. this.cff = cff;
  1123. }
  1124. compile() {
  1125. const cff = this.cff;
  1126. const output = {
  1127. data: [],
  1128. length: 0,
  1129. add(data) {
  1130. this.data = this.data.concat(data);
  1131. this.length = this.data.length;
  1132. }
  1133. };
  1134. const header = this.compileHeader(cff.header);
  1135. output.add(header);
  1136. const nameIndex = this.compileNameIndex(cff.names);
  1137. output.add(nameIndex);
  1138. if (cff.isCIDFont) {
  1139. if (cff.topDict.hasName("FontMatrix")) {
  1140. const base = cff.topDict.getByName("FontMatrix");
  1141. cff.topDict.removeByName("FontMatrix");
  1142. for (const subDict of cff.fdArray) {
  1143. let matrix = base.slice(0);
  1144. if (subDict.hasName("FontMatrix")) {
  1145. matrix = _util.Util.transform(matrix, subDict.getByName("FontMatrix"));
  1146. }
  1147. subDict.setByName("FontMatrix", matrix);
  1148. }
  1149. }
  1150. }
  1151. const xuid = cff.topDict.getByName("XUID");
  1152. if (xuid && xuid.length > 16) {
  1153. cff.topDict.removeByName("XUID");
  1154. }
  1155. cff.topDict.setByName("charset", 0);
  1156. let compiled = this.compileTopDicts([cff.topDict], output.length, cff.isCIDFont);
  1157. output.add(compiled.output);
  1158. const topDictTracker = compiled.trackers[0];
  1159. const stringIndex = this.compileStringIndex(cff.strings.strings);
  1160. output.add(stringIndex);
  1161. const globalSubrIndex = this.compileIndex(cff.globalSubrIndex);
  1162. output.add(globalSubrIndex);
  1163. if (cff.encoding && cff.topDict.hasName("Encoding")) {
  1164. if (cff.encoding.predefined) {
  1165. topDictTracker.setEntryLocation("Encoding", [cff.encoding.format], output);
  1166. } else {
  1167. const encoding = this.compileEncoding(cff.encoding);
  1168. topDictTracker.setEntryLocation("Encoding", [output.length], output);
  1169. output.add(encoding);
  1170. }
  1171. }
  1172. const charset = this.compileCharset(cff.charset, cff.charStrings.count, cff.strings, cff.isCIDFont);
  1173. topDictTracker.setEntryLocation("charset", [output.length], output);
  1174. output.add(charset);
  1175. const charStrings = this.compileCharStrings(cff.charStrings);
  1176. topDictTracker.setEntryLocation("CharStrings", [output.length], output);
  1177. output.add(charStrings);
  1178. if (cff.isCIDFont) {
  1179. topDictTracker.setEntryLocation("FDSelect", [output.length], output);
  1180. const fdSelect = this.compileFDSelect(cff.fdSelect);
  1181. output.add(fdSelect);
  1182. compiled = this.compileTopDicts(cff.fdArray, output.length, true);
  1183. topDictTracker.setEntryLocation("FDArray", [output.length], output);
  1184. output.add(compiled.output);
  1185. const fontDictTrackers = compiled.trackers;
  1186. this.compilePrivateDicts(cff.fdArray, fontDictTrackers, output);
  1187. }
  1188. this.compilePrivateDicts([cff.topDict], [topDictTracker], output);
  1189. output.add([0]);
  1190. return output.data;
  1191. }
  1192. encodeNumber(value) {
  1193. if (Number.isInteger(value)) {
  1194. return this.encodeInteger(value);
  1195. }
  1196. return this.encodeFloat(value);
  1197. }
  1198. static get EncodeFloatRegExp() {
  1199. return (0, _util.shadow)(this, "EncodeFloatRegExp", /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/);
  1200. }
  1201. encodeFloat(num) {
  1202. let value = num.toString();
  1203. const m = CFFCompiler.EncodeFloatRegExp.exec(value);
  1204. if (m) {
  1205. const epsilon = parseFloat("1e" + ((m[2] ? +m[2] : 0) + m[1].length));
  1206. value = (Math.round(num * epsilon) / epsilon).toString();
  1207. }
  1208. let nibbles = "";
  1209. let i, ii;
  1210. for (i = 0, ii = value.length; i < ii; ++i) {
  1211. const a = value[i];
  1212. if (a === "e") {
  1213. nibbles += value[++i] === "-" ? "c" : "b";
  1214. } else if (a === ".") {
  1215. nibbles += "a";
  1216. } else if (a === "-") {
  1217. nibbles += "e";
  1218. } else {
  1219. nibbles += a;
  1220. }
  1221. }
  1222. nibbles += nibbles.length & 1 ? "f" : "ff";
  1223. const out = [30];
  1224. for (i = 0, ii = nibbles.length; i < ii; i += 2) {
  1225. out.push(parseInt(nibbles.substring(i, i + 2), 16));
  1226. }
  1227. return out;
  1228. }
  1229. encodeInteger(value) {
  1230. let code;
  1231. if (value >= -107 && value <= 107) {
  1232. code = [value + 139];
  1233. } else if (value >= 108 && value <= 1131) {
  1234. value -= 108;
  1235. code = [(value >> 8) + 247, value & 0xff];
  1236. } else if (value >= -1131 && value <= -108) {
  1237. value = -value - 108;
  1238. code = [(value >> 8) + 251, value & 0xff];
  1239. } else if (value >= -32768 && value <= 32767) {
  1240. code = [0x1c, value >> 8 & 0xff, value & 0xff];
  1241. } else {
  1242. code = [0x1d, value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff];
  1243. }
  1244. return code;
  1245. }
  1246. compileHeader(header) {
  1247. return [header.major, header.minor, 4, header.offSize];
  1248. }
  1249. compileNameIndex(names) {
  1250. const nameIndex = new CFFIndex();
  1251. for (const name of names) {
  1252. const length = Math.min(name.length, 127);
  1253. let sanitizedName = new Array(length);
  1254. for (let j = 0; j < length; j++) {
  1255. let char = name[j];
  1256. if (char < "!" || char > "~" || char === "[" || char === "]" || char === "(" || char === ")" || char === "{" || char === "}" || char === "<" || char === ">" || char === "/" || char === "%") {
  1257. char = "_";
  1258. }
  1259. sanitizedName[j] = char;
  1260. }
  1261. sanitizedName = sanitizedName.join("");
  1262. if (sanitizedName === "") {
  1263. sanitizedName = "Bad_Font_Name";
  1264. }
  1265. nameIndex.add((0, _util.stringToBytes)(sanitizedName));
  1266. }
  1267. return this.compileIndex(nameIndex);
  1268. }
  1269. compileTopDicts(dicts, length, removeCidKeys) {
  1270. const fontDictTrackers = [];
  1271. let fdArrayIndex = new CFFIndex();
  1272. for (const fontDict of dicts) {
  1273. if (removeCidKeys) {
  1274. fontDict.removeByName("CIDFontVersion");
  1275. fontDict.removeByName("CIDFontRevision");
  1276. fontDict.removeByName("CIDFontType");
  1277. fontDict.removeByName("CIDCount");
  1278. fontDict.removeByName("UIDBase");
  1279. }
  1280. const fontDictTracker = new CFFOffsetTracker();
  1281. const fontDictData = this.compileDict(fontDict, fontDictTracker);
  1282. fontDictTrackers.push(fontDictTracker);
  1283. fdArrayIndex.add(fontDictData);
  1284. fontDictTracker.offset(length);
  1285. }
  1286. fdArrayIndex = this.compileIndex(fdArrayIndex, fontDictTrackers);
  1287. return {
  1288. trackers: fontDictTrackers,
  1289. output: fdArrayIndex
  1290. };
  1291. }
  1292. compilePrivateDicts(dicts, trackers, output) {
  1293. for (let i = 0, ii = dicts.length; i < ii; ++i) {
  1294. const fontDict = dicts[i];
  1295. const privateDict = fontDict.privateDict;
  1296. if (!privateDict || !fontDict.hasName("Private")) {
  1297. throw new _util.FormatError("There must be a private dictionary.");
  1298. }
  1299. const privateDictTracker = new CFFOffsetTracker();
  1300. const privateDictData = this.compileDict(privateDict, privateDictTracker);
  1301. let outputLength = output.length;
  1302. privateDictTracker.offset(outputLength);
  1303. if (!privateDictData.length) {
  1304. outputLength = 0;
  1305. }
  1306. trackers[i].setEntryLocation("Private", [privateDictData.length, outputLength], output);
  1307. output.add(privateDictData);
  1308. if (privateDict.subrsIndex && privateDict.hasName("Subrs")) {
  1309. const subrs = this.compileIndex(privateDict.subrsIndex);
  1310. privateDictTracker.setEntryLocation("Subrs", [privateDictData.length], output);
  1311. output.add(subrs);
  1312. }
  1313. }
  1314. }
  1315. compileDict(dict, offsetTracker) {
  1316. const out = [];
  1317. for (const key of dict.order) {
  1318. if (!(key in dict.values)) {
  1319. continue;
  1320. }
  1321. let values = dict.values[key];
  1322. let types = dict.types[key];
  1323. if (!Array.isArray(types)) {
  1324. types = [types];
  1325. }
  1326. if (!Array.isArray(values)) {
  1327. values = [values];
  1328. }
  1329. if (values.length === 0) {
  1330. continue;
  1331. }
  1332. for (let j = 0, jj = types.length; j < jj; ++j) {
  1333. const type = types[j];
  1334. const value = values[j];
  1335. switch (type) {
  1336. case "num":
  1337. case "sid":
  1338. out.push(...this.encodeNumber(value));
  1339. break;
  1340. case "offset":
  1341. const name = dict.keyToNameMap[key];
  1342. if (!offsetTracker.isTracking(name)) {
  1343. offsetTracker.track(name, out.length);
  1344. }
  1345. out.push(0x1d, 0, 0, 0, 0);
  1346. break;
  1347. case "array":
  1348. case "delta":
  1349. out.push(...this.encodeNumber(value));
  1350. for (let k = 1, kk = values.length; k < kk; ++k) {
  1351. out.push(...this.encodeNumber(values[k]));
  1352. }
  1353. break;
  1354. default:
  1355. throw new _util.FormatError(`Unknown data type of ${type}`);
  1356. }
  1357. }
  1358. out.push(...dict.opcodes[key]);
  1359. }
  1360. return out;
  1361. }
  1362. compileStringIndex(strings) {
  1363. const stringIndex = new CFFIndex();
  1364. for (const string of strings) {
  1365. stringIndex.add((0, _util.stringToBytes)(string));
  1366. }
  1367. return this.compileIndex(stringIndex);
  1368. }
  1369. compileGlobalSubrIndex() {
  1370. const globalSubrIndex = this.cff.globalSubrIndex;
  1371. this.out.writeByteArray(this.compileIndex(globalSubrIndex));
  1372. }
  1373. compileCharStrings(charStrings) {
  1374. const charStringsIndex = new CFFIndex();
  1375. for (let i = 0; i < charStrings.count; i++) {
  1376. const glyph = charStrings.get(i);
  1377. if (glyph.length === 0) {
  1378. charStringsIndex.add(new Uint8Array([0x8b, 0x0e]));
  1379. continue;
  1380. }
  1381. charStringsIndex.add(glyph);
  1382. }
  1383. return this.compileIndex(charStringsIndex);
  1384. }
  1385. compileCharset(charset, numGlyphs, strings, isCIDFont) {
  1386. let out;
  1387. const numGlyphsLessNotDef = numGlyphs - 1;
  1388. if (isCIDFont) {
  1389. out = new Uint8Array([2, 0, 0, numGlyphsLessNotDef >> 8 & 0xff, numGlyphsLessNotDef & 0xff]);
  1390. } else {
  1391. const length = 1 + numGlyphsLessNotDef * 2;
  1392. out = new Uint8Array(length);
  1393. out[0] = 0;
  1394. let charsetIndex = 0;
  1395. const numCharsets = charset.charset.length;
  1396. let warned = false;
  1397. for (let i = 1; i < out.length; i += 2) {
  1398. let sid = 0;
  1399. if (charsetIndex < numCharsets) {
  1400. const name = charset.charset[charsetIndex++];
  1401. sid = strings.getSID(name);
  1402. if (sid === -1) {
  1403. sid = 0;
  1404. if (!warned) {
  1405. warned = true;
  1406. (0, _util.warn)(`Couldn't find ${name} in CFF strings`);
  1407. }
  1408. }
  1409. }
  1410. out[i] = sid >> 8 & 0xff;
  1411. out[i + 1] = sid & 0xff;
  1412. }
  1413. }
  1414. return this.compileTypedArray(out);
  1415. }
  1416. compileEncoding(encoding) {
  1417. return this.compileTypedArray(encoding.raw);
  1418. }
  1419. compileFDSelect(fdSelect) {
  1420. const format = fdSelect.format;
  1421. let out, i;
  1422. switch (format) {
  1423. case 0:
  1424. out = new Uint8Array(1 + fdSelect.fdSelect.length);
  1425. out[0] = format;
  1426. for (i = 0; i < fdSelect.fdSelect.length; i++) {
  1427. out[i + 1] = fdSelect.fdSelect[i];
  1428. }
  1429. break;
  1430. case 3:
  1431. const start = 0;
  1432. let lastFD = fdSelect.fdSelect[0];
  1433. const ranges = [format, 0, 0, start >> 8 & 0xff, start & 0xff, lastFD];
  1434. for (i = 1; i < fdSelect.fdSelect.length; i++) {
  1435. const currentFD = fdSelect.fdSelect[i];
  1436. if (currentFD !== lastFD) {
  1437. ranges.push(i >> 8 & 0xff, i & 0xff, currentFD);
  1438. lastFD = currentFD;
  1439. }
  1440. }
  1441. const numRanges = (ranges.length - 3) / 3;
  1442. ranges[1] = numRanges >> 8 & 0xff;
  1443. ranges[2] = numRanges & 0xff;
  1444. ranges.push(i >> 8 & 0xff, i & 0xff);
  1445. out = new Uint8Array(ranges);
  1446. break;
  1447. }
  1448. return this.compileTypedArray(out);
  1449. }
  1450. compileTypedArray(data) {
  1451. const out = [];
  1452. for (let i = 0, ii = data.length; i < ii; ++i) {
  1453. out[i] = data[i];
  1454. }
  1455. return out;
  1456. }
  1457. compileIndex(index, trackers = []) {
  1458. const objects = index.objects;
  1459. const count = objects.length;
  1460. if (count === 0) {
  1461. return [0, 0];
  1462. }
  1463. const data = [count >> 8 & 0xff, count & 0xff];
  1464. let lastOffset = 1,
  1465. i;
  1466. for (i = 0; i < count; ++i) {
  1467. lastOffset += objects[i].length;
  1468. }
  1469. let offsetSize;
  1470. if (lastOffset < 0x100) {
  1471. offsetSize = 1;
  1472. } else if (lastOffset < 0x10000) {
  1473. offsetSize = 2;
  1474. } else if (lastOffset < 0x1000000) {
  1475. offsetSize = 3;
  1476. } else {
  1477. offsetSize = 4;
  1478. }
  1479. data.push(offsetSize);
  1480. let relativeOffset = 1;
  1481. for (i = 0; i < count + 1; i++) {
  1482. if (offsetSize === 1) {
  1483. data.push(relativeOffset & 0xff);
  1484. } else if (offsetSize === 2) {
  1485. data.push(relativeOffset >> 8 & 0xff, relativeOffset & 0xff);
  1486. } else if (offsetSize === 3) {
  1487. data.push(relativeOffset >> 16 & 0xff, relativeOffset >> 8 & 0xff, relativeOffset & 0xff);
  1488. } else {
  1489. data.push(relativeOffset >>> 24 & 0xff, relativeOffset >> 16 & 0xff, relativeOffset >> 8 & 0xff, relativeOffset & 0xff);
  1490. }
  1491. if (objects[i]) {
  1492. relativeOffset += objects[i].length;
  1493. }
  1494. }
  1495. for (i = 0; i < count; i++) {
  1496. if (trackers[i]) {
  1497. trackers[i].offset(data.length);
  1498. }
  1499. data.push(...objects[i]);
  1500. }
  1501. return data;
  1502. }
  1503. }
  1504. exports.CFFCompiler = CFFCompiler;