2
0

fonts.js 76 KB

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