-
Notifications
You must be signed in to change notification settings - Fork 10.2k
/
Copy pathdisplay_utils.js
686 lines (622 loc) · 19.2 KB
/
display_utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
/* Copyright 2015 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
BaseException,
FeatureTest,
shadow,
Util,
warn,
} from "../shared/util.js";
const SVG_NS = "http://www.w3.org/2000/svg";
class PixelsPerInch {
static CSS = 96.0;
static PDF = 72.0;
static PDF_TO_CSS_UNITS = this.CSS / this.PDF;
}
async function fetchData(url, type = "text") {
if (
(typeof PDFJSDev !== "undefined" && PDFJSDev.test("MOZCENTRAL")) ||
isValidFetchUrl(url, document.baseURI)
) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(response.statusText);
}
switch (type) {
case "arraybuffer":
return response.arrayBuffer();
case "blob":
return response.blob();
case "json":
return response.json();
}
return response.text();
}
// The Fetch API is not supported.
return new Promise((resolve, reject) => {
const request = new XMLHttpRequest();
request.open("GET", url, /* async = */ true);
request.responseType = type;
request.onreadystatechange = () => {
if (request.readyState !== XMLHttpRequest.DONE) {
return;
}
if (request.status === 200 || request.status === 0) {
switch (type) {
case "arraybuffer":
case "blob":
case "json":
resolve(request.response);
return;
}
resolve(request.responseText);
return;
}
reject(new Error(request.statusText));
};
request.send(null);
});
}
/**
* @typedef {Object} PageViewportParameters
* @property {Array<number>} viewBox - The xMin, yMin, xMax and
* yMax coordinates.
* @property {number} userUnit - The size of units.
* @property {number} scale - The scale of the viewport.
* @property {number} rotation - The rotation, in degrees, of the viewport.
* @property {number} [offsetX] - The horizontal, i.e. x-axis, offset. The
* default value is `0`.
* @property {number} [offsetY] - The vertical, i.e. y-axis, offset. The
* default value is `0`.
* @property {boolean} [dontFlip] - If true, the y-axis will not be flipped.
* The default value is `false`.
*/
/**
* @typedef {Object} PageViewportCloneParameters
* @property {number} [scale] - The scale, overriding the one in the cloned
* viewport. The default value is `this.scale`.
* @property {number} [rotation] - The rotation, in degrees, overriding the one
* in the cloned viewport. The default value is `this.rotation`.
* @property {number} [offsetX] - The horizontal, i.e. x-axis, offset.
* The default value is `this.offsetX`.
* @property {number} [offsetY] - The vertical, i.e. y-axis, offset.
* The default value is `this.offsetY`.
* @property {boolean} [dontFlip] - If true, the x-axis will not be flipped.
* The default value is `false`.
*/
/**
* PDF page viewport created based on scale, rotation and offset.
*/
class PageViewport {
/**
* @param {PageViewportParameters}
*/
constructor({
viewBox,
userUnit,
scale,
rotation,
offsetX = 0,
offsetY = 0,
dontFlip = false,
}) {
this.viewBox = viewBox;
this.userUnit = userUnit;
this.scale = scale;
this.rotation = rotation;
this.offsetX = offsetX;
this.offsetY = offsetY;
scale *= userUnit; // Take the userUnit into account.
// creating transform to convert pdf coordinate system to the normal
// canvas like coordinates taking in account scale and rotation
const centerX = (viewBox[2] + viewBox[0]) / 2;
const centerY = (viewBox[3] + viewBox[1]) / 2;
let rotateA, rotateB, rotateC, rotateD;
// Normalize the rotation, by clamping it to the [0, 360) range.
rotation %= 360;
if (rotation < 0) {
rotation += 360;
}
switch (rotation) {
case 180:
rotateA = -1;
rotateB = 0;
rotateC = 0;
rotateD = 1;
break;
case 90:
rotateA = 0;
rotateB = 1;
rotateC = 1;
rotateD = 0;
break;
case 270:
rotateA = 0;
rotateB = -1;
rotateC = -1;
rotateD = 0;
break;
case 0:
rotateA = 1;
rotateB = 0;
rotateC = 0;
rotateD = -1;
break;
default:
throw new Error(
"PageViewport: Invalid rotation, must be a multiple of 90 degrees."
);
}
if (dontFlip) {
rotateC = -rotateC;
rotateD = -rotateD;
}
let offsetCanvasX, offsetCanvasY;
let width, height;
if (rotateA === 0) {
offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
width = (viewBox[3] - viewBox[1]) * scale;
height = (viewBox[2] - viewBox[0]) * scale;
} else {
offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
width = (viewBox[2] - viewBox[0]) * scale;
height = (viewBox[3] - viewBox[1]) * scale;
}
// creating transform for the following operations:
// translate(-centerX, -centerY), rotate and flip vertically,
// scale, and translate(offsetCanvasX, offsetCanvasY)
this.transform = [
rotateA * scale,
rotateB * scale,
rotateC * scale,
rotateD * scale,
offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,
offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY,
];
this.width = width;
this.height = height;
}
/**
* The original, un-scaled, viewport dimensions.
* @type {Object}
*/
get rawDims() {
const dims = this.viewBox;
return shadow(this, "rawDims", {
pageWidth: dims[2] - dims[0],
pageHeight: dims[3] - dims[1],
pageX: dims[0],
pageY: dims[1],
});
}
/**
* Clones viewport, with optional additional properties.
* @param {PageViewportCloneParameters} [params]
* @returns {PageViewport} Cloned viewport.
*/
clone({
scale = this.scale,
rotation = this.rotation,
offsetX = this.offsetX,
offsetY = this.offsetY,
dontFlip = false,
} = {}) {
return new PageViewport({
viewBox: this.viewBox.slice(),
userUnit: this.userUnit,
scale,
rotation,
offsetX,
offsetY,
dontFlip,
});
}
/**
* Converts PDF point to the viewport coordinates. For examples, useful for
* converting PDF location into canvas pixel coordinates.
* @param {number} x - The x-coordinate.
* @param {number} y - The y-coordinate.
* @returns {Array} Array containing `x`- and `y`-coordinates of the
* point in the viewport coordinate space.
* @see {@link convertToPdfPoint}
* @see {@link convertToViewportRectangle}
*/
convertToViewportPoint(x, y) {
return Util.applyTransform([x, y], this.transform);
}
/**
* Converts PDF rectangle to the viewport coordinates.
* @param {Array} rect - The xMin, yMin, xMax and yMax coordinates.
* @returns {Array} Array containing corresponding coordinates of the
* rectangle in the viewport coordinate space.
* @see {@link convertToViewportPoint}
*/
convertToViewportRectangle(rect) {
const topLeft = Util.applyTransform([rect[0], rect[1]], this.transform);
const bottomRight = Util.applyTransform([rect[2], rect[3]], this.transform);
return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
}
/**
* Converts viewport coordinates to the PDF location. For examples, useful
* for converting canvas pixel location into PDF one.
* @param {number} x - The x-coordinate.
* @param {number} y - The y-coordinate.
* @returns {Array} Array containing `x`- and `y`-coordinates of the
* point in the PDF coordinate space.
* @see {@link convertToViewportPoint}
*/
convertToPdfPoint(x, y) {
return Util.applyInverseTransform([x, y], this.transform);
}
}
class RenderingCancelledException extends BaseException {
constructor(msg, extraDelay = 0) {
super(msg, "RenderingCancelledException");
this.extraDelay = extraDelay;
}
}
function isDataScheme(url) {
const ii = url.length;
let i = 0;
while (i < ii && url[i].trim() === "") {
i++;
}
return url.substring(i, i + 5).toLowerCase() === "data:";
}
function isPdfFile(filename) {
return typeof filename === "string" && /\.pdf$/i.test(filename);
}
/**
* Gets the filename from a given URL.
* @param {string} url
* @returns {string}
*/
function getFilenameFromUrl(url) {
[url] = url.split(/[#?]/, 1);
return url.substring(url.lastIndexOf("/") + 1);
}
/**
* Returns the filename or guessed filename from the url (see issue 3455).
* @param {string} url - The original PDF location.
* @param {string} defaultFilename - The value returned if the filename is
* unknown, or the protocol is unsupported.
* @returns {string} Guessed PDF filename.
*/
function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") {
if (typeof url !== "string") {
return defaultFilename;
}
if (isDataScheme(url)) {
warn('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');
return defaultFilename;
}
const reURI = /^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
// SCHEME HOST 1.PATH 2.QUERY 3.REF
// Pattern to get last matching NAME.pdf
const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
const splitURI = reURI.exec(url);
let suggestedFilename =
reFilename.exec(splitURI[1]) ||
reFilename.exec(splitURI[2]) ||
reFilename.exec(splitURI[3]);
if (suggestedFilename) {
suggestedFilename = suggestedFilename[0];
if (suggestedFilename.includes("%")) {
// URL-encoded %2Fpath%2Fto%2Ffile.pdf should be file.pdf
try {
suggestedFilename = reFilename.exec(
decodeURIComponent(suggestedFilename)
)[0];
} catch {
// Possible (extremely rare) errors:
// URIError "Malformed URI", e.g. for "%AA.pdf"
// TypeError "null has no properties", e.g. for "%2F.pdf"
}
}
}
return suggestedFilename || defaultFilename;
}
class StatTimer {
started = Object.create(null);
times = [];
time(name) {
if (name in this.started) {
warn(`Timer is already running for ${name}`);
}
this.started[name] = Date.now();
}
timeEnd(name) {
if (!(name in this.started)) {
warn(`Timer has not been started for ${name}`);
}
this.times.push({
name,
start: this.started[name],
end: Date.now(),
});
// Remove timer from started so it can be called again.
delete this.started[name];
}
toString() {
// Find the longest name for padding purposes.
const outBuf = [];
let longest = 0;
for (const { name } of this.times) {
longest = Math.max(name.length, longest);
}
for (const { name, start, end } of this.times) {
outBuf.push(`${name.padEnd(longest)} ${end - start}ms\n`);
}
return outBuf.join("");
}
}
function isValidFetchUrl(url, baseUrl) {
if (typeof PDFJSDev !== "undefined" && PDFJSDev.test("MOZCENTRAL")) {
throw new Error("Not implemented: isValidFetchUrl");
}
const res = baseUrl ? URL.parse(url, baseUrl) : URL.parse(url);
// The Fetch API only supports the http/https protocols, and not file/ftp.
return res?.protocol === "http:" || res?.protocol === "https:";
}
/**
* Event handler to suppress context menu.
*/
function noContextMenu(e) {
e.preventDefault();
}
function stopEvent(e) {
e.preventDefault();
e.stopPropagation();
}
// Deprecated API function -- display regardless of the `verbosity` setting.
function deprecated(details) {
// eslint-disable-next-line no-console
console.log("Deprecated API usage: " + details);
}
class PDFDateString {
static #regex;
/**
* Convert a PDF date string to a JavaScript `Date` object.
*
* The PDF date string format is described in section 7.9.4 of the official
* PDF 32000-1:2008 specification. However, in the PDF 1.7 reference (sixth
* edition) Adobe describes the same format including a trailing apostrophe.
* This syntax in incorrect, but Adobe Acrobat creates PDF files that contain
* them. We ignore all apostrophes as they are not necessary for date parsing.
*
* Moreover, Adobe Acrobat doesn't handle changing the date to universal time
* and doesn't use the user's time zone (effectively ignoring the HH' and mm'
* parts of the date string).
*
* @param {string} input
* @returns {Date|null}
*/
static toDateObject(input) {
if (!input || typeof input !== "string") {
return null;
}
// Lazily initialize the regular expression.
this.#regex ||= new RegExp(
"^D:" + // Prefix (required)
"(\\d{4})" + // Year (required)
"(\\d{2})?" + // Month (optional)
"(\\d{2})?" + // Day (optional)
"(\\d{2})?" + // Hour (optional)
"(\\d{2})?" + // Minute (optional)
"(\\d{2})?" + // Second (optional)
"([Z|+|-])?" + // Universal time relation (optional)
"(\\d{2})?" + // Offset hour (optional)
"'?" + // Splitting apostrophe (optional)
"(\\d{2})?" + // Offset minute (optional)
"'?" // Trailing apostrophe (optional)
);
// Optional fields that don't satisfy the requirements from the regular
// expression (such as incorrect digit counts or numbers that are out of
// range) will fall back the defaults from the specification.
const matches = this.#regex.exec(input);
if (!matches) {
return null;
}
// JavaScript's `Date` object expects the month to be between 0 and 11
// instead of 1 and 12, so we have to correct for that.
const year = parseInt(matches[1], 10);
let month = parseInt(matches[2], 10);
month = month >= 1 && month <= 12 ? month - 1 : 0;
let day = parseInt(matches[3], 10);
day = day >= 1 && day <= 31 ? day : 1;
let hour = parseInt(matches[4], 10);
hour = hour >= 0 && hour <= 23 ? hour : 0;
let minute = parseInt(matches[5], 10);
minute = minute >= 0 && minute <= 59 ? minute : 0;
let second = parseInt(matches[6], 10);
second = second >= 0 && second <= 59 ? second : 0;
const universalTimeRelation = matches[7] || "Z";
let offsetHour = parseInt(matches[8], 10);
offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
let offsetMinute = parseInt(matches[9], 10) || 0;
offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
// Universal time relation 'Z' means that the local time is equal to the
// universal time, whereas the relations '+'/'-' indicate that the local
// time is later respectively earlier than the universal time. Every date
// is normalized to universal time.
if (universalTimeRelation === "-") {
hour += offsetHour;
minute += offsetMinute;
} else if (universalTimeRelation === "+") {
hour -= offsetHour;
minute -= offsetMinute;
}
return new Date(Date.UTC(year, month, day, hour, minute, second));
}
}
/**
* NOTE: This is (mostly) intended to support printing of XFA forms.
*/
function getXfaPageViewport(xfaPage, { scale = 1, rotation = 0 }) {
const { width, height } = xfaPage.attributes.style;
const viewBox = [0, 0, parseInt(width), parseInt(height)];
return new PageViewport({
viewBox,
userUnit: 1,
scale,
rotation,
});
}
function getRGB(color) {
if (color.startsWith("#")) {
const colorRGB = parseInt(color.slice(1), 16);
return [
(colorRGB & 0xff0000) >> 16,
(colorRGB & 0x00ff00) >> 8,
colorRGB & 0x0000ff,
];
}
if (color.startsWith("rgb(")) {
// getComputedStyle(...).color returns a `rgb(R, G, B)` color.
return color
.slice(/* "rgb(".length */ 4, -1) // Strip out "rgb(" and ")".
.split(",")
.map(x => parseInt(x));
}
if (color.startsWith("rgba(")) {
return color
.slice(/* "rgba(".length */ 5, -1) // Strip out "rgba(" and ")".
.split(",")
.map(x => parseInt(x))
.slice(0, 3);
}
warn(`Not a valid color format: "${color}"`);
return [0, 0, 0];
}
function getColorValues(colors) {
const span = document.createElement("span");
span.style.visibility = "hidden";
document.body.append(span);
for (const name of colors.keys()) {
span.style.color = name;
const computedColor = window.getComputedStyle(span).color;
colors.set(name, getRGB(computedColor));
}
span.remove();
}
function getCurrentTransform(ctx) {
const { a, b, c, d, e, f } = ctx.getTransform();
return [a, b, c, d, e, f];
}
function getCurrentTransformInverse(ctx) {
const { a, b, c, d, e, f } = ctx.getTransform().invertSelf();
return [a, b, c, d, e, f];
}
/**
* @param {HTMLDivElement} div
* @param {PageViewport} viewport
* @param {boolean} mustFlip
* @param {boolean} mustRotate
*/
function setLayerDimensions(
div,
viewport,
mustFlip = false,
mustRotate = true
) {
if (viewport instanceof PageViewport) {
const { pageWidth, pageHeight } = viewport.rawDims;
const { style } = div;
const useRound = FeatureTest.isCSSRoundSupported;
const w = `var(--total-scale-factor) * ${pageWidth}px`,
h = `var(--total-scale-factor) * ${pageHeight}px`;
const widthStr = useRound
? `round(down, ${w}, var(--scale-round-x))`
: `calc(${w})`,
heightStr = useRound
? `round(down, ${h}, var(--scale-round-y))`
: `calc(${h})`;
if (!mustFlip || viewport.rotation % 180 === 0) {
style.width = widthStr;
style.height = heightStr;
} else {
style.width = heightStr;
style.height = widthStr;
}
}
if (mustRotate) {
div.setAttribute("data-main-rotation", viewport.rotation);
}
}
/**
* Scale factors for the canvas, necessary with HiDPI displays.
*/
class OutputScale {
constructor() {
const pixelRatio = window.devicePixelRatio || 1;
/**
* @type {number} Horizontal scale.
*/
this.sx = pixelRatio;
/**
* @type {number} Vertical scale.
*/
this.sy = pixelRatio;
}
/**
* @type {boolean} Returns `true` when scaling is required, `false` otherwise.
*/
get scaled() {
return this.sx !== 1 || this.sy !== 1;
}
get symmetric() {
return this.sx === this.sy;
}
}
// See https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types
// to know which types are supported by the browser.
const SupportedImageMimeTypes = [
"image/apng",
"image/avif",
"image/bmp",
"image/gif",
"image/jpeg",
"image/png",
"image/svg+xml",
"image/webp",
"image/x-icon",
];
export {
deprecated,
fetchData,
getColorValues,
getCurrentTransform,
getCurrentTransformInverse,
getFilenameFromUrl,
getPdfFilenameFromUrl,
getRGB,
getXfaPageViewport,
isDataScheme,
isPdfFile,
isValidFetchUrl,
noContextMenu,
OutputScale,
PageViewport,
PDFDateString,
PixelsPerInch,
RenderingCancelledException,
setLayerDimensions,
StatTimer,
stopEvent,
SupportedImageMimeTypes,
SVG_NS,
};