fonts.js 79 KB

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