fonts.js 84 KB

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