font_loader.js 11 KB

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