fonts.js 84 KB

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