font_loader.js 13 KB

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