font_loader.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2020 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. this.nativeFontFaces.forEach(nativeFontFace => {
  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. const supported = typeof this._document !== "undefined" && !!this._document.fonts;
  106. return (0, _util.shadow)(this, "isFontLoadingAPISupported", supported);
  107. }
  108. get isSyncFontLoadingSupported() {
  109. (0, _util.unreachable)("Abstract method `isSyncFontLoadingSupported`.");
  110. }
  111. get _loadTestFont() {
  112. (0, _util.unreachable)("Abstract method `_loadTestFont`.");
  113. }
  114. _prepareFontLoadEvent(rules, fontsToLoad, request) {
  115. (0, _util.unreachable)("Abstract method `_prepareFontLoadEvent`.");
  116. }
  117. }
  118. let FontLoader;
  119. exports.FontLoader = FontLoader;
  120. {
  121. exports.FontLoader = FontLoader = class GenericFontLoader extends BaseFontLoader {
  122. constructor(params) {
  123. super(params);
  124. this.loadingContext = {
  125. requests: [],
  126. nextRequestId: 0
  127. };
  128. this.loadTestFontId = 0;
  129. }
  130. get isSyncFontLoadingSupported() {
  131. let supported = false;
  132. if (typeof navigator === "undefined") {
  133. supported = true;
  134. } else {
  135. const m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent);
  136. if (m && m[1] >= 14) {
  137. supported = true;
  138. }
  139. }
  140. return (0, _util.shadow)(this, "isSyncFontLoadingSupported", supported);
  141. }
  142. _queueLoadingCallback(callback) {
  143. function completeRequest() {
  144. (0, _util.assert)(!request.done, "completeRequest() cannot be called twice.");
  145. request.done = true;
  146. while (context.requests.length > 0 && context.requests[0].done) {
  147. const otherRequest = context.requests.shift();
  148. setTimeout(otherRequest.callback, 0);
  149. }
  150. }
  151. const context = this.loadingContext;
  152. const request = {
  153. id: `pdfjs-font-loading-${context.nextRequestId++}`,
  154. done: false,
  155. complete: completeRequest,
  156. callback
  157. };
  158. context.requests.push(request);
  159. return request;
  160. }
  161. get _loadTestFont() {
  162. const getLoadTestFont = function () {
  163. return atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQA" + "FQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAA" + "ALwAAAA2aGhlYQdkA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AAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAA" + "AAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQAC" + "AQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3" + "Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTj" + "FQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");
  164. };
  165. return (0, _util.shadow)(this, "_loadTestFont", getLoadTestFont());
  166. }
  167. _prepareFontLoadEvent(rules, fonts, request) {
  168. function int32(data, offset) {
  169. return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff;
  170. }
  171. function spliceString(s, offset, remove, insert) {
  172. const chunk1 = s.substring(0, offset);
  173. const chunk2 = s.substring(offset + remove);
  174. return chunk1 + insert + chunk2;
  175. }
  176. let i, ii;
  177. const canvas = this._document.createElement("canvas");
  178. canvas.width = 1;
  179. canvas.height = 1;
  180. const ctx = canvas.getContext("2d");
  181. let called = 0;
  182. function isFontReady(name, callback) {
  183. called++;
  184. if (called > 30) {
  185. (0, _util.warn)("Load test font never loaded.");
  186. callback();
  187. return;
  188. }
  189. ctx.font = "30px " + name;
  190. ctx.fillText(".", 0, 20);
  191. const imageData = ctx.getImageData(0, 0, 1, 1);
  192. if (imageData.data[3] > 0) {
  193. callback();
  194. return;
  195. }
  196. setTimeout(isFontReady.bind(null, name, callback));
  197. }
  198. const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`;
  199. let data = this._loadTestFont;
  200. const COMMENT_OFFSET = 976;
  201. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId);
  202. const CFF_CHECKSUM_OFFSET = 16;
  203. const XXXX_VALUE = 0x58585858;
  204. let checksum = int32(data, CFF_CHECKSUM_OFFSET);
  205. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  206. checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0;
  207. }
  208. if (i < loadTestFontId.length) {
  209. checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i) | 0;
  210. }
  211. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, (0, _util.string32)(checksum));
  212. const url = `url(data:font/opentype;base64,${btoa(data)});`;
  213. const rule = `@font-face {font-family:"${loadTestFontId}";src:${url}}`;
  214. this.insertRule(rule);
  215. const names = [];
  216. for (i = 0, ii = fonts.length; i < ii; i++) {
  217. names.push(fonts[i].loadedName);
  218. }
  219. names.push(loadTestFontId);
  220. const div = this._document.createElement("div");
  221. div.style.visibility = "hidden";
  222. div.style.width = div.style.height = "10px";
  223. div.style.position = "absolute";
  224. div.style.top = div.style.left = "0px";
  225. for (i = 0, ii = names.length; i < ii; ++i) {
  226. const span = this._document.createElement("span");
  227. span.textContent = "Hi";
  228. span.style.fontFamily = names[i];
  229. div.appendChild(span);
  230. }
  231. this._document.body.appendChild(div);
  232. isFontReady(loadTestFontId, () => {
  233. this._document.body.removeChild(div);
  234. request.complete();
  235. });
  236. }
  237. };
  238. }
  239. class FontFaceObject {
  240. constructor(translatedData, {
  241. isEvalSupported = true,
  242. disableFontFace = false,
  243. ignoreErrors = false,
  244. onUnsupportedFeature = null,
  245. fontRegistry = null
  246. }) {
  247. this.compiledGlyphs = Object.create(null);
  248. for (const i in translatedData) {
  249. this[i] = translatedData[i];
  250. }
  251. this.isEvalSupported = isEvalSupported !== false;
  252. this.disableFontFace = disableFontFace === true;
  253. this.ignoreErrors = ignoreErrors === true;
  254. this._onUnsupportedFeature = onUnsupportedFeature;
  255. this.fontRegistry = fontRegistry;
  256. }
  257. createNativeFontFace() {
  258. if (!this.data || this.disableFontFace) {
  259. return null;
  260. }
  261. const nativeFontFace = new FontFace(this.loadedName, this.data, {});
  262. if (this.fontRegistry) {
  263. this.fontRegistry.registerFont(this);
  264. }
  265. return nativeFontFace;
  266. }
  267. createFontFaceRule() {
  268. if (!this.data || this.disableFontFace) {
  269. return null;
  270. }
  271. const data = (0, _util.bytesToString)(new Uint8Array(this.data));
  272. const url = `url(data:${this.mimetype};base64,${btoa(data)});`;
  273. const rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`;
  274. if (this.fontRegistry) {
  275. this.fontRegistry.registerFont(this, url);
  276. }
  277. return rule;
  278. }
  279. getPathGenerator(objs, character) {
  280. if (this.compiledGlyphs[character] !== undefined) {
  281. return this.compiledGlyphs[character];
  282. }
  283. let cmds, current;
  284. try {
  285. cmds = objs.get(this.loadedName + "_path_" + character);
  286. } catch (ex) {
  287. if (!this.ignoreErrors) {
  288. throw ex;
  289. }
  290. if (this._onUnsupportedFeature) {
  291. this._onUnsupportedFeature({
  292. featureId: _util.UNSUPPORTED_FEATURES.errorFontGetPath
  293. });
  294. }
  295. (0, _util.warn)(`getPathGenerator - ignoring character: "${ex}".`);
  296. return this.compiledGlyphs[character] = function (c, size) {};
  297. }
  298. if (this.isEvalSupported && _util.IsEvalSupportedCached.value) {
  299. let args,
  300. js = "";
  301. for (let i = 0, ii = cmds.length; i < ii; i++) {
  302. current = cmds[i];
  303. if (current.args !== undefined) {
  304. args = current.args.join(",");
  305. } else {
  306. args = "";
  307. }
  308. js += "c." + current.cmd + "(" + args + ");\n";
  309. }
  310. return this.compiledGlyphs[character] = new Function("c", "size", js);
  311. }
  312. return this.compiledGlyphs[character] = function (c, size) {
  313. for (let i = 0, ii = cmds.length; i < ii; i++) {
  314. current = cmds[i];
  315. if (current.cmd === "scale") {
  316. current.args = [size, -size];
  317. }
  318. c[current.cmd].apply(c, current.args);
  319. }
  320. };
  321. }
  322. }
  323. exports.FontFaceObject = FontFaceObject;