display_utils.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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.addLinkAttributes = addLinkAttributes;
  27. exports.getFilenameFromUrl = getFilenameFromUrl;
  28. exports.isFetchSupported = isFetchSupported;
  29. exports.isValidFetchUrl = isValidFetchUrl;
  30. exports.loadScript = loadScript;
  31. exports.deprecated = deprecated;
  32. exports.releaseImageResources = releaseImageResources;
  33. exports.PDFDateString = exports.StatTimer = exports.DOMSVGFactory = exports.DOMCMapReaderFactory = exports.DOMCanvasFactory = exports.DEFAULT_LINK_REL = exports.LinkTarget = exports.RenderingCancelledException = exports.PageViewport = void 0;
  34. var _util = require("../shared/util.js");
  35. const DEFAULT_LINK_REL = "noopener noreferrer nofollow";
  36. exports.DEFAULT_LINK_REL = DEFAULT_LINK_REL;
  37. const SVG_NS = "http://www.w3.org/2000/svg";
  38. class DOMCanvasFactory {
  39. create(width, height) {
  40. if (width <= 0 || height <= 0) {
  41. throw new Error("Invalid canvas size");
  42. }
  43. const canvas = document.createElement("canvas");
  44. const context = canvas.getContext("2d");
  45. canvas.width = width;
  46. canvas.height = height;
  47. return {
  48. canvas,
  49. context
  50. };
  51. }
  52. reset(canvasAndContext, width, height) {
  53. if (!canvasAndContext.canvas) {
  54. throw new Error("Canvas is not specified");
  55. }
  56. if (width <= 0 || height <= 0) {
  57. throw new Error("Invalid canvas size");
  58. }
  59. canvasAndContext.canvas.width = width;
  60. canvasAndContext.canvas.height = height;
  61. }
  62. destroy(canvasAndContext) {
  63. if (!canvasAndContext.canvas) {
  64. throw new Error("Canvas is not specified");
  65. }
  66. canvasAndContext.canvas.width = 0;
  67. canvasAndContext.canvas.height = 0;
  68. canvasAndContext.canvas = null;
  69. canvasAndContext.context = null;
  70. }
  71. }
  72. exports.DOMCanvasFactory = DOMCanvasFactory;
  73. class DOMCMapReaderFactory {
  74. constructor({
  75. baseUrl = null,
  76. isCompressed = false
  77. }) {
  78. this.baseUrl = baseUrl;
  79. this.isCompressed = isCompressed;
  80. }
  81. async fetch({
  82. name
  83. }) {
  84. if (!this.baseUrl) {
  85. throw new Error('The CMap "baseUrl" parameter must be specified, ensure that ' + 'the "cMapUrl" and "cMapPacked" API parameters are provided.');
  86. }
  87. if (!name) {
  88. throw new Error("CMap name must be specified.");
  89. }
  90. const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : "");
  91. const compressionType = this.isCompressed ? _util.CMapCompressionType.BINARY : _util.CMapCompressionType.NONE;
  92. if (isFetchSupported() && isValidFetchUrl(url, document.baseURI)) {
  93. return fetch(url).then(async response => {
  94. if (!response.ok) {
  95. throw new Error(response.statusText);
  96. }
  97. let cMapData;
  98. if (this.isCompressed) {
  99. cMapData = new Uint8Array((await response.arrayBuffer()));
  100. } else {
  101. cMapData = (0, _util.stringToBytes)((await response.text()));
  102. }
  103. return {
  104. cMapData,
  105. compressionType
  106. };
  107. }).catch(reason => {
  108. throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}` + `CMap at: ${url}`);
  109. });
  110. }
  111. return new Promise((resolve, reject) => {
  112. const request = new XMLHttpRequest();
  113. request.open("GET", url, true);
  114. if (this.isCompressed) {
  115. request.responseType = "arraybuffer";
  116. }
  117. request.onreadystatechange = () => {
  118. if (request.readyState !== XMLHttpRequest.DONE) {
  119. return;
  120. }
  121. if (request.status === 200 || request.status === 0) {
  122. let cMapData;
  123. if (this.isCompressed && request.response) {
  124. cMapData = new Uint8Array(request.response);
  125. } else if (!this.isCompressed && request.responseText) {
  126. cMapData = (0, _util.stringToBytes)(request.responseText);
  127. }
  128. if (cMapData) {
  129. resolve({
  130. cMapData,
  131. compressionType
  132. });
  133. return;
  134. }
  135. }
  136. reject(new Error(request.statusText));
  137. };
  138. request.send(null);
  139. }).catch(reason => {
  140. throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}` + `CMap at: ${url}`);
  141. });
  142. }
  143. }
  144. exports.DOMCMapReaderFactory = DOMCMapReaderFactory;
  145. class DOMSVGFactory {
  146. create(width, height) {
  147. (0, _util.assert)(width > 0 && height > 0, "Invalid SVG dimensions");
  148. const svg = document.createElementNS(SVG_NS, "svg:svg");
  149. svg.setAttribute("version", "1.1");
  150. svg.setAttribute("width", width + "px");
  151. svg.setAttribute("height", height + "px");
  152. svg.setAttribute("preserveAspectRatio", "none");
  153. svg.setAttribute("viewBox", "0 0 " + width + " " + height);
  154. return svg;
  155. }
  156. createElement(type) {
  157. (0, _util.assert)(typeof type === "string", "Invalid SVG element type");
  158. return document.createElementNS(SVG_NS, type);
  159. }
  160. }
  161. exports.DOMSVGFactory = DOMSVGFactory;
  162. class PageViewport {
  163. constructor({
  164. viewBox,
  165. scale,
  166. rotation,
  167. offsetX = 0,
  168. offsetY = 0,
  169. dontFlip = false
  170. }) {
  171. this.viewBox = viewBox;
  172. this.scale = scale;
  173. this.rotation = rotation;
  174. this.offsetX = offsetX;
  175. this.offsetY = offsetY;
  176. const centerX = (viewBox[2] + viewBox[0]) / 2;
  177. const centerY = (viewBox[3] + viewBox[1]) / 2;
  178. let rotateA, rotateB, rotateC, rotateD;
  179. rotation = rotation % 360;
  180. rotation = rotation < 0 ? rotation + 360 : rotation;
  181. switch (rotation) {
  182. case 180:
  183. rotateA = -1;
  184. rotateB = 0;
  185. rotateC = 0;
  186. rotateD = 1;
  187. break;
  188. case 90:
  189. rotateA = 0;
  190. rotateB = 1;
  191. rotateC = 1;
  192. rotateD = 0;
  193. break;
  194. case 270:
  195. rotateA = 0;
  196. rotateB = -1;
  197. rotateC = -1;
  198. rotateD = 0;
  199. break;
  200. default:
  201. rotateA = 1;
  202. rotateB = 0;
  203. rotateC = 0;
  204. rotateD = -1;
  205. break;
  206. }
  207. if (dontFlip) {
  208. rotateC = -rotateC;
  209. rotateD = -rotateD;
  210. }
  211. let offsetCanvasX, offsetCanvasY;
  212. let width, height;
  213. if (rotateA === 0) {
  214. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  215. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  216. width = Math.abs(viewBox[3] - viewBox[1]) * scale;
  217. height = Math.abs(viewBox[2] - viewBox[0]) * scale;
  218. } else {
  219. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  220. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  221. width = Math.abs(viewBox[2] - viewBox[0]) * scale;
  222. height = Math.abs(viewBox[3] - viewBox[1]) * scale;
  223. }
  224. this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
  225. this.width = width;
  226. this.height = height;
  227. }
  228. clone({
  229. scale = this.scale,
  230. rotation = this.rotation,
  231. offsetX = this.offsetX,
  232. offsetY = this.offsetY,
  233. dontFlip = false
  234. } = {}) {
  235. return new PageViewport({
  236. viewBox: this.viewBox.slice(),
  237. scale,
  238. rotation,
  239. offsetX,
  240. offsetY,
  241. dontFlip
  242. });
  243. }
  244. convertToViewportPoint(x, y) {
  245. return _util.Util.applyTransform([x, y], this.transform);
  246. }
  247. convertToViewportRectangle(rect) {
  248. const topLeft = _util.Util.applyTransform([rect[0], rect[1]], this.transform);
  249. const bottomRight = _util.Util.applyTransform([rect[2], rect[3]], this.transform);
  250. return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
  251. }
  252. convertToPdfPoint(x, y) {
  253. return _util.Util.applyInverseTransform([x, y], this.transform);
  254. }
  255. }
  256. exports.PageViewport = PageViewport;
  257. class RenderingCancelledException extends _util.BaseException {
  258. constructor(msg, type) {
  259. super(msg);
  260. this.type = type;
  261. }
  262. }
  263. exports.RenderingCancelledException = RenderingCancelledException;
  264. const LinkTarget = {
  265. NONE: 0,
  266. SELF: 1,
  267. BLANK: 2,
  268. PARENT: 3,
  269. TOP: 4
  270. };
  271. exports.LinkTarget = LinkTarget;
  272. function addLinkAttributes(link, {
  273. url,
  274. target,
  275. rel,
  276. enabled = true
  277. } = {}) {
  278. (0, _util.assert)(url && typeof url === "string", 'addLinkAttributes: A valid "url" parameter must provided.');
  279. const urlNullRemoved = (0, _util.removeNullCharacters)(url);
  280. if (enabled) {
  281. link.href = link.title = urlNullRemoved;
  282. } else {
  283. link.href = "";
  284. link.title = `Disabled: ${urlNullRemoved}`;
  285. link.onclick = () => {
  286. return false;
  287. };
  288. }
  289. let targetStr = "";
  290. switch (target) {
  291. case LinkTarget.NONE:
  292. break;
  293. case LinkTarget.SELF:
  294. targetStr = "_self";
  295. break;
  296. case LinkTarget.BLANK:
  297. targetStr = "_blank";
  298. break;
  299. case LinkTarget.PARENT:
  300. targetStr = "_parent";
  301. break;
  302. case LinkTarget.TOP:
  303. targetStr = "_top";
  304. break;
  305. }
  306. link.target = targetStr;
  307. link.rel = typeof rel === "string" ? rel : DEFAULT_LINK_REL;
  308. }
  309. function getFilenameFromUrl(url) {
  310. const anchor = url.indexOf("#");
  311. const query = url.indexOf("?");
  312. const end = Math.min(anchor > 0 ? anchor : url.length, query > 0 ? query : url.length);
  313. return url.substring(url.lastIndexOf("/", end) + 1, end);
  314. }
  315. class StatTimer {
  316. constructor() {
  317. this.started = Object.create(null);
  318. this.times = [];
  319. }
  320. time(name) {
  321. if (name in this.started) {
  322. (0, _util.warn)(`Timer is already running for ${name}`);
  323. }
  324. this.started[name] = Date.now();
  325. }
  326. timeEnd(name) {
  327. if (!(name in this.started)) {
  328. (0, _util.warn)(`Timer has not been started for ${name}`);
  329. }
  330. this.times.push({
  331. name,
  332. start: this.started[name],
  333. end: Date.now()
  334. });
  335. delete this.started[name];
  336. }
  337. toString() {
  338. const outBuf = [];
  339. let longest = 0;
  340. for (const time of this.times) {
  341. const name = time.name;
  342. if (name.length > longest) {
  343. longest = name.length;
  344. }
  345. }
  346. for (const time of this.times) {
  347. const duration = time.end - time.start;
  348. outBuf.push(`${time.name.padEnd(longest)} ${duration}ms\n`);
  349. }
  350. return outBuf.join("");
  351. }
  352. }
  353. exports.StatTimer = StatTimer;
  354. function isFetchSupported() {
  355. return typeof fetch !== "undefined" && typeof Response !== "undefined" && "body" in Response.prototype && typeof ReadableStream !== "undefined";
  356. }
  357. function isValidFetchUrl(url, baseUrl) {
  358. try {
  359. const {
  360. protocol
  361. } = baseUrl ? new URL(url, baseUrl) : new URL(url);
  362. return protocol === "http:" || protocol === "https:";
  363. } catch (ex) {
  364. return false;
  365. }
  366. }
  367. function loadScript(src) {
  368. return new Promise((resolve, reject) => {
  369. const script = document.createElement("script");
  370. script.src = src;
  371. script.onload = resolve;
  372. script.onerror = function () {
  373. reject(new Error(`Cannot load script at: ${script.src}`));
  374. };
  375. (document.head || document.documentElement).appendChild(script);
  376. });
  377. }
  378. function deprecated(details) {
  379. console.log("Deprecated API usage: " + details);
  380. }
  381. function releaseImageResources(img) {
  382. (0, _util.assert)(img instanceof Image, "Invalid `img` parameter.");
  383. const url = img.src;
  384. if (typeof url === "string" && url.startsWith("blob:") && URL.revokeObjectURL) {
  385. URL.revokeObjectURL(url);
  386. }
  387. img.removeAttribute("src");
  388. }
  389. let pdfDateStringRegex;
  390. class PDFDateString {
  391. static toDateObject(input) {
  392. if (!input || !(0, _util.isString)(input)) {
  393. return null;
  394. }
  395. if (!pdfDateStringRegex) {
  396. pdfDateStringRegex = new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?");
  397. }
  398. const matches = pdfDateStringRegex.exec(input);
  399. if (!matches) {
  400. return null;
  401. }
  402. const year = parseInt(matches[1], 10);
  403. let month = parseInt(matches[2], 10);
  404. month = month >= 1 && month <= 12 ? month - 1 : 0;
  405. let day = parseInt(matches[3], 10);
  406. day = day >= 1 && day <= 31 ? day : 1;
  407. let hour = parseInt(matches[4], 10);
  408. hour = hour >= 0 && hour <= 23 ? hour : 0;
  409. let minute = parseInt(matches[5], 10);
  410. minute = minute >= 0 && minute <= 59 ? minute : 0;
  411. let second = parseInt(matches[6], 10);
  412. second = second >= 0 && second <= 59 ? second : 0;
  413. const universalTimeRelation = matches[7] || "Z";
  414. let offsetHour = parseInt(matches[8], 10);
  415. offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
  416. let offsetMinute = parseInt(matches[9], 10) || 0;
  417. offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
  418. if (universalTimeRelation === "-") {
  419. hour += offsetHour;
  420. minute += offsetMinute;
  421. } else if (universalTimeRelation === "+") {
  422. hour -= offsetHour;
  423. minute -= offsetMinute;
  424. }
  425. return new Date(Date.UTC(year, month, day, hour, minute, second));
  426. }
  427. }
  428. exports.PDFDateString = PDFDateString;