font_loader.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2021 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * Javascript code in this page
  21. */
  22. "use strict";
  23. Object.defineProperty(exports, "__esModule", {
  24. value: true
  25. });
  26. exports.FontLoader = exports.FontFaceObject = void 0;
  27. var _util = require("../shared/util.js");
  28. class BaseFontLoader {
  29. constructor({
  30. docId,
  31. onUnsupportedFeature,
  32. ownerDocument = globalThis.document
  33. }) {
  34. if (this.constructor === BaseFontLoader) {
  35. (0, _util.unreachable)("Cannot initialize BaseFontLoader.");
  36. }
  37. this.docId = docId;
  38. this._onUnsupportedFeature = onUnsupportedFeature;
  39. this._document = ownerDocument;
  40. this.nativeFontFaces = [];
  41. this.styleElement = null;
  42. }
  43. addNativeFontFace(nativeFontFace) {
  44. this.nativeFontFaces.push(nativeFontFace);
  45. this._document.fonts.add(nativeFontFace);
  46. }
  47. insertRule(rule) {
  48. let styleElement = this.styleElement;
  49. if (!styleElement) {
  50. styleElement = this.styleElement = this._document.createElement("style");
  51. styleElement.id = `PDFJS_FONT_STYLE_TAG_${this.docId}`;
  52. this._document.documentElement.getElementsByTagName("head")[0].appendChild(styleElement);
  53. }
  54. const styleSheet = styleElement.sheet;
  55. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  56. }
  57. clear() {
  58. for (const nativeFontFace of this.nativeFontFaces) {
  59. this._document.fonts.delete(nativeFontFace);
  60. }
  61. this.nativeFontFaces.length = 0;
  62. if (this.styleElement) {
  63. this.styleElement.remove();
  64. this.styleElement = null;
  65. }
  66. }
  67. async bind(font) {
  68. if (font.attached || font.missingFile) {
  69. return;
  70. }
  71. font.attached = true;
  72. if (this.isFontLoadingAPISupported) {
  73. const nativeFontFace = font.createNativeFontFace();
  74. if (nativeFontFace) {
  75. this.addNativeFontFace(nativeFontFace);
  76. try {
  77. await nativeFontFace.loaded;
  78. } catch (ex) {
  79. this._onUnsupportedFeature({
  80. featureId: _util.UNSUPPORTED_FEATURES.errorFontLoadNative
  81. });
  82. (0, _util.warn)(`Failed to load font '${nativeFontFace.family}': '${ex}'.`);
  83. font.disableFontFace = true;
  84. throw ex;
  85. }
  86. }
  87. return;
  88. }
  89. const rule = font.createFontFaceRule();
  90. if (rule) {
  91. this.insertRule(rule);
  92. if (this.isSyncFontLoadingSupported) {
  93. return;
  94. }
  95. await new Promise(resolve => {
  96. const request = this._queueLoadingCallback(resolve);
  97. this._prepareFontLoadEvent([rule], [font], request);
  98. });
  99. }
  100. }
  101. _queueLoadingCallback(callback) {
  102. (0, _util.unreachable)("Abstract method `_queueLoadingCallback`.");
  103. }
  104. get isFontLoadingAPISupported() {
  105. return (0, _util.shadow)(this, "isFontLoadingAPISupported", !!this._document?.fonts);
  106. }
  107. get isSyncFontLoadingSupported() {
  108. (0, _util.unreachable)("Abstract method `isSyncFontLoadingSupported`.");
  109. }
  110. get _loadTestFont() {
  111. (0, _util.unreachable)("Abstract method `_loadTestFont`.");
  112. }
  113. _prepareFontLoadEvent(rules, fontsToLoad, request) {
  114. (0, _util.unreachable)("Abstract method `_prepareFontLoadEvent`.");
  115. }
  116. }
  117. let FontLoader;
  118. exports.FontLoader = FontLoader;
  119. {
  120. exports.FontLoader = FontLoader = class GenericFontLoader extends BaseFontLoader {
  121. constructor(params) {
  122. super(params);
  123. this.loadingContext = {
  124. requests: [],
  125. nextRequestId: 0
  126. };
  127. this.loadTestFontId = 0;
  128. }
  129. get isSyncFontLoadingSupported() {
  130. let supported = false;
  131. if (typeof navigator === "undefined") {
  132. supported = true;
  133. } else {
  134. const m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent);
  135. if (m?.[1] >= 14) {
  136. supported = true;
  137. }
  138. }
  139. return (0, _util.shadow)(this, "isSyncFontLoadingSupported", supported);
  140. }
  141. _queueLoadingCallback(callback) {
  142. function completeRequest() {
  143. (0, _util.assert)(!request.done, "completeRequest() cannot be called twice.");
  144. request.done = true;
  145. while (context.requests.length > 0 && context.requests[0].done) {
  146. const otherRequest = context.requests.shift();
  147. setTimeout(otherRequest.callback, 0);
  148. }
  149. }
  150. const context = this.loadingContext;
  151. const request = {
  152. id: `pdfjs-font-loading-${context.nextRequestId++}`,
  153. done: false,
  154. complete: completeRequest,
  155. callback
  156. };
  157. context.requests.push(request);
  158. return request;
  159. }
  160. get _loadTestFont() {
  161. const getLoadTestFont = function () {
  162. return atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQA" + "FQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAA" + "ALwAAAA2aGhlYQdkA+oAAAD0AAAA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AAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAA" + "AAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQAC" + "AQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3" + "Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTj" + "FQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");
  163. };
  164. return (0, _util.shadow)(this, "_loadTestFont", getLoadTestFont());
  165. }
  166. _prepareFontLoadEvent(rules, fonts, request) {
  167. function int32(data, offset) {
  168. return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff;
  169. }
  170. function spliceString(s, offset, remove, insert) {
  171. const chunk1 = s.substring(0, offset);
  172. const chunk2 = s.substring(offset + remove);
  173. return chunk1 + insert + chunk2;
  174. }
  175. let i, ii;
  176. const canvas = this._document.createElement("canvas");
  177. canvas.width = 1;
  178. canvas.height = 1;
  179. const ctx = canvas.getContext("2d");
  180. let called = 0;
  181. function isFontReady(name, callback) {
  182. called++;
  183. if (called > 30) {
  184. (0, _util.warn)("Load test font never loaded.");
  185. callback();
  186. return;
  187. }
  188. ctx.font = "30px " + name;
  189. ctx.fillText(".", 0, 20);
  190. const imageData = ctx.getImageData(0, 0, 1, 1);
  191. if (imageData.data[3] > 0) {
  192. callback();
  193. return;
  194. }
  195. setTimeout(isFontReady.bind(null, name, callback));
  196. }
  197. const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`;
  198. let data = this._loadTestFont;
  199. const COMMENT_OFFSET = 976;
  200. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId);
  201. const CFF_CHECKSUM_OFFSET = 16;
  202. const XXXX_VALUE = 0x58585858;
  203. let checksum = int32(data, CFF_CHECKSUM_OFFSET);
  204. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  205. checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0;
  206. }
  207. if (i < loadTestFontId.length) {
  208. checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i) | 0;
  209. }
  210. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, (0, _util.string32)(checksum));
  211. const url = `url(data:font/opentype;base64,${btoa(data)});`;
  212. const rule = `@font-face {font-family:"${loadTestFontId}";src:${url}}`;
  213. this.insertRule(rule);
  214. const names = [];
  215. for (const font of fonts) {
  216. names.push(font.loadedName);
  217. }
  218. names.push(loadTestFontId);
  219. const div = this._document.createElement("div");
  220. div.style.visibility = "hidden";
  221. div.style.width = div.style.height = "10px";
  222. div.style.position = "absolute";
  223. div.style.top = div.style.left = "0px";
  224. for (const name of names) {
  225. const span = this._document.createElement("span");
  226. span.textContent = "Hi";
  227. span.style.fontFamily = name;
  228. div.appendChild(span);
  229. }
  230. this._document.body.appendChild(div);
  231. isFontReady(loadTestFontId, () => {
  232. this._document.body.removeChild(div);
  233. request.complete();
  234. });
  235. }
  236. };
  237. }
  238. class FontFaceObject {
  239. constructor(translatedData, {
  240. isEvalSupported = true,
  241. disableFontFace = false,
  242. ignoreErrors = false,
  243. onUnsupportedFeature,
  244. fontRegistry = null
  245. }) {
  246. this.compiledGlyphs = Object.create(null);
  247. for (const i in translatedData) {
  248. this[i] = translatedData[i];
  249. }
  250. this.isEvalSupported = isEvalSupported !== false;
  251. this.disableFontFace = disableFontFace === true;
  252. this.ignoreErrors = ignoreErrors === true;
  253. this._onUnsupportedFeature = onUnsupportedFeature;
  254. this.fontRegistry = fontRegistry;
  255. }
  256. createNativeFontFace() {
  257. if (!this.data || this.disableFontFace) {
  258. return null;
  259. }
  260. let nativeFontFace;
  261. if (!this.cssFontInfo) {
  262. nativeFontFace = new FontFace(this.loadedName, this.data, {});
  263. } else {
  264. const css = {
  265. weight: this.cssFontInfo.fontWeight
  266. };
  267. if (this.cssFontInfo.italicAngle) {
  268. css.style = `oblique ${this.cssFontInfo.italicAngle}deg`;
  269. }
  270. nativeFontFace = new FontFace(this.cssFontInfo.fontFamily, this.data, css);
  271. }
  272. if (this.fontRegistry) {
  273. this.fontRegistry.registerFont(this);
  274. }
  275. return nativeFontFace;
  276. }
  277. createFontFaceRule() {
  278. if (!this.data || this.disableFontFace) {
  279. return null;
  280. }
  281. const data = (0, _util.bytesToString)(this.data);
  282. const url = `url(data:${this.mimetype};base64,${btoa(data)});`;
  283. let rule;
  284. if (!this.cssFontInfo) {
  285. rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`;
  286. } else {
  287. let css = `font-weight: ${this.cssFontInfo.fontWeight};`;
  288. if (this.cssFontInfo.italicAngle) {
  289. css += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`;
  290. }
  291. rule = `@font-face {font-family:"${this.cssFontInfo.fontFamily}";${css}src:${url}}`;
  292. }
  293. if (this.fontRegistry) {
  294. this.fontRegistry.registerFont(this, url);
  295. }
  296. return rule;
  297. }
  298. getPathGenerator(objs, character) {
  299. if (this.compiledGlyphs[character] !== undefined) {
  300. return this.compiledGlyphs[character];
  301. }
  302. let cmds;
  303. try {
  304. cmds = objs.get(this.loadedName + "_path_" + character);
  305. } catch (ex) {
  306. if (!this.ignoreErrors) {
  307. throw ex;
  308. }
  309. this._onUnsupportedFeature({
  310. featureId: _util.UNSUPPORTED_FEATURES.errorFontGetPath
  311. });
  312. (0, _util.warn)(`getPathGenerator - ignoring character: "${ex}".`);
  313. return this.compiledGlyphs[character] = function (c, size) {};
  314. }
  315. if (this.isEvalSupported && _util.IsEvalSupportedCached.value) {
  316. const jsBuf = [];
  317. for (const current of cmds) {
  318. const args = current.args !== undefined ? current.args.join(",") : "";
  319. jsBuf.push("c.", current.cmd, "(", args, ");\n");
  320. }
  321. return this.compiledGlyphs[character] = new Function("c", "size", jsBuf.join(""));
  322. }
  323. return this.compiledGlyphs[character] = function (c, size) {
  324. for (const current of cmds) {
  325. if (current.cmd === "scale") {
  326. current.args = [size, -size];
  327. }
  328. c[current.cmd].apply(c, current.args);
  329. }
  330. };
  331. }
  332. }
  333. exports.FontFaceObject = FontFaceObject;