font_loader.js 12 KB

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