cff_parser.js 53 KB

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