fonts.js 82 KB

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