2
0

fonts.js 84 KB

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