font_loader.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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.FontLoader = exports.FontFaceObject = void 0;
  27. var _util = require("../shared/util.js");
  28. var _is_node = require("../shared/is_node.js");
  29. class FontLoader {
  30. constructor({
  31. onUnsupportedFeature,
  32. ownerDocument = globalThis.document,
  33. styleElement = null
  34. }) {
  35. this._onUnsupportedFeature = onUnsupportedFeature;
  36. this._document = ownerDocument;
  37. this.nativeFontFaces = [];
  38. this.styleElement = null;
  39. this.loadingRequests = [];
  40. this.loadTestFontId = 0;
  41. }
  42. addNativeFontFace(nativeFontFace) {
  43. this.nativeFontFaces.push(nativeFontFace);
  44. this._document.fonts.add(nativeFontFace);
  45. }
  46. insertRule(rule) {
  47. if (!this.styleElement) {
  48. this.styleElement = this._document.createElement("style");
  49. this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement);
  50. }
  51. const styleSheet = this.styleElement.sheet;
  52. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  53. }
  54. clear() {
  55. for (const nativeFontFace of this.nativeFontFaces) {
  56. this._document.fonts.delete(nativeFontFace);
  57. }
  58. this.nativeFontFaces.length = 0;
  59. if (this.styleElement) {
  60. this.styleElement.remove();
  61. this.styleElement = null;
  62. }
  63. }
  64. async bind(font) {
  65. if (font.attached || font.missingFile) {
  66. return;
  67. }
  68. font.attached = true;
  69. if (this.isFontLoadingAPISupported) {
  70. const nativeFontFace = font.createNativeFontFace();
  71. if (nativeFontFace) {
  72. this.addNativeFontFace(nativeFontFace);
  73. try {
  74. await nativeFontFace.loaded;
  75. } catch (ex) {
  76. this._onUnsupportedFeature({
  77. featureId: _util.UNSUPPORTED_FEATURES.errorFontLoadNative
  78. });
  79. (0, _util.warn)(`Failed to load font '${nativeFontFace.family}': '${ex}'.`);
  80. font.disableFontFace = true;
  81. throw ex;
  82. }
  83. }
  84. return;
  85. }
  86. const rule = font.createFontFaceRule();
  87. if (rule) {
  88. this.insertRule(rule);
  89. if (this.isSyncFontLoadingSupported) {
  90. return;
  91. }
  92. await new Promise(resolve => {
  93. const request = this._queueLoadingCallback(resolve);
  94. this._prepareFontLoadEvent(font, request);
  95. });
  96. }
  97. }
  98. get isFontLoadingAPISupported() {
  99. const hasFonts = !!this._document?.fonts;
  100. return (0, _util.shadow)(this, "isFontLoadingAPISupported", hasFonts);
  101. }
  102. get isSyncFontLoadingSupported() {
  103. let supported = false;
  104. if (_is_node.isNodeJS) {
  105. supported = true;
  106. } else if (typeof navigator !== "undefined" && /Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent)) {
  107. supported = true;
  108. }
  109. return (0, _util.shadow)(this, "isSyncFontLoadingSupported", supported);
  110. }
  111. _queueLoadingCallback(callback) {
  112. function completeRequest() {
  113. (0, _util.assert)(!request.done, "completeRequest() cannot be called twice.");
  114. request.done = true;
  115. while (loadingRequests.length > 0 && loadingRequests[0].done) {
  116. const otherRequest = loadingRequests.shift();
  117. setTimeout(otherRequest.callback, 0);
  118. }
  119. }
  120. const {
  121. loadingRequests
  122. } = this;
  123. const request = {
  124. done: false,
  125. complete: completeRequest,
  126. callback
  127. };
  128. loadingRequests.push(request);
  129. return request;
  130. }
  131. get _loadTestFont() {
  132. const testFont = atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQA" + "FQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAA" + "ALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgA" + "AAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1" + "AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD" + "6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACM" + "AooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4D" + "IP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAA" + "AAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUA" + "AQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgAB" + "AAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABY" + "AAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAA" + "AC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAA" + "AAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQAC" + "AQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3" + "Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTj" + "FQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");
  133. return (0, _util.shadow)(this, "_loadTestFont", testFont);
  134. }
  135. _prepareFontLoadEvent(font, request) {
  136. function int32(data, offset) {
  137. return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff;
  138. }
  139. function spliceString(s, offset, remove, insert) {
  140. const chunk1 = s.substring(0, offset);
  141. const chunk2 = s.substring(offset + remove);
  142. return chunk1 + insert + chunk2;
  143. }
  144. let i, ii;
  145. const canvas = this._document.createElement("canvas");
  146. canvas.width = 1;
  147. canvas.height = 1;
  148. const ctx = canvas.getContext("2d");
  149. let called = 0;
  150. function isFontReady(name, callback) {
  151. if (++called > 30) {
  152. (0, _util.warn)("Load test font never loaded.");
  153. callback();
  154. return;
  155. }
  156. ctx.font = "30px " + name;
  157. ctx.fillText(".", 0, 20);
  158. const imageData = ctx.getImageData(0, 0, 1, 1);
  159. if (imageData.data[3] > 0) {
  160. callback();
  161. return;
  162. }
  163. setTimeout(isFontReady.bind(null, name, callback));
  164. }
  165. const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`;
  166. let data = this._loadTestFont;
  167. const COMMENT_OFFSET = 976;
  168. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId);
  169. const CFF_CHECKSUM_OFFSET = 16;
  170. const XXXX_VALUE = 0x58585858;
  171. let checksum = int32(data, CFF_CHECKSUM_OFFSET);
  172. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  173. checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0;
  174. }
  175. if (i < loadTestFontId.length) {
  176. checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i) | 0;
  177. }
  178. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, (0, _util.string32)(checksum));
  179. const url = `url(data:font/opentype;base64,${btoa(data)});`;
  180. const rule = `@font-face {font-family:"${loadTestFontId}";src:${url}}`;
  181. this.insertRule(rule);
  182. const div = this._document.createElement("div");
  183. div.style.visibility = "hidden";
  184. div.style.width = div.style.height = "10px";
  185. div.style.position = "absolute";
  186. div.style.top = div.style.left = "0px";
  187. for (const name of [font.loadedName, loadTestFontId]) {
  188. const span = this._document.createElement("span");
  189. span.textContent = "Hi";
  190. span.style.fontFamily = name;
  191. div.append(span);
  192. }
  193. this._document.body.append(div);
  194. isFontReady(loadTestFontId, () => {
  195. div.remove();
  196. request.complete();
  197. });
  198. }
  199. }
  200. exports.FontLoader = FontLoader;
  201. class FontFaceObject {
  202. constructor(translatedData, {
  203. isEvalSupported = true,
  204. disableFontFace = false,
  205. ignoreErrors = false,
  206. onUnsupportedFeature,
  207. fontRegistry = null
  208. }) {
  209. this.compiledGlyphs = Object.create(null);
  210. for (const i in translatedData) {
  211. this[i] = translatedData[i];
  212. }
  213. this.isEvalSupported = isEvalSupported !== false;
  214. this.disableFontFace = disableFontFace === true;
  215. this.ignoreErrors = ignoreErrors === true;
  216. this._onUnsupportedFeature = onUnsupportedFeature;
  217. this.fontRegistry = fontRegistry;
  218. }
  219. createNativeFontFace() {
  220. if (!this.data || this.disableFontFace) {
  221. return null;
  222. }
  223. let nativeFontFace;
  224. if (!this.cssFontInfo) {
  225. nativeFontFace = new FontFace(this.loadedName, this.data, {});
  226. } else {
  227. const css = {
  228. weight: this.cssFontInfo.fontWeight
  229. };
  230. if (this.cssFontInfo.italicAngle) {
  231. css.style = `oblique ${this.cssFontInfo.italicAngle}deg`;
  232. }
  233. nativeFontFace = new FontFace(this.cssFontInfo.fontFamily, this.data, css);
  234. }
  235. this.fontRegistry?.registerFont(this);
  236. return nativeFontFace;
  237. }
  238. createFontFaceRule() {
  239. if (!this.data || this.disableFontFace) {
  240. return null;
  241. }
  242. const data = (0, _util.bytesToString)(this.data);
  243. const url = `url(data:${this.mimetype};base64,${btoa(data)});`;
  244. let rule;
  245. if (!this.cssFontInfo) {
  246. rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`;
  247. } else {
  248. let css = `font-weight: ${this.cssFontInfo.fontWeight};`;
  249. if (this.cssFontInfo.italicAngle) {
  250. css += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`;
  251. }
  252. rule = `@font-face {font-family:"${this.cssFontInfo.fontFamily}";${css}src:${url}}`;
  253. }
  254. this.fontRegistry?.registerFont(this, url);
  255. return rule;
  256. }
  257. getPathGenerator(objs, character) {
  258. if (this.compiledGlyphs[character] !== undefined) {
  259. return this.compiledGlyphs[character];
  260. }
  261. let cmds;
  262. try {
  263. cmds = objs.get(this.loadedName + "_path_" + character);
  264. } catch (ex) {
  265. if (!this.ignoreErrors) {
  266. throw ex;
  267. }
  268. this._onUnsupportedFeature({
  269. featureId: _util.UNSUPPORTED_FEATURES.errorFontGetPath
  270. });
  271. (0, _util.warn)(`getPathGenerator - ignoring character: "${ex}".`);
  272. return this.compiledGlyphs[character] = function (c, size) {};
  273. }
  274. if (this.isEvalSupported && _util.FeatureTest.isEvalSupported) {
  275. const jsBuf = [];
  276. for (const current of cmds) {
  277. const args = current.args !== undefined ? current.args.join(",") : "";
  278. jsBuf.push("c.", current.cmd, "(", args, ");\n");
  279. }
  280. return this.compiledGlyphs[character] = new Function("c", "size", jsBuf.join(""));
  281. }
  282. return this.compiledGlyphs[character] = function (c, size) {
  283. for (const current of cmds) {
  284. if (current.cmd === "scale") {
  285. current.args = [size, -size];
  286. }
  287. c[current.cmd].apply(c, current.args);
  288. }
  289. };
  290. }
  291. }
  292. exports.FontFaceObject = FontFaceObject;