2
0

fonts.js 85 KB

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