Debian Codegraph @

src/foliate-js/vendor/pdfjs/pdf.mjs

raw
1 /**
2 * @licstart The following is the entire license notice for the
3 * JavaScript code in this page
4 *
5 * Copyright 2024 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
23 /******/ // The require scope
24 /******/ var __webpack_require__ = {};
25 /******/
26 /************************************************************************/
27 /******/ /* webpack/runtime/define property getters */
28 /******/ (() => {
29 /******/ // define getter functions for harmony exports
30 /******/ __webpack_require__.d = (exports, definition) => {
31 /******/ for(var key in definition) {
32 /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
33 /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
34 /******/ }
35 /******/ }
36 /******/ };
37 /******/ })();
38 /******/
39 /******/ /* webpack/runtime/hasOwnProperty shorthand */
40 /******/ (() => {
41 /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
42 /******/ })();
43 /******/
44 /************************************************************************/
45 var __webpack_exports__ = globalThis.pdfjsLib = {};
46
47 // EXPORTS
48 __webpack_require__.d(__webpack_exports__, {
49 AbortException: () => (/* reexport */ AbortException),
50 AnnotationEditorLayer: () => (/* reexport */ AnnotationEditorLayer),
51 AnnotationEditorParamsType: () => (/* reexport */ AnnotationEditorParamsType),
52 AnnotationEditorType: () => (/* reexport */ AnnotationEditorType),
53 AnnotationEditorUIManager: () => (/* reexport */ AnnotationEditorUIManager),
54 AnnotationLayer: () => (/* reexport */ AnnotationLayer),
55 AnnotationMode: () => (/* reexport */ AnnotationMode),
56 CMapCompressionType: () => (/* reexport */ CMapCompressionType),
57 ColorPicker: () => (/* reexport */ ColorPicker),
58 DOMSVGFactory: () => (/* reexport */ DOMSVGFactory),
59 DrawLayer: () => (/* reexport */ DrawLayer),
60 FeatureTest: () => (/* reexport */ util_FeatureTest),
61 GlobalWorkerOptions: () => (/* reexport */ GlobalWorkerOptions),
62 ImageKind: () => (/* reexport */ util_ImageKind),
63 InvalidPDFException: () => (/* reexport */ InvalidPDFException),
64 MissingPDFException: () => (/* reexport */ MissingPDFException),
65 OPS: () => (/* reexport */ OPS),
66 OutputScale: () => (/* reexport */ OutputScale),
67 PDFDataRangeTransport: () => (/* reexport */ PDFDataRangeTransport),
68 PDFDateString: () => (/* reexport */ PDFDateString),
69 PDFWorker: () => (/* reexport */ PDFWorker),
70 PasswordResponses: () => (/* reexport */ PasswordResponses),
71 PermissionFlag: () => (/* reexport */ PermissionFlag),
72 PixelsPerInch: () => (/* reexport */ PixelsPerInch),
73 RenderingCancelledException: () => (/* reexport */ RenderingCancelledException),
74 TextLayer: () => (/* reexport */ TextLayer),
75 UnexpectedResponseException: () => (/* reexport */ UnexpectedResponseException),
76 Util: () => (/* reexport */ Util),
77 VerbosityLevel: () => (/* reexport */ VerbosityLevel),
78 XfaLayer: () => (/* reexport */ XfaLayer),
79 build: () => (/* reexport */ build),
80 createValidAbsoluteUrl: () => (/* reexport */ createValidAbsoluteUrl),
81 fetchData: () => (/* reexport */ fetchData),
82 getDocument: () => (/* reexport */ getDocument),
83 getFilenameFromUrl: () => (/* reexport */ getFilenameFromUrl),
84 getPdfFilenameFromUrl: () => (/* reexport */ getPdfFilenameFromUrl),
85 getXfaPageViewport: () => (/* reexport */ getXfaPageViewport),
86 isDataScheme: () => (/* reexport */ isDataScheme),
87 isPdfFile: () => (/* reexport */ isPdfFile),
88 noContextMenu: () => (/* reexport */ noContextMenu),
89 normalizeUnicode: () => (/* reexport */ normalizeUnicode),
90 setLayerDimensions: () => (/* reexport */ setLayerDimensions),
91 shadow: () => (/* reexport */ shadow),
92 version: () => (/* reexport */ version)
93 });
94
95 ;// ./src/shared/util.js
96 const isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser");
97 const IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
98 const FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
99 const MAX_IMAGE_SIZE_TO_CACHE = 10e6;
100 const LINE_FACTOR = 1.35;
101 const LINE_DESCENT_FACTOR = 0.35;
102 const BASELINE_FACTOR = LINE_DESCENT_FACTOR / LINE_FACTOR;
103 const RenderingIntentFlag = {
104 ANY: 0x01,
105 DISPLAY: 0x02,
106 PRINT: 0x04,
107 SAVE: 0x08,
108 ANNOTATIONS_FORMS: 0x10,
109 ANNOTATIONS_STORAGE: 0x20,
110 ANNOTATIONS_DISABLE: 0x40,
111 IS_EDITING: 0x80,
112 OPLIST: 0x100
113 };
114 const AnnotationMode = {
115 DISABLE: 0,
116 ENABLE: 1,
117 ENABLE_FORMS: 2,
118 ENABLE_STORAGE: 3
119 };
120 const AnnotationEditorPrefix = "pdfjs_internal_editor_";
121 const AnnotationEditorType = {
122 DISABLE: -1,
123 NONE: 0,
124 FREETEXT: 3,
125 HIGHLIGHT: 9,
126 STAMP: 13,
127 INK: 15
128 };
129 const AnnotationEditorParamsType = {
130 RESIZE: 1,
131 CREATE: 2,
132 FREETEXT_SIZE: 11,
133 FREETEXT_COLOR: 12,
134 FREETEXT_OPACITY: 13,
135 INK_COLOR: 21,
136 INK_THICKNESS: 22,
137 INK_OPACITY: 23,
138 HIGHLIGHT_COLOR: 31,
139 HIGHLIGHT_DEFAULT_COLOR: 32,
140 HIGHLIGHT_THICKNESS: 33,
141 HIGHLIGHT_FREE: 34,
142 HIGHLIGHT_SHOW_ALL: 35
143 };
144 const PermissionFlag = {
145 PRINT: 0x04,
146 MODIFY_CONTENTS: 0x08,
147 COPY: 0x10,
148 MODIFY_ANNOTATIONS: 0x20,
149 FILL_INTERACTIVE_FORMS: 0x100,
150 COPY_FOR_ACCESSIBILITY: 0x200,
151 ASSEMBLE: 0x400,
152 PRINT_HIGH_QUALITY: 0x800
153 };
154 const TextRenderingMode = {
155 FILL: 0,
156 STROKE: 1,
157 FILL_STROKE: 2,
158 INVISIBLE: 3,
159 FILL_ADD_TO_PATH: 4,
160 STROKE_ADD_TO_PATH: 5,
161 FILL_STROKE_ADD_TO_PATH: 6,
162 ADD_TO_PATH: 7,
163 FILL_STROKE_MASK: 3,
164 ADD_TO_PATH_FLAG: 4
165 };
166 const util_ImageKind = {
167 GRAYSCALE_1BPP: 1,
168 RGB_24BPP: 2,
169 RGBA_32BPP: 3
170 };
171 const AnnotationType = {
172 TEXT: 1,
173 LINK: 2,
174 FREETEXT: 3,
175 LINE: 4,
176 SQUARE: 5,
177 CIRCLE: 6,
178 POLYGON: 7,
179 POLYLINE: 8,
180 HIGHLIGHT: 9,
181 UNDERLINE: 10,
182 SQUIGGLY: 11,
183 STRIKEOUT: 12,
184 STAMP: 13,
185 CARET: 14,
186 INK: 15,
187 POPUP: 16,
188 FILEATTACHMENT: 17,
189 SOUND: 18,
190 MOVIE: 19,
191 WIDGET: 20,
192 SCREEN: 21,
193 PRINTERMARK: 22,
194 TRAPNET: 23,
195 WATERMARK: 24,
196 THREED: 25,
197 REDACT: 26
198 };
199 const AnnotationReplyType = {
200 GROUP: "Group",
201 REPLY: "R"
202 };
203 const AnnotationFlag = {
204 INVISIBLE: 0x01,
205 HIDDEN: 0x02,
206 PRINT: 0x04,
207 NOZOOM: 0x08,
208 NOROTATE: 0x10,
209 NOVIEW: 0x20,
210 READONLY: 0x40,
211 LOCKED: 0x80,
212 TOGGLENOVIEW: 0x100,
213 LOCKEDCONTENTS: 0x200
214 };
215 const AnnotationFieldFlag = {
216 READONLY: 0x0000001,
217 REQUIRED: 0x0000002,
218 NOEXPORT: 0x0000004,
219 MULTILINE: 0x0001000,
220 PASSWORD: 0x0002000,
221 NOTOGGLETOOFF: 0x0004000,
222 RADIO: 0x0008000,
223 PUSHBUTTON: 0x0010000,
224 COMBO: 0x0020000,
225 EDIT: 0x0040000,
226 SORT: 0x0080000,
227 FILESELECT: 0x0100000,
228 MULTISELECT: 0x0200000,
229 DONOTSPELLCHECK: 0x0400000,
230 DONOTSCROLL: 0x0800000,
231 COMB: 0x1000000,
232 RICHTEXT: 0x2000000,
233 RADIOSINUNISON: 0x2000000,
234 COMMITONSELCHANGE: 0x4000000
235 };
236 const AnnotationBorderStyleType = {
237 SOLID: 1,
238 DASHED: 2,
239 BEVELED: 3,
240 INSET: 4,
241 UNDERLINE: 5
242 };
243 const AnnotationActionEventType = {
244 E: "Mouse Enter",
245 X: "Mouse Exit",
246 D: "Mouse Down",
247 U: "Mouse Up",
248 Fo: "Focus",
249 Bl: "Blur",
250 PO: "PageOpen",
251 PC: "PageClose",
252 PV: "PageVisible",
253 PI: "PageInvisible",
254 K: "Keystroke",
255 F: "Format",
256 V: "Validate",
257 C: "Calculate"
258 };
259 const DocumentActionEventType = {
260 WC: "WillClose",
261 WS: "WillSave",
262 DS: "DidSave",
263 WP: "WillPrint",
264 DP: "DidPrint"
265 };
266 const PageActionEventType = {
267 O: "PageOpen",
268 C: "PageClose"
269 };
270 const VerbosityLevel = {
271 ERRORS: 0,
272 WARNINGS: 1,
273 INFOS: 5
274 };
275 const CMapCompressionType = {
276 NONE: 0,
277 BINARY: 1
278 };
279 const OPS = {
280 dependency: 1,
281 setLineWidth: 2,
282 setLineCap: 3,
283 setLineJoin: 4,
284 setMiterLimit: 5,
285 setDash: 6,
286 setRenderingIntent: 7,
287 setFlatness: 8,
288 setGState: 9,
289 save: 10,
290 restore: 11,
291 transform: 12,
292 moveTo: 13,
293 lineTo: 14,
294 curveTo: 15,
295 curveTo2: 16,
296 curveTo3: 17,
297 closePath: 18,
298 rectangle: 19,
299 stroke: 20,
300 closeStroke: 21,
301 fill: 22,
302 eoFill: 23,
303 fillStroke: 24,
304 eoFillStroke: 25,
305 closeFillStroke: 26,
306 closeEOFillStroke: 27,
307 endPath: 28,
308 clip: 29,
309 eoClip: 30,
310 beginText: 31,
311 endText: 32,
312 setCharSpacing: 33,
313 setWordSpacing: 34,
314 setHScale: 35,
315 setLeading: 36,
316 setFont: 37,
317 setTextRenderingMode: 38,
318 setTextRise: 39,
319 moveText: 40,
320 setLeadingMoveText: 41,
321 setTextMatrix: 42,
322 nextLine: 43,
323 showText: 44,
324 showSpacedText: 45,
325 nextLineShowText: 46,
326 nextLineSetSpacingShowText: 47,
327 setCharWidth: 48,
328 setCharWidthAndBounds: 49,
329 setStrokeColorSpace: 50,
330 setFillColorSpace: 51,
331 setStrokeColor: 52,
332 setStrokeColorN: 53,
333 setFillColor: 54,
334 setFillColorN: 55,
335 setStrokeGray: 56,
336 setFillGray: 57,
337 setStrokeRGBColor: 58,
338 setFillRGBColor: 59,
339 setStrokeCMYKColor: 60,
340 setFillCMYKColor: 61,
341 shadingFill: 62,
342 beginInlineImage: 63,
343 beginImageData: 64,
344 endInlineImage: 65,
345 paintXObject: 66,
346 markPoint: 67,
347 markPointProps: 68,
348 beginMarkedContent: 69,
349 beginMarkedContentProps: 70,
350 endMarkedContent: 71,
351 beginCompat: 72,
352 endCompat: 73,
353 paintFormXObjectBegin: 74,
354 paintFormXObjectEnd: 75,
355 beginGroup: 76,
356 endGroup: 77,
357 beginAnnotation: 80,
358 endAnnotation: 81,
359 paintImageMaskXObject: 83,
360 paintImageMaskXObjectGroup: 84,
361 paintImageXObject: 85,
362 paintInlineImageXObject: 86,
363 paintInlineImageXObjectGroup: 87,
364 paintImageXObjectRepeat: 88,
365 paintImageMaskXObjectRepeat: 89,
366 paintSolidColorImageMask: 90,
367 constructPath: 91,
368 setStrokeTransparent: 92,
369 setFillTransparent: 93
370 };
371 const PasswordResponses = {
372 NEED_PASSWORD: 1,
373 INCORRECT_PASSWORD: 2
374 };
375 let verbosity = VerbosityLevel.WARNINGS;
376 function setVerbosityLevel(level) {
377 if (Number.isInteger(level)) {
378 verbosity = level;
379 }
380 }
381 function getVerbosityLevel() {
382 return verbosity;
383 }
384 function info(msg) {
385 if (verbosity >= VerbosityLevel.INFOS) {
386 console.log(`Info: ${msg}`);
387 }
388 }
389 function warn(msg) {
390 if (verbosity >= VerbosityLevel.WARNINGS) {
391 console.log(`Warning: ${msg}`);
392 }
393 }
394 function unreachable(msg) {
395 throw new Error(msg);
396 }
397 function assert(cond, msg) {
398 if (!cond) {
399 unreachable(msg);
400 }
401 }
402 function _isValidProtocol(url) {
403 switch (url?.protocol) {
404 case "http:":
405 case "https:":
406 case "ftp:":
407 case "mailto:":
408 case "tel:":
409 return true;
410 default:
411 return false;
412 }
413 }
414 function createValidAbsoluteUrl(url, baseUrl = null, options = null) {
415 if (!url) {
416 return null;
417 }
418 try {
419 if (options && typeof url === "string") {
420 if (options.addDefaultProtocol && url.startsWith("www.")) {
421 const dots = url.match(/\./g);
422 if (dots?.length >= 2) {
423 url = `http://${url}`;
424 }
425 }
426 if (options.tryConvertEncoding) {
427 try {
428 url = stringToUTF8String(url);
429 } catch {}
430 }
431 }
432 const absoluteUrl = baseUrl ? new URL(url, baseUrl) : new URL(url);
433 if (_isValidProtocol(absoluteUrl)) {
434 return absoluteUrl;
435 }
436 } catch {}
437 return null;
438 }
439 function shadow(obj, prop, value, nonSerializable = false) {
440 Object.defineProperty(obj, prop, {
441 value,
442 enumerable: !nonSerializable,
443 configurable: true,
444 writable: false
445 });
446 return value;
447 }
448 const BaseException = function BaseExceptionClosure() {
449 function BaseException(message, name) {
450 this.message = message;
451 this.name = name;
452 }
453 BaseException.prototype = new Error();
454 BaseException.constructor = BaseException;
455 return BaseException;
456 }();
457 class PasswordException extends BaseException {
458 constructor(msg, code) {
459 super(msg, "PasswordException");
460 this.code = code;
461 }
462 }
463 class UnknownErrorException extends BaseException {
464 constructor(msg, details) {
465 super(msg, "UnknownErrorException");
466 this.details = details;
467 }
468 }
469 class InvalidPDFException extends BaseException {
470 constructor(msg) {
471 super(msg, "InvalidPDFException");
472 }
473 }
474 class MissingPDFException extends BaseException {
475 constructor(msg) {
476 super(msg, "MissingPDFException");
477 }
478 }
479 class UnexpectedResponseException extends BaseException {
480 constructor(msg, status) {
481 super(msg, "UnexpectedResponseException");
482 this.status = status;
483 }
484 }
485 class FormatError extends BaseException {
486 constructor(msg) {
487 super(msg, "FormatError");
488 }
489 }
490 class AbortException extends BaseException {
491 constructor(msg) {
492 super(msg, "AbortException");
493 }
494 }
495 function bytesToString(bytes) {
496 if (typeof bytes !== "object" || bytes?.length === undefined) {
497 unreachable("Invalid argument for bytesToString");
498 }
499 const length = bytes.length;
500 const MAX_ARGUMENT_COUNT = 8192;
501 if (length < MAX_ARGUMENT_COUNT) {
502 return String.fromCharCode.apply(null, bytes);
503 }
504 const strBuf = [];
505 for (let i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
506 const chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
507 const chunk = bytes.subarray(i, chunkEnd);
508 strBuf.push(String.fromCharCode.apply(null, chunk));
509 }
510 return strBuf.join("");
511 }
512 function stringToBytes(str) {
513 if (typeof str !== "string") {
514 unreachable("Invalid argument for stringToBytes");
515 }
516 const length = str.length;
517 const bytes = new Uint8Array(length);
518 for (let i = 0; i < length; ++i) {
519 bytes[i] = str.charCodeAt(i) & 0xff;
520 }
521 return bytes;
522 }
523 function string32(value) {
524 return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);
525 }
526 function objectSize(obj) {
527 return Object.keys(obj).length;
528 }
529 function objectFromMap(map) {
530 const obj = Object.create(null);
531 for (const [key, value] of map) {
532 obj[key] = value;
533 }
534 return obj;
535 }
536 function isLittleEndian() {
537 const buffer8 = new Uint8Array(4);
538 buffer8[0] = 1;
539 const view32 = new Uint32Array(buffer8.buffer, 0, 1);
540 return view32[0] === 1;
541 }
542 function isEvalSupported() {
543 try {
544 new Function("");
545 return true;
546 } catch {
547 return false;
548 }
549 }
550 class util_FeatureTest {
551 static get isLittleEndian() {
552 return shadow(this, "isLittleEndian", isLittleEndian());
553 }
554 static get isEvalSupported() {
555 return shadow(this, "isEvalSupported", isEvalSupported());
556 }
557 static get isOffscreenCanvasSupported() {
558 return shadow(this, "isOffscreenCanvasSupported", typeof OffscreenCanvas !== "undefined");
559 }
560 static get platform() {
561 if (typeof navigator !== "undefined" && typeof navigator?.platform === "string") {
562 return shadow(this, "platform", {
563 isMac: navigator.platform.includes("Mac"),
564 isWindows: navigator.platform.includes("Win"),
565 isFirefox: typeof navigator?.userAgent === "string" && navigator.userAgent.includes("Firefox")
566 });
567 }
568 return shadow(this, "platform", {
569 isMac: false,
570 isWindows: false,
571 isFirefox: false
572 });
573 }
574 static get isCSSRoundSupported() {
575 return shadow(this, "isCSSRoundSupported", globalThis.CSS?.supports?.("width: round(1.5px, 1px)"));
576 }
577 }
578 const hexNumbers = Array.from(Array(256).keys(), n => n.toString(16).padStart(2, "0"));
579 class Util {
580 static makeHexColor(r, g, b) {
581 return `#${hexNumbers[r]}${hexNumbers[g]}${hexNumbers[b]}`;
582 }
583 static scaleMinMax(transform, minMax) {
584 let temp;
585 if (transform[0]) {
586 if (transform[0] < 0) {
587 temp = minMax[0];
588 minMax[0] = minMax[2];
589 minMax[2] = temp;
590 }
591 minMax[0] *= transform[0];
592 minMax[2] *= transform[0];
593 if (transform[3] < 0) {
594 temp = minMax[1];
595 minMax[1] = minMax[3];
596 minMax[3] = temp;
597 }
598 minMax[1] *= transform[3];
599 minMax[3] *= transform[3];
600 } else {
601 temp = minMax[0];
602 minMax[0] = minMax[1];
603 minMax[1] = temp;
604 temp = minMax[2];
605 minMax[2] = minMax[3];
606 minMax[3] = temp;
607 if (transform[1] < 0) {
608 temp = minMax[1];
609 minMax[1] = minMax[3];
610 minMax[3] = temp;
611 }
612 minMax[1] *= transform[1];
613 minMax[3] *= transform[1];
614 if (transform[2] < 0) {
615 temp = minMax[0];
616 minMax[0] = minMax[2];
617 minMax[2] = temp;
618 }
619 minMax[0] *= transform[2];
620 minMax[2] *= transform[2];
621 }
622 minMax[0] += transform[4];
623 minMax[1] += transform[5];
624 minMax[2] += transform[4];
625 minMax[3] += transform[5];
626 }
627 static transform(m1, m2) {
628 return [m1[0] * m2[0] + m1[2] * m2[1], m1[1] * m2[0] + m1[3] * m2[1], m1[0] * m2[2] + m1[2] * m2[3], m1[1] * m2[2] + m1[3] * m2[3], m1[0] * m2[4] + m1[2] * m2[5] + m1[4], m1[1] * m2[4] + m1[3] * m2[5] + m1[5]];
629 }
630 static applyTransform(p, m) {
631 const xt = p[0] * m[0] + p[1] * m[2] + m[4];
632 const yt = p[0] * m[1] + p[1] * m[3] + m[5];
633 return [xt, yt];
634 }
635 static applyInverseTransform(p, m) {
636 const d = m[0] * m[3] - m[1] * m[2];
637 const xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
638 const yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
639 return [xt, yt];
640 }
641 static getAxialAlignedBoundingBox(r, m) {
642 const p1 = this.applyTransform(r, m);
643 const p2 = this.applyTransform(r.slice(2, 4), m);
644 const p3 = this.applyTransform([r[0], r[3]], m);
645 const p4 = this.applyTransform([r[2], r[1]], m);
646 return [Math.min(p1[0], p2[0], p3[0], p4[0]), Math.min(p1[1], p2[1], p3[1], p4[1]), Math.max(p1[0], p2[0], p3[0], p4[0]), Math.max(p1[1], p2[1], p3[1], p4[1])];
647 }
648 static inverseTransform(m) {
649 const d = m[0] * m[3] - m[1] * m[2];
650 return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d, (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
651 }
652 static singularValueDecompose2dScale(m) {
653 const transpose = [m[0], m[2], m[1], m[3]];
654 const a = m[0] * transpose[0] + m[1] * transpose[2];
655 const b = m[0] * transpose[1] + m[1] * transpose[3];
656 const c = m[2] * transpose[0] + m[3] * transpose[2];
657 const d = m[2] * transpose[1] + m[3] * transpose[3];
658 const first = (a + d) / 2;
659 const second = Math.sqrt((a + d) ** 2 - 4 * (a * d - c * b)) / 2;
660 const sx = first + second || 1;
661 const sy = first - second || 1;
662 return [Math.sqrt(sx), Math.sqrt(sy)];
663 }
664 static normalizeRect(rect) {
665 const r = rect.slice(0);
666 if (rect[0] > rect[2]) {
667 r[0] = rect[2];
668 r[2] = rect[0];
669 }
670 if (rect[1] > rect[3]) {
671 r[1] = rect[3];
672 r[3] = rect[1];
673 }
674 return r;
675 }
676 static intersect(rect1, rect2) {
677 const xLow = Math.max(Math.min(rect1[0], rect1[2]), Math.min(rect2[0], rect2[2]));
678 const xHigh = Math.min(Math.max(rect1[0], rect1[2]), Math.max(rect2[0], rect2[2]));
679 if (xLow > xHigh) {
680 return null;
681 }
682 const yLow = Math.max(Math.min(rect1[1], rect1[3]), Math.min(rect2[1], rect2[3]));
683 const yHigh = Math.min(Math.max(rect1[1], rect1[3]), Math.max(rect2[1], rect2[3]));
684 if (yLow > yHigh) {
685 return null;
686 }
687 return [xLow, yLow, xHigh, yHigh];
688 }
689 static #getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, t, minMax) {
690 if (t <= 0 || t >= 1) {
691 return;
692 }
693 const mt = 1 - t;
694 const tt = t * t;
695 const ttt = tt * t;
696 const x = mt * (mt * (mt * x0 + 3 * t * x1) + 3 * tt * x2) + ttt * x3;
697 const y = mt * (mt * (mt * y0 + 3 * t * y1) + 3 * tt * y2) + ttt * y3;
698 minMax[0] = Math.min(minMax[0], x);
699 minMax[1] = Math.min(minMax[1], y);
700 minMax[2] = Math.max(minMax[2], x);
701 minMax[3] = Math.max(minMax[3], y);
702 }
703 static #getExtremum(x0, x1, x2, x3, y0, y1, y2, y3, a, b, c, minMax) {
704 if (Math.abs(a) < 1e-12) {
705 if (Math.abs(b) >= 1e-12) {
706 this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, -c / b, minMax);
707 }
708 return;
709 }
710 const delta = b ** 2 - 4 * c * a;
711 if (delta < 0) {
712 return;
713 }
714 const sqrtDelta = Math.sqrt(delta);
715 const a2 = 2 * a;
716 this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, (-b + sqrtDelta) / a2, minMax);
717 this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, (-b - sqrtDelta) / a2, minMax);
718 }
719 static bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3, minMax) {
720 if (minMax) {
721 minMax[0] = Math.min(minMax[0], x0, x3);
722 minMax[1] = Math.min(minMax[1], y0, y3);
723 minMax[2] = Math.max(minMax[2], x0, x3);
724 minMax[3] = Math.max(minMax[3], y0, y3);
725 } else {
726 minMax = [Math.min(x0, x3), Math.min(y0, y3), Math.max(x0, x3), Math.max(y0, y3)];
727 }
728 this.#getExtremum(x0, x1, x2, x3, y0, y1, y2, y3, 3 * (-x0 + 3 * (x1 - x2) + x3), 6 * (x0 - 2 * x1 + x2), 3 * (x1 - x0), minMax);
729 this.#getExtremum(x0, x1, x2, x3, y0, y1, y2, y3, 3 * (-y0 + 3 * (y1 - y2) + y3), 6 * (y0 - 2 * y1 + y2), 3 * (y1 - y0), minMax);
730 return minMax;
731 }
732 }
733 const PDFStringTranslateTable = (/* unused pure expression or super */ null && ([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2d8, 0x2c7, 0x2c6, 0x2d9, 0x2dd, 0x2db, 0x2da, 0x2dc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x192, 0x2044, 0x2039, 0x203a, 0x2212, 0x2030, 0x201e, 0x201c, 0x201d, 0x2018, 0x2019, 0x201a, 0x2122, 0xfb01, 0xfb02, 0x141, 0x152, 0x160, 0x178, 0x17d, 0x131, 0x142, 0x153, 0x161, 0x17e, 0, 0x20ac]));
734 function stringToPDFString(str) {
735 if (str[0] >= "\xEF") {
736 let encoding;
737 if (str[0] === "\xFE" && str[1] === "\xFF") {
738 encoding = "utf-16be";
739 if (str.length % 2 === 1) {
740 str = str.slice(0, -1);
741 }
742 } else if (str[0] === "\xFF" && str[1] === "\xFE") {
743 encoding = "utf-16le";
744 if (str.length % 2 === 1) {
745 str = str.slice(0, -1);
746 }
747 } else if (str[0] === "\xEF" && str[1] === "\xBB" && str[2] === "\xBF") {
748 encoding = "utf-8";
749 }
750 if (encoding) {
751 try {
752 const decoder = new TextDecoder(encoding, {
753 fatal: true
754 });
755 const buffer = stringToBytes(str);
756 const decoded = decoder.decode(buffer);
757 if (!decoded.includes("\x1b")) {
758 return decoded;
759 }
760 return decoded.replaceAll(/\x1b[^\x1b]*(?:\x1b|$)/g, "");
761 } catch (ex) {
762 warn(`stringToPDFString: "${ex}".`);
763 }
764 }
765 }
766 const strBuf = [];
767 for (let i = 0, ii = str.length; i < ii; i++) {
768 const charCode = str.charCodeAt(i);
769 if (charCode === 0x1b) {
770 while (++i < ii && str.charCodeAt(i) !== 0x1b) {}
771 continue;
772 }
773 const code = PDFStringTranslateTable[charCode];
774 strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
775 }
776 return strBuf.join("");
777 }
778 function stringToUTF8String(str) {
779 return decodeURIComponent(escape(str));
780 }
781 function utf8StringToString(str) {
782 return unescape(encodeURIComponent(str));
783 }
784 function isArrayEqual(arr1, arr2) {
785 if (arr1.length !== arr2.length) {
786 return false;
787 }
788 for (let i = 0, ii = arr1.length; i < ii; i++) {
789 if (arr1[i] !== arr2[i]) {
790 return false;
791 }
792 }
793 return true;
794 }
795 function getModificationDate(date = new Date()) {
796 const buffer = [date.getUTCFullYear().toString(), (date.getUTCMonth() + 1).toString().padStart(2, "0"), date.getUTCDate().toString().padStart(2, "0"), date.getUTCHours().toString().padStart(2, "0"), date.getUTCMinutes().toString().padStart(2, "0"), date.getUTCSeconds().toString().padStart(2, "0")];
797 return buffer.join("");
798 }
799 let NormalizeRegex = null;
800 let NormalizationMap = null;
801 function normalizeUnicode(str) {
802 if (!NormalizeRegex) {
803 NormalizeRegex = /([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu;
804 NormalizationMap = new Map([["ſt", "ſt"]]);
805 }
806 return str.replaceAll(NormalizeRegex, (_, p1, p2) => p1 ? p1.normalize("NFKC") : NormalizationMap.get(p2));
807 }
808 function getUuid() {
809 if (typeof crypto !== "undefined" && typeof crypto?.randomUUID === "function") {
810 return crypto.randomUUID();
811 }
812 const buf = new Uint8Array(32);
813 if (typeof crypto !== "undefined" && typeof crypto?.getRandomValues === "function") {
814 crypto.getRandomValues(buf);
815 } else {
816 for (let i = 0; i < 32; i++) {
817 buf[i] = Math.floor(Math.random() * 255);
818 }
819 }
820 return bytesToString(buf);
821 }
822 const AnnotationPrefix = "pdfjs_internal_id_";
823 const FontRenderOps = {
824 BEZIER_CURVE_TO: 0,
825 MOVE_TO: 1,
826 LINE_TO: 2,
827 QUADRATIC_CURVE_TO: 3,
828 RESTORE: 4,
829 SAVE: 5,
830 SCALE: 6,
831 TRANSFORM: 7,
832 TRANSLATE: 8
833 };
834
835 ;// ./src/display/base_factory.js
836
837 class BaseFilterFactory {
838 addFilter(maps) {
839 return "none";
840 }
841 addHCMFilter(fgColor, bgColor) {
842 return "none";
843 }
844 addAlphaFilter(map) {
845 return "none";
846 }
847 addLuminosityFilter(map) {
848 return "none";
849 }
850 addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) {
851 return "none";
852 }
853 destroy(keepHCM = false) {}
854 }
855 class BaseCanvasFactory {
856 #enableHWA = false;
857 constructor({
858 enableHWA = false
859 }) {
860 this.#enableHWA = enableHWA;
861 }
862 create(width, height) {
863 if (width <= 0 || height <= 0) {
864 throw new Error("Invalid canvas size");
865 }
866 const canvas = this._createCanvas(width, height);
867 return {
868 canvas,
869 context: canvas.getContext("2d", {
870 willReadFrequently: !this.#enableHWA
871 })
872 };
873 }
874 reset(canvasAndContext, width, height) {
875 if (!canvasAndContext.canvas) {
876 throw new Error("Canvas is not specified");
877 }
878 if (width <= 0 || height <= 0) {
879 throw new Error("Invalid canvas size");
880 }
881 canvasAndContext.canvas.width = width;
882 canvasAndContext.canvas.height = height;
883 }
884 destroy(canvasAndContext) {
885 if (!canvasAndContext.canvas) {
886 throw new Error("Canvas is not specified");
887 }
888 canvasAndContext.canvas.width = 0;
889 canvasAndContext.canvas.height = 0;
890 canvasAndContext.canvas = null;
891 canvasAndContext.context = null;
892 }
893 _createCanvas(width, height) {
894 unreachable("Abstract method `_createCanvas` called.");
895 }
896 }
897 class BaseCMapReaderFactory {
898 constructor({
899 baseUrl = null,
900 isCompressed = true
901 }) {
902 this.baseUrl = baseUrl;
903 this.isCompressed = isCompressed;
904 }
905 async fetch({
906 name
907 }) {
908 if (!this.baseUrl) {
909 throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");
910 }
911 if (!name) {
912 throw new Error("CMap name must be specified.");
913 }
914 const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : "");
915 const compressionType = this.isCompressed ? CMapCompressionType.BINARY : CMapCompressionType.NONE;
916 return this._fetchData(url, compressionType).catch(reason => {
917 throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`);
918 });
919 }
920 _fetchData(url, compressionType) {
921 unreachable("Abstract method `_fetchData` called.");
922 }
923 }
924 class BaseStandardFontDataFactory {
925 constructor({
926 baseUrl = null
927 }) {
928 this.baseUrl = baseUrl;
929 }
930 async fetch({
931 filename
932 }) {
933 if (!this.baseUrl) {
934 throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");
935 }
936 if (!filename) {
937 throw new Error("Font filename must be specified.");
938 }
939 const url = `${this.baseUrl}${filename}`;
940 return this._fetchData(url).catch(reason => {
941 throw new Error(`Unable to load font data at: ${url}`);
942 });
943 }
944 _fetchData(url) {
945 unreachable("Abstract method `_fetchData` called.");
946 }
947 }
948 class BaseSVGFactory {
949 create(width, height, skipDimensions = false) {
950 if (width <= 0 || height <= 0) {
951 throw new Error("Invalid SVG dimensions");
952 }
953 const svg = this._createSVG("svg:svg");
954 svg.setAttribute("version", "1.1");
955 if (!skipDimensions) {
956 svg.setAttribute("width", `${width}px`);
957 svg.setAttribute("height", `${height}px`);
958 }
959 svg.setAttribute("preserveAspectRatio", "none");
960 svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
961 return svg;
962 }
963 createElement(type) {
964 if (typeof type !== "string") {
965 throw new Error("Invalid SVG element type");
966 }
967 return this._createSVG(type);
968 }
969 _createSVG(type) {
970 unreachable("Abstract method `_createSVG` called.");
971 }
972 }
973
974 ;// ./src/display/display_utils.js
975
976
977 const SVG_NS = "http://www.w3.org/2000/svg";
978 class PixelsPerInch {
979 static CSS = 96.0;
980 static PDF = 72.0;
981 static PDF_TO_CSS_UNITS = this.CSS / this.PDF;
982 }
983 class DOMFilterFactory extends BaseFilterFactory {
984 #baseUrl;
985 #_cache;
986 #_defs;
987 #docId;
988 #document;
989 #_hcmCache;
990 #id = 0;
991 constructor({
992 docId,
993 ownerDocument = globalThis.document
994 }) {
995 super();
996 this.#docId = docId;
997 this.#document = ownerDocument;
998 }
999 get #cache() {
1000 return this.#_cache ||= new Map();
1001 }
1002 get #hcmCache() {
1003 return this.#_hcmCache ||= new Map();
1004 }
1005 get #defs() {
1006 if (!this.#_defs) {
1007 const div = this.#document.createElement("div");
1008 const {
1009 style
1010 } = div;
1011 style.visibility = "hidden";
1012 style.contain = "strict";
1013 style.width = style.height = 0;
1014 style.position = "absolute";
1015 style.top = style.left = 0;
1016 style.zIndex = -1;
1017 const svg = this.#document.createElementNS(SVG_NS, "svg");
1018 svg.setAttribute("width", 0);
1019 svg.setAttribute("height", 0);
1020 this.#_defs = this.#document.createElementNS(SVG_NS, "defs");
1021 div.append(svg);
1022 svg.append(this.#_defs);
1023 this.#document.body.append(div);
1024 }
1025 return this.#_defs;
1026 }
1027 #createTables(maps) {
1028 if (maps.length === 1) {
1029 const mapR = maps[0];
1030 const buffer = new Array(256);
1031 for (let i = 0; i < 256; i++) {
1032 buffer[i] = mapR[i] / 255;
1033 }
1034 const table = buffer.join(",");
1035 return [table, table, table];
1036 }
1037 const [mapR, mapG, mapB] = maps;
1038 const bufferR = new Array(256);
1039 const bufferG = new Array(256);
1040 const bufferB = new Array(256);
1041 for (let i = 0; i < 256; i++) {
1042 bufferR[i] = mapR[i] / 255;
1043 bufferG[i] = mapG[i] / 255;
1044 bufferB[i] = mapB[i] / 255;
1045 }
1046 return [bufferR.join(","), bufferG.join(","), bufferB.join(",")];
1047 }
1048 #createUrl(id) {
1049 if (this.#baseUrl === undefined) {
1050 this.#baseUrl = "";
1051 const url = this.#document.URL;
1052 if (url !== this.#document.baseURI) {
1053 if (isDataScheme(url)) {
1054 warn('#createUrl: ignore "data:"-URL for performance reasons.');
1055 } else {
1056 this.#baseUrl = url.split("#", 1)[0];
1057 }
1058 }
1059 }
1060 return `url(${this.#baseUrl}#${id})`;
1061 }
1062 addFilter(maps) {
1063 if (!maps) {
1064 return "none";
1065 }
1066 let value = this.#cache.get(maps);
1067 if (value) {
1068 return value;
1069 }
1070 const [tableR, tableG, tableB] = this.#createTables(maps);
1071 const key = maps.length === 1 ? tableR : `${tableR}${tableG}${tableB}`;
1072 value = this.#cache.get(key);
1073 if (value) {
1074 this.#cache.set(maps, value);
1075 return value;
1076 }
1077 const id = `g_${this.#docId}_transfer_map_${this.#id++}`;
1078 const url = this.#createUrl(id);
1079 this.#cache.set(maps, url);
1080 this.#cache.set(key, url);
1081 const filter = this.#createFilter(id);
1082 this.#addTransferMapConversion(tableR, tableG, tableB, filter);
1083 return url;
1084 }
1085 addHCMFilter(fgColor, bgColor) {
1086 const key = `${fgColor}-${bgColor}`;
1087 const filterName = "base";
1088 let info = this.#hcmCache.get(filterName);
1089 if (info?.key === key) {
1090 return info.url;
1091 }
1092 if (info) {
1093 info.filter?.remove();
1094 info.key = key;
1095 info.url = "none";
1096 info.filter = null;
1097 } else {
1098 info = {
1099 key,
1100 url: "none",
1101 filter: null
1102 };
1103 this.#hcmCache.set(filterName, info);
1104 }
1105 if (!fgColor || !bgColor) {
1106 return info.url;
1107 }
1108 const fgRGB = this.#getRGB(fgColor);
1109 fgColor = Util.makeHexColor(...fgRGB);
1110 const bgRGB = this.#getRGB(bgColor);
1111 bgColor = Util.makeHexColor(...bgRGB);
1112 this.#defs.style.color = "";
1113 if (fgColor === "#000000" && bgColor === "#ffffff" || fgColor === bgColor) {
1114 return info.url;
1115 }
1116 const map = new Array(256);
1117 for (let i = 0; i <= 255; i++) {
1118 const x = i / 255;
1119 map[i] = x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
1120 }
1121 const table = map.join(",");
1122 const id = `g_${this.#docId}_hcm_filter`;
1123 const filter = info.filter = this.#createFilter(id);
1124 this.#addTransferMapConversion(table, table, table, filter);
1125 this.#addGrayConversion(filter);
1126 const getSteps = (c, n) => {
1127 const start = fgRGB[c] / 255;
1128 const end = bgRGB[c] / 255;
1129 const arr = new Array(n + 1);
1130 for (let i = 0; i <= n; i++) {
1131 arr[i] = start + i / n * (end - start);
1132 }
1133 return arr.join(",");
1134 };
1135 this.#addTransferMapConversion(getSteps(0, 5), getSteps(1, 5), getSteps(2, 5), filter);
1136 info.url = this.#createUrl(id);
1137 return info.url;
1138 }
1139 addAlphaFilter(map) {
1140 let value = this.#cache.get(map);
1141 if (value) {
1142 return value;
1143 }
1144 const [tableA] = this.#createTables([map]);
1145 const key = `alpha_${tableA}`;
1146 value = this.#cache.get(key);
1147 if (value) {
1148 this.#cache.set(map, value);
1149 return value;
1150 }
1151 const id = `g_${this.#docId}_alpha_map_${this.#id++}`;
1152 const url = this.#createUrl(id);
1153 this.#cache.set(map, url);
1154 this.#cache.set(key, url);
1155 const filter = this.#createFilter(id);
1156 this.#addTransferMapAlphaConversion(tableA, filter);
1157 return url;
1158 }
1159 addLuminosityFilter(map) {
1160 let value = this.#cache.get(map || "luminosity");
1161 if (value) {
1162 return value;
1163 }
1164 let tableA, key;
1165 if (map) {
1166 [tableA] = this.#createTables([map]);
1167 key = `luminosity_${tableA}`;
1168 } else {
1169 key = "luminosity";
1170 }
1171 value = this.#cache.get(key);
1172 if (value) {
1173 this.#cache.set(map, value);
1174 return value;
1175 }
1176 const id = `g_${this.#docId}_luminosity_map_${this.#id++}`;
1177 const url = this.#createUrl(id);
1178 this.#cache.set(map, url);
1179 this.#cache.set(key, url);
1180 const filter = this.#createFilter(id);
1181 this.#addLuminosityConversion(filter);
1182 if (map) {
1183 this.#addTransferMapAlphaConversion(tableA, filter);
1184 }
1185 return url;
1186 }
1187 addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) {
1188 const key = `${fgColor}-${bgColor}-${newFgColor}-${newBgColor}`;
1189 let info = this.#hcmCache.get(filterName);
1190 if (info?.key === key) {
1191 return info.url;
1192 }
1193 if (info) {
1194 info.filter?.remove();
1195 info.key = key;
1196 info.url = "none";
1197 info.filter = null;
1198 } else {
1199 info = {
1200 key,
1201 url: "none",
1202 filter: null
1203 };
1204 this.#hcmCache.set(filterName, info);
1205 }
1206 if (!fgColor || !bgColor) {
1207 return info.url;
1208 }
1209 const [fgRGB, bgRGB] = [fgColor, bgColor].map(this.#getRGB.bind(this));
1210 let fgGray = Math.round(0.2126 * fgRGB[0] + 0.7152 * fgRGB[1] + 0.0722 * fgRGB[2]);
1211 let bgGray = Math.round(0.2126 * bgRGB[0] + 0.7152 * bgRGB[1] + 0.0722 * bgRGB[2]);
1212 let [newFgRGB, newBgRGB] = [newFgColor, newBgColor].map(this.#getRGB.bind(this));
1213 if (bgGray < fgGray) {
1214 [fgGray, bgGray, newFgRGB, newBgRGB] = [bgGray, fgGray, newBgRGB, newFgRGB];
1215 }
1216 this.#defs.style.color = "";
1217 const getSteps = (fg, bg, n) => {
1218 const arr = new Array(256);
1219 const step = (bgGray - fgGray) / n;
1220 const newStart = fg / 255;
1221 const newStep = (bg - fg) / (255 * n);
1222 let prev = 0;
1223 for (let i = 0; i <= n; i++) {
1224 const k = Math.round(fgGray + i * step);
1225 const value = newStart + i * newStep;
1226 for (let j = prev; j <= k; j++) {
1227 arr[j] = value;
1228 }
1229 prev = k + 1;
1230 }
1231 for (let i = prev; i < 256; i++) {
1232 arr[i] = arr[prev - 1];
1233 }
1234 return arr.join(",");
1235 };
1236 const id = `g_${this.#docId}_hcm_${filterName}_filter`;
1237 const filter = info.filter = this.#createFilter(id);
1238 this.#addGrayConversion(filter);
1239 this.#addTransferMapConversion(getSteps(newFgRGB[0], newBgRGB[0], 5), getSteps(newFgRGB[1], newBgRGB[1], 5), getSteps(newFgRGB[2], newBgRGB[2], 5), filter);
1240 info.url = this.#createUrl(id);
1241 return info.url;
1242 }
1243 destroy(keepHCM = false) {
1244 if (keepHCM && this.#hcmCache.size !== 0) {
1245 return;
1246 }
1247 if (this.#_defs) {
1248 this.#_defs.parentNode.parentNode.remove();
1249 this.#_defs = null;
1250 }
1251 if (this.#_cache) {
1252 this.#_cache.clear();
1253 this.#_cache = null;
1254 }
1255 this.#id = 0;
1256 }
1257 #addLuminosityConversion(filter) {
1258 const feColorMatrix = this.#document.createElementNS(SVG_NS, "feColorMatrix");
1259 feColorMatrix.setAttribute("type", "matrix");
1260 feColorMatrix.setAttribute("values", "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0");
1261 filter.append(feColorMatrix);
1262 }
1263 #addGrayConversion(filter) {
1264 const feColorMatrix = this.#document.createElementNS(SVG_NS, "feColorMatrix");
1265 feColorMatrix.setAttribute("type", "matrix");
1266 feColorMatrix.setAttribute("values", "0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0");
1267 filter.append(feColorMatrix);
1268 }
1269 #createFilter(id) {
1270 const filter = this.#document.createElementNS(SVG_NS, "filter");
1271 filter.setAttribute("color-interpolation-filters", "sRGB");
1272 filter.setAttribute("id", id);
1273 this.#defs.append(filter);
1274 return filter;
1275 }
1276 #appendFeFunc(feComponentTransfer, func, table) {
1277 const feFunc = this.#document.createElementNS(SVG_NS, func);
1278 feFunc.setAttribute("type", "discrete");
1279 feFunc.setAttribute("tableValues", table);
1280 feComponentTransfer.append(feFunc);
1281 }
1282 #addTransferMapConversion(rTable, gTable, bTable, filter) {
1283 const feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer");
1284 filter.append(feComponentTransfer);
1285 this.#appendFeFunc(feComponentTransfer, "feFuncR", rTable);
1286 this.#appendFeFunc(feComponentTransfer, "feFuncG", gTable);
1287 this.#appendFeFunc(feComponentTransfer, "feFuncB", bTable);
1288 }
1289 #addTransferMapAlphaConversion(aTable, filter) {
1290 const feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer");
1291 filter.append(feComponentTransfer);
1292 this.#appendFeFunc(feComponentTransfer, "feFuncA", aTable);
1293 }
1294 #getRGB(color) {
1295 this.#defs.style.color = color;
1296 return getRGB(getComputedStyle(this.#defs).getPropertyValue("color"));
1297 }
1298 }
1299 class DOMCanvasFactory extends BaseCanvasFactory {
1300 constructor({
1301 ownerDocument = globalThis.document,
1302 enableHWA = false
1303 }) {
1304 super({
1305 enableHWA
1306 });
1307 this._document = ownerDocument;
1308 }
1309 _createCanvas(width, height) {
1310 const canvas = this._document.createElement("canvas");
1311 canvas.width = width;
1312 canvas.height = height;
1313 return canvas;
1314 }
1315 }
1316 async function fetchData(url, type = "text") {
1317 if (isValidFetchUrl(url, document.baseURI)) {
1318 const response = await fetch(url);
1319 if (!response.ok) {
1320 throw new Error(response.statusText);
1321 }
1322 switch (type) {
1323 case "arraybuffer":
1324 return response.arrayBuffer();
1325 case "blob":
1326 return response.blob();
1327 case "json":
1328 return response.json();
1329 }
1330 return response.text();
1331 }
1332 return new Promise((resolve, reject) => {
1333 const request = new XMLHttpRequest();
1334 request.open("GET", url, true);
1335 request.responseType = type;
1336 request.onreadystatechange = () => {
1337 if (request.readyState !== XMLHttpRequest.DONE) {
1338 return;
1339 }
1340 if (request.status === 200 || request.status === 0) {
1341 switch (type) {
1342 case "arraybuffer":
1343 case "blob":
1344 case "json":
1345 resolve(request.response);
1346 return;
1347 }
1348 resolve(request.responseText);
1349 return;
1350 }
1351 reject(new Error(request.statusText));
1352 };
1353 request.send(null);
1354 });
1355 }
1356 class DOMCMapReaderFactory extends BaseCMapReaderFactory {
1357 _fetchData(url, compressionType) {
1358 return fetchData(url, this.isCompressed ? "arraybuffer" : "text").then(data => ({
1359 cMapData: data instanceof ArrayBuffer ? new Uint8Array(data) : stringToBytes(data),
1360 compressionType
1361 }));
1362 }
1363 }
1364 class DOMStandardFontDataFactory extends BaseStandardFontDataFactory {
1365 _fetchData(url) {
1366 return fetchData(url, "arraybuffer").then(data => new Uint8Array(data));
1367 }
1368 }
1369 class DOMSVGFactory extends BaseSVGFactory {
1370 _createSVG(type) {
1371 return document.createElementNS(SVG_NS, type);
1372 }
1373 }
1374 class PageViewport {
1375 constructor({
1376 viewBox,
1377 scale,
1378 rotation,
1379 offsetX = 0,
1380 offsetY = 0,
1381 dontFlip = false
1382 }) {
1383 this.viewBox = viewBox;
1384 this.scale = scale;
1385 this.rotation = rotation;
1386 this.offsetX = offsetX;
1387 this.offsetY = offsetY;
1388 const centerX = (viewBox[2] + viewBox[0]) / 2;
1389 const centerY = (viewBox[3] + viewBox[1]) / 2;
1390 let rotateA, rotateB, rotateC, rotateD;
1391 rotation %= 360;
1392 if (rotation < 0) {
1393 rotation += 360;
1394 }
1395 switch (rotation) {
1396 case 180:
1397 rotateA = -1;
1398 rotateB = 0;
1399 rotateC = 0;
1400 rotateD = 1;
1401 break;
1402 case 90:
1403 rotateA = 0;
1404 rotateB = 1;
1405 rotateC = 1;
1406 rotateD = 0;
1407 break;
1408 case 270:
1409 rotateA = 0;
1410 rotateB = -1;
1411 rotateC = -1;
1412 rotateD = 0;
1413 break;
1414 case 0:
1415 rotateA = 1;
1416 rotateB = 0;
1417 rotateC = 0;
1418 rotateD = -1;
1419 break;
1420 default:
1421 throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.");
1422 }
1423 if (dontFlip) {
1424 rotateC = -rotateC;
1425 rotateD = -rotateD;
1426 }
1427 let offsetCanvasX, offsetCanvasY;
1428 let width, height;
1429 if (rotateA === 0) {
1430 offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
1431 offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
1432 width = (viewBox[3] - viewBox[1]) * scale;
1433 height = (viewBox[2] - viewBox[0]) * scale;
1434 } else {
1435 offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
1436 offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
1437 width = (viewBox[2] - viewBox[0]) * scale;
1438 height = (viewBox[3] - viewBox[1]) * scale;
1439 }
1440 this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
1441 this.width = width;
1442 this.height = height;
1443 }
1444 get rawDims() {
1445 const {
1446 viewBox
1447 } = this;
1448 return shadow(this, "rawDims", {
1449 pageWidth: viewBox[2] - viewBox[0],
1450 pageHeight: viewBox[3] - viewBox[1],
1451 pageX: viewBox[0],
1452 pageY: viewBox[1]
1453 });
1454 }
1455 clone({
1456 scale = this.scale,
1457 rotation = this.rotation,
1458 offsetX = this.offsetX,
1459 offsetY = this.offsetY,
1460 dontFlip = false
1461 } = {}) {
1462 return new PageViewport({
1463 viewBox: this.viewBox.slice(),
1464 scale,
1465 rotation,
1466 offsetX,
1467 offsetY,
1468 dontFlip
1469 });
1470 }
1471 convertToViewportPoint(x, y) {
1472 return Util.applyTransform([x, y], this.transform);
1473 }
1474 convertToViewportRectangle(rect) {
1475 const topLeft = Util.applyTransform([rect[0], rect[1]], this.transform);
1476 const bottomRight = Util.applyTransform([rect[2], rect[3]], this.transform);
1477 return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
1478 }
1479 convertToPdfPoint(x, y) {
1480 return Util.applyInverseTransform([x, y], this.transform);
1481 }
1482 }
1483 class RenderingCancelledException extends BaseException {
1484 constructor(msg, extraDelay = 0) {
1485 super(msg, "RenderingCancelledException");
1486 this.extraDelay = extraDelay;
1487 }
1488 }
1489 function isDataScheme(url) {
1490 const ii = url.length;
1491 let i = 0;
1492 while (i < ii && url[i].trim() === "") {
1493 i++;
1494 }
1495 return url.substring(i, i + 5).toLowerCase() === "data:";
1496 }
1497 function isPdfFile(filename) {
1498 return typeof filename === "string" && /\.pdf$/i.test(filename);
1499 }
1500 function getFilenameFromUrl(url) {
1501 [url] = url.split(/[#?]/, 1);
1502 return url.substring(url.lastIndexOf("/") + 1);
1503 }
1504 function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") {
1505 if (typeof url !== "string") {
1506 return defaultFilename;
1507 }
1508 if (isDataScheme(url)) {
1509 warn('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');
1510 return defaultFilename;
1511 }
1512 const reURI = /^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
1513 const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
1514 const splitURI = reURI.exec(url);
1515 let suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]);
1516 if (suggestedFilename) {
1517 suggestedFilename = suggestedFilename[0];
1518 if (suggestedFilename.includes("%")) {
1519 try {
1520 suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0];
1521 } catch {}
1522 }
1523 }
1524 return suggestedFilename || defaultFilename;
1525 }
1526 class StatTimer {
1527 started = Object.create(null);
1528 times = [];
1529 time(name) {
1530 if (name in this.started) {
1531 warn(`Timer is already running for ${name}`);
1532 }
1533 this.started[name] = Date.now();
1534 }
1535 timeEnd(name) {
1536 if (!(name in this.started)) {
1537 warn(`Timer has not been started for ${name}`);
1538 }
1539 this.times.push({
1540 name,
1541 start: this.started[name],
1542 end: Date.now()
1543 });
1544 delete this.started[name];
1545 }
1546 toString() {
1547 const outBuf = [];
1548 let longest = 0;
1549 for (const {
1550 name
1551 } of this.times) {
1552 longest = Math.max(name.length, longest);
1553 }
1554 for (const {
1555 name,
1556 start,
1557 end
1558 } of this.times) {
1559 outBuf.push(`${name.padEnd(longest)} ${end - start}ms\n`);
1560 }
1561 return outBuf.join("");
1562 }
1563 }
1564 function isValidFetchUrl(url, baseUrl) {
1565 try {
1566 const {
1567 protocol
1568 } = baseUrl ? new URL(url, baseUrl) : new URL(url);
1569 return protocol === "http:" || protocol === "https:";
1570 } catch {
1571 return false;
1572 }
1573 }
1574 function noContextMenu(e) {
1575 e.preventDefault();
1576 }
1577 function deprecated(details) {
1578 console.log("Deprecated API usage: " + details);
1579 }
1580 let pdfDateStringRegex;
1581 class PDFDateString {
1582 static toDateObject(input) {
1583 if (!input || typeof input !== "string") {
1584 return null;
1585 }
1586 pdfDateStringRegex ||= new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?");
1587 const matches = pdfDateStringRegex.exec(input);
1588 if (!matches) {
1589 return null;
1590 }
1591 const year = parseInt(matches[1], 10);
1592 let month = parseInt(matches[2], 10);
1593 month = month >= 1 && month <= 12 ? month - 1 : 0;
1594 let day = parseInt(matches[3], 10);
1595 day = day >= 1 && day <= 31 ? day : 1;
1596 let hour = parseInt(matches[4], 10);
1597 hour = hour >= 0 && hour <= 23 ? hour : 0;
1598 let minute = parseInt(matches[5], 10);
1599 minute = minute >= 0 && minute <= 59 ? minute : 0;
1600 let second = parseInt(matches[6], 10);
1601 second = second >= 0 && second <= 59 ? second : 0;
1602 const universalTimeRelation = matches[7] || "Z";
1603 let offsetHour = parseInt(matches[8], 10);
1604 offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
1605 let offsetMinute = parseInt(matches[9], 10) || 0;
1606 offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
1607 if (universalTimeRelation === "-") {
1608 hour += offsetHour;
1609 minute += offsetMinute;
1610 } else if (universalTimeRelation === "+") {
1611 hour -= offsetHour;
1612 minute -= offsetMinute;
1613 }
1614 return new Date(Date.UTC(year, month, day, hour, minute, second));
1615 }
1616 }
1617 function getXfaPageViewport(xfaPage, {
1618 scale = 1,
1619 rotation = 0
1620 }) {
1621 const {
1622 width,
1623 height
1624 } = xfaPage.attributes.style;
1625 const viewBox = [0, 0, parseInt(width), parseInt(height)];
1626 return new PageViewport({
1627 viewBox,
1628 scale,
1629 rotation
1630 });
1631 }
1632 function getRGB(color) {
1633 if (color.startsWith("#")) {
1634 const colorRGB = parseInt(color.slice(1), 16);
1635 return [(colorRGB & 0xff0000) >> 16, (colorRGB & 0x00ff00) >> 8, colorRGB & 0x0000ff];
1636 }
1637 if (color.startsWith("rgb(")) {
1638 return color.slice(4, -1).split(",").map(x => parseInt(x));
1639 }
1640 if (color.startsWith("rgba(")) {
1641 return color.slice(5, -1).split(",").map(x => parseInt(x)).slice(0, 3);
1642 }
1643 warn(`Not a valid color format: "${color}"`);
1644 return [0, 0, 0];
1645 }
1646 function getColorValues(colors) {
1647 const span = document.createElement("span");
1648 span.style.visibility = "hidden";
1649 document.body.append(span);
1650 for (const name of colors.keys()) {
1651 span.style.color = name;
1652 const computedColor = window.getComputedStyle(span).color;
1653 colors.set(name, getRGB(computedColor));
1654 }
1655 span.remove();
1656 }
1657 function getCurrentTransform(ctx) {
1658 const {
1659 a,
1660 b,
1661 c,
1662 d,
1663 e,
1664 f
1665 } = ctx.getTransform();
1666 return [a, b, c, d, e, f];
1667 }
1668 function getCurrentTransformInverse(ctx) {
1669 const {
1670 a,
1671 b,
1672 c,
1673 d,
1674 e,
1675 f
1676 } = ctx.getTransform().invertSelf();
1677 return [a, b, c, d, e, f];
1678 }
1679 function setLayerDimensions(div, viewport, mustFlip = false, mustRotate = true) {
1680 if (viewport instanceof PageViewport) {
1681 const {
1682 pageWidth,
1683 pageHeight
1684 } = viewport.rawDims;
1685 const {
1686 style
1687 } = div;
1688 const useRound = util_FeatureTest.isCSSRoundSupported;
1689 const w = `var(--scale-factor) * ${pageWidth}px`,
1690 h = `var(--scale-factor) * ${pageHeight}px`;
1691 const widthStr = useRound ? `round(down, ${w}, var(--scale-round-x, 1px))` : `calc(${w})`,
1692 heightStr = useRound ? `round(down, ${h}, var(--scale-round-y, 1px))` : `calc(${h})`;
1693 if (!mustFlip || viewport.rotation % 180 === 0) {
1694 style.width = widthStr;
1695 style.height = heightStr;
1696 } else {
1697 style.width = heightStr;
1698 style.height = widthStr;
1699 }
1700 }
1701 if (mustRotate) {
1702 div.setAttribute("data-main-rotation", viewport.rotation);
1703 }
1704 }
1705 class OutputScale {
1706 constructor() {
1707 const pixelRatio = window.devicePixelRatio || 1;
1708 this.sx = pixelRatio;
1709 this.sy = pixelRatio;
1710 }
1711 get scaled() {
1712 return this.sx !== 1 || this.sy !== 1;
1713 }
1714 get symmetric() {
1715 return this.sx === this.sy;
1716 }
1717 }
1718
1719 ;// ./src/display/editor/toolbar.js
1720
1721 class EditorToolbar {
1722 #toolbar = null;
1723 #colorPicker = null;
1724 #editor;
1725 #buttons = null;
1726 #altText = null;
1727 static #l10nRemove = null;
1728 constructor(editor) {
1729 this.#editor = editor;
1730 EditorToolbar.#l10nRemove ||= Object.freeze({
1731 freetext: "pdfjs-editor-remove-freetext-button",
1732 highlight: "pdfjs-editor-remove-highlight-button",
1733 ink: "pdfjs-editor-remove-ink-button",
1734 stamp: "pdfjs-editor-remove-stamp-button"
1735 });
1736 }
1737 render() {
1738 const editToolbar = this.#toolbar = document.createElement("div");
1739 editToolbar.classList.add("editToolbar", "hidden");
1740 editToolbar.setAttribute("role", "toolbar");
1741 const signal = this.#editor._uiManager._signal;
1742 editToolbar.addEventListener("contextmenu", noContextMenu, {
1743 signal
1744 });
1745 editToolbar.addEventListener("pointerdown", EditorToolbar.#pointerDown, {
1746 signal
1747 });
1748 const buttons = this.#buttons = document.createElement("div");
1749 buttons.className = "buttons";
1750 editToolbar.append(buttons);
1751 const position = this.#editor.toolbarPosition;
1752 if (position) {
1753 const {
1754 style
1755 } = editToolbar;
1756 const x = this.#editor._uiManager.direction === "ltr" ? 1 - position[0] : position[0];
1757 style.insetInlineEnd = `${100 * x}%`;
1758 style.top = `calc(${100 * position[1]}% + var(--editor-toolbar-vert-offset))`;
1759 }
1760 this.#addDeleteButton();
1761 return editToolbar;
1762 }
1763 get div() {
1764 return this.#toolbar;
1765 }
1766 static #pointerDown(e) {
1767 e.stopPropagation();
1768 }
1769 #focusIn(e) {
1770 this.#editor._focusEventsAllowed = false;
1771 e.preventDefault();
1772 e.stopPropagation();
1773 }
1774 #focusOut(e) {
1775 this.#editor._focusEventsAllowed = true;
1776 e.preventDefault();
1777 e.stopPropagation();
1778 }
1779 #addListenersToElement(element) {
1780 const signal = this.#editor._uiManager._signal;
1781 element.addEventListener("focusin", this.#focusIn.bind(this), {
1782 capture: true,
1783 signal
1784 });
1785 element.addEventListener("focusout", this.#focusOut.bind(this), {
1786 capture: true,
1787 signal
1788 });
1789 element.addEventListener("contextmenu", noContextMenu, {
1790 signal
1791 });
1792 }
1793 hide() {
1794 this.#toolbar.classList.add("hidden");
1795 this.#colorPicker?.hideDropdown();
1796 }
1797 show() {
1798 this.#toolbar.classList.remove("hidden");
1799 this.#altText?.shown();
1800 }
1801 #addDeleteButton() {
1802 const {
1803 editorType,
1804 _uiManager
1805 } = this.#editor;
1806 const button = document.createElement("button");
1807 button.className = "delete";
1808 button.tabIndex = 0;
1809 button.setAttribute("data-l10n-id", EditorToolbar.#l10nRemove[editorType]);
1810 this.#addListenersToElement(button);
1811 button.addEventListener("click", e => {
1812 _uiManager.delete();
1813 }, {
1814 signal: _uiManager._signal
1815 });
1816 this.#buttons.append(button);
1817 }
1818 get #divider() {
1819 const divider = document.createElement("div");
1820 divider.className = "divider";
1821 return divider;
1822 }
1823 async addAltText(altText) {
1824 const button = await altText.render();
1825 this.#addListenersToElement(button);
1826 this.#buttons.prepend(button, this.#divider);
1827 this.#altText = altText;
1828 }
1829 addColorPicker(colorPicker) {
1830 this.#colorPicker = colorPicker;
1831 const button = colorPicker.renderButton();
1832 this.#addListenersToElement(button);
1833 this.#buttons.prepend(button, this.#divider);
1834 }
1835 remove() {
1836 this.#toolbar.remove();
1837 this.#colorPicker?.destroy();
1838 this.#colorPicker = null;
1839 }
1840 }
1841 class HighlightToolbar {
1842 #buttons = null;
1843 #toolbar = null;
1844 #uiManager;
1845 constructor(uiManager) {
1846 this.#uiManager = uiManager;
1847 }
1848 #render() {
1849 const editToolbar = this.#toolbar = document.createElement("div");
1850 editToolbar.className = "editToolbar";
1851 editToolbar.setAttribute("role", "toolbar");
1852 editToolbar.addEventListener("contextmenu", noContextMenu, {
1853 signal: this.#uiManager._signal
1854 });
1855 const buttons = this.#buttons = document.createElement("div");
1856 buttons.className = "buttons";
1857 editToolbar.append(buttons);
1858 this.#addHighlightButton();
1859 return editToolbar;
1860 }
1861 #getLastPoint(boxes, isLTR) {
1862 let lastY = 0;
1863 let lastX = 0;
1864 for (const box of boxes) {
1865 const y = box.y + box.height;
1866 if (y < lastY) {
1867 continue;
1868 }
1869 const x = box.x + (isLTR ? box.width : 0);
1870 if (y > lastY) {
1871 lastX = x;
1872 lastY = y;
1873 continue;
1874 }
1875 if (isLTR) {
1876 if (x > lastX) {
1877 lastX = x;
1878 }
1879 } else if (x < lastX) {
1880 lastX = x;
1881 }
1882 }
1883 return [isLTR ? 1 - lastX : lastX, lastY];
1884 }
1885 show(parent, boxes, isLTR) {
1886 const [x, y] = this.#getLastPoint(boxes, isLTR);
1887 const {
1888 style
1889 } = this.#toolbar ||= this.#render();
1890 parent.append(this.#toolbar);
1891 style.insetInlineEnd = `${100 * x}%`;
1892 style.top = `calc(${100 * y}% + var(--editor-toolbar-vert-offset))`;
1893 }
1894 hide() {
1895 this.#toolbar.remove();
1896 }
1897 #addHighlightButton() {
1898 const button = document.createElement("button");
1899 button.className = "highlightButton";
1900 button.tabIndex = 0;
1901 button.setAttribute("data-l10n-id", `pdfjs-highlight-floating-button1`);
1902 const span = document.createElement("span");
1903 button.append(span);
1904 span.className = "visuallyHidden";
1905 span.setAttribute("data-l10n-id", "pdfjs-highlight-floating-button-label");
1906 const signal = this.#uiManager._signal;
1907 button.addEventListener("contextmenu", noContextMenu, {
1908 signal
1909 });
1910 button.addEventListener("click", () => {
1911 this.#uiManager.highlightSelection("floating_button");
1912 }, {
1913 signal
1914 });
1915 this.#buttons.append(button);
1916 }
1917 }
1918
1919 ;// ./src/display/editor/tools.js
1920
1921
1922
1923 function bindEvents(obj, element, names) {
1924 for (const name of names) {
1925 element.addEventListener(name, obj[name].bind(obj));
1926 }
1927 }
1928 function opacityToHex(opacity) {
1929 return Math.round(Math.min(255, Math.max(1, 255 * opacity))).toString(16).padStart(2, "0");
1930 }
1931 class IdManager {
1932 #id = 0;
1933 get id() {
1934 return `${AnnotationEditorPrefix}${this.#id++}`;
1935 }
1936 }
1937 class ImageManager {
1938 #baseId = getUuid();
1939 #id = 0;
1940 #cache = null;
1941 static get _isSVGFittingCanvas() {
1942 const svg = `data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>`;
1943 const canvas = new OffscreenCanvas(1, 3);
1944 const ctx = canvas.getContext("2d", {
1945 willReadFrequently: true
1946 });
1947 const image = new Image();
1948 image.src = svg;
1949 const promise = image.decode().then(() => {
1950 ctx.drawImage(image, 0, 0, 1, 1, 0, 0, 1, 3);
1951 return new Uint32Array(ctx.getImageData(0, 0, 1, 1).data.buffer)[0] === 0;
1952 });
1953 return shadow(this, "_isSVGFittingCanvas", promise);
1954 }
1955 async #get(key, rawData) {
1956 this.#cache ||= new Map();
1957 let data = this.#cache.get(key);
1958 if (data === null) {
1959 return null;
1960 }
1961 if (data?.bitmap) {
1962 data.refCounter += 1;
1963 return data;
1964 }
1965 try {
1966 data ||= {
1967 bitmap: null,
1968 id: `image_${this.#baseId}_${this.#id++}`,
1969 refCounter: 0,
1970 isSvg: false
1971 };
1972 let image;
1973 if (typeof rawData === "string") {
1974 data.url = rawData;
1975 image = await fetchData(rawData, "blob");
1976 } else if (rawData instanceof File) {
1977 image = data.file = rawData;
1978 } else if (rawData instanceof Blob) {
1979 image = rawData;
1980 }
1981 if (image.type === "image/svg+xml") {
1982 const mustRemoveAspectRatioPromise = ImageManager._isSVGFittingCanvas;
1983 const fileReader = new FileReader();
1984 const imageElement = new Image();
1985 const imagePromise = new Promise((resolve, reject) => {
1986 imageElement.onload = () => {
1987 data.bitmap = imageElement;
1988 data.isSvg = true;
1989 resolve();
1990 };
1991 fileReader.onload = async () => {
1992 const url = data.svgUrl = fileReader.result;
1993 imageElement.src = (await mustRemoveAspectRatioPromise) ? `${url}#svgView(preserveAspectRatio(none))` : url;
1994 };
1995 imageElement.onerror = fileReader.onerror = reject;
1996 });
1997 fileReader.readAsDataURL(image);
1998 await imagePromise;
1999 } else {
2000 data.bitmap = await createImageBitmap(image);
2001 }
2002 data.refCounter = 1;
2003 } catch (e) {
2004 console.error(e);
2005 data = null;
2006 }
2007 this.#cache.set(key, data);
2008 if (data) {
2009 this.#cache.set(data.id, data);
2010 }
2011 return data;
2012 }
2013 async getFromFile(file) {
2014 const {
2015 lastModified,
2016 name,
2017 size,
2018 type
2019 } = file;
2020 return this.#get(`${lastModified}_${name}_${size}_${type}`, file);
2021 }
2022 async getFromUrl(url) {
2023 return this.#get(url, url);
2024 }
2025 async getFromBlob(id, blobPromise) {
2026 const blob = await blobPromise;
2027 return this.#get(id, blob);
2028 }
2029 async getFromId(id) {
2030 this.#cache ||= new Map();
2031 const data = this.#cache.get(id);
2032 if (!data) {
2033 return null;
2034 }
2035 if (data.bitmap) {
2036 data.refCounter += 1;
2037 return data;
2038 }
2039 if (data.file) {
2040 return this.getFromFile(data.file);
2041 }
2042 if (data.blobPromise) {
2043 const {
2044 blobPromise
2045 } = data;
2046 delete data.blobPromise;
2047 return this.getFromBlob(data.id, blobPromise);
2048 }
2049 return this.getFromUrl(data.url);
2050 }
2051 getFromCanvas(id, canvas) {
2052 this.#cache ||= new Map();
2053 let data = this.#cache.get(id);
2054 if (data?.bitmap) {
2055 data.refCounter += 1;
2056 return data;
2057 }
2058 const offscreen = new OffscreenCanvas(canvas.width, canvas.height);
2059 const ctx = offscreen.getContext("2d");
2060 ctx.drawImage(canvas, 0, 0);
2061 data = {
2062 bitmap: offscreen.transferToImageBitmap(),
2063 id: `image_${this.#baseId}_${this.#id++}`,
2064 refCounter: 1,
2065 isSvg: false
2066 };
2067 this.#cache.set(id, data);
2068 this.#cache.set(data.id, data);
2069 return data;
2070 }
2071 getSvgUrl(id) {
2072 const data = this.#cache.get(id);
2073 if (!data?.isSvg) {
2074 return null;
2075 }
2076 return data.svgUrl;
2077 }
2078 deleteId(id) {
2079 this.#cache ||= new Map();
2080 const data = this.#cache.get(id);
2081 if (!data) {
2082 return;
2083 }
2084 data.refCounter -= 1;
2085 if (data.refCounter !== 0) {
2086 return;
2087 }
2088 const {
2089 bitmap
2090 } = data;
2091 if (!data.url && !data.file) {
2092 const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
2093 const ctx = canvas.getContext("bitmaprenderer");
2094 ctx.transferFromImageBitmap(bitmap);
2095 data.blobPromise = canvas.convertToBlob();
2096 }
2097 bitmap.close?.();
2098 data.bitmap = null;
2099 }
2100 isValidId(id) {
2101 return id.startsWith(`image_${this.#baseId}_`);
2102 }
2103 }
2104 class CommandManager {
2105 #commands = [];
2106 #locked = false;
2107 #maxSize;
2108 #position = -1;
2109 constructor(maxSize = 128) {
2110 this.#maxSize = maxSize;
2111 }
2112 add({
2113 cmd,
2114 undo,
2115 post,
2116 mustExec,
2117 type = NaN,
2118 overwriteIfSameType = false,
2119 keepUndo = false
2120 }) {
2121 if (mustExec) {
2122 cmd();
2123 }
2124 if (this.#locked) {
2125 return;
2126 }
2127 const save = {
2128 cmd,
2129 undo,
2130 post,
2131 type
2132 };
2133 if (this.#position === -1) {
2134 if (this.#commands.length > 0) {
2135 this.#commands.length = 0;
2136 }
2137 this.#position = 0;
2138 this.#commands.push(save);
2139 return;
2140 }
2141 if (overwriteIfSameType && this.#commands[this.#position].type === type) {
2142 if (keepUndo) {
2143 save.undo = this.#commands[this.#position].undo;
2144 }
2145 this.#commands[this.#position] = save;
2146 return;
2147 }
2148 const next = this.#position + 1;
2149 if (next === this.#maxSize) {
2150 this.#commands.splice(0, 1);
2151 } else {
2152 this.#position = next;
2153 if (next < this.#commands.length) {
2154 this.#commands.splice(next);
2155 }
2156 }
2157 this.#commands.push(save);
2158 }
2159 undo() {
2160 if (this.#position === -1) {
2161 return;
2162 }
2163 this.#locked = true;
2164 const {
2165 undo,
2166 post
2167 } = this.#commands[this.#position];
2168 undo();
2169 post?.();
2170 this.#locked = false;
2171 this.#position -= 1;
2172 }
2173 redo() {
2174 if (this.#position < this.#commands.length - 1) {
2175 this.#position += 1;
2176 this.#locked = true;
2177 const {
2178 cmd,
2179 post
2180 } = this.#commands[this.#position];
2181 cmd();
2182 post?.();
2183 this.#locked = false;
2184 }
2185 }
2186 hasSomethingToUndo() {
2187 return this.#position !== -1;
2188 }
2189 hasSomethingToRedo() {
2190 return this.#position < this.#commands.length - 1;
2191 }
2192 destroy() {
2193 this.#commands = null;
2194 }
2195 }
2196 class KeyboardManager {
2197 constructor(callbacks) {
2198 this.buffer = [];
2199 this.callbacks = new Map();
2200 this.allKeys = new Set();
2201 const {
2202 isMac
2203 } = util_FeatureTest.platform;
2204 for (const [keys, callback, options = {}] of callbacks) {
2205 for (const key of keys) {
2206 const isMacKey = key.startsWith("mac+");
2207 if (isMac && isMacKey) {
2208 this.callbacks.set(key.slice(4), {
2209 callback,
2210 options
2211 });
2212 this.allKeys.add(key.split("+").at(-1));
2213 } else if (!isMac && !isMacKey) {
2214 this.callbacks.set(key, {
2215 callback,
2216 options
2217 });
2218 this.allKeys.add(key.split("+").at(-1));
2219 }
2220 }
2221 }
2222 }
2223 #serialize(event) {
2224 if (event.altKey) {
2225 this.buffer.push("alt");
2226 }
2227 if (event.ctrlKey) {
2228 this.buffer.push("ctrl");
2229 }
2230 if (event.metaKey) {
2231 this.buffer.push("meta");
2232 }
2233 if (event.shiftKey) {
2234 this.buffer.push("shift");
2235 }
2236 this.buffer.push(event.key);
2237 const str = this.buffer.join("+");
2238 this.buffer.length = 0;
2239 return str;
2240 }
2241 exec(self, event) {
2242 if (!this.allKeys.has(event.key)) {
2243 return;
2244 }
2245 const info = this.callbacks.get(this.#serialize(event));
2246 if (!info) {
2247 return;
2248 }
2249 const {
2250 callback,
2251 options: {
2252 bubbles = false,
2253 args = [],
2254 checker = null
2255 }
2256 } = info;
2257 if (checker && !checker(self, event)) {
2258 return;
2259 }
2260 callback.bind(self, ...args, event)();
2261 if (!bubbles) {
2262 event.stopPropagation();
2263 event.preventDefault();
2264 }
2265 }
2266 }
2267 class ColorManager {
2268 static _colorsMapping = new Map([["CanvasText", [0, 0, 0]], ["Canvas", [255, 255, 255]]]);
2269 get _colors() {
2270 const colors = new Map([["CanvasText", null], ["Canvas", null]]);
2271 getColorValues(colors);
2272 return shadow(this, "_colors", colors);
2273 }
2274 convert(color) {
2275 const rgb = getRGB(color);
2276 if (!window.matchMedia("(forced-colors: active)").matches) {
2277 return rgb;
2278 }
2279 for (const [name, RGB] of this._colors) {
2280 if (RGB.every((x, i) => x === rgb[i])) {
2281 return ColorManager._colorsMapping.get(name);
2282 }
2283 }
2284 return rgb;
2285 }
2286 getHexCode(name) {
2287 const rgb = this._colors.get(name);
2288 if (!rgb) {
2289 return name;
2290 }
2291 return Util.makeHexColor(...rgb);
2292 }
2293 }
2294 class AnnotationEditorUIManager {
2295 #abortController = new AbortController();
2296 #activeEditor = null;
2297 #allEditors = new Map();
2298 #allLayers = new Map();
2299 #altTextManager = null;
2300 #annotationStorage = null;
2301 #changedExistingAnnotations = null;
2302 #commandManager = new CommandManager();
2303 #copyPasteAC = null;
2304 #currentPageIndex = 0;
2305 #deletedAnnotationsElementIds = new Set();
2306 #draggingEditors = null;
2307 #editorTypes = null;
2308 #editorsToRescale = new Set();
2309 #enableHighlightFloatingButton = false;
2310 #enableUpdatedAddImage = false;
2311 #enableNewAltTextWhenAddingImage = false;
2312 #filterFactory = null;
2313 #focusMainContainerTimeoutId = null;
2314 #focusManagerAC = null;
2315 #highlightColors = null;
2316 #highlightWhenShiftUp = false;
2317 #highlightToolbar = null;
2318 #idManager = new IdManager();
2319 #isEnabled = false;
2320 #isWaiting = false;
2321 #keyboardManagerAC = null;
2322 #lastActiveElement = null;
2323 #mainHighlightColorPicker = null;
2324 #mlManager = null;
2325 #mode = AnnotationEditorType.NONE;
2326 #selectedEditors = new Set();
2327 #selectedTextNode = null;
2328 #pageColors = null;
2329 #showAllStates = null;
2330 #previousStates = {
2331 isEditing: false,
2332 isEmpty: true,
2333 hasSomethingToUndo: false,
2334 hasSomethingToRedo: false,
2335 hasSelectedEditor: false,
2336 hasSelectedText: false
2337 };
2338 #translation = [0, 0];
2339 #translationTimeoutId = null;
2340 #container = null;
2341 #viewer = null;
2342 #updateModeCapability = null;
2343 static TRANSLATE_SMALL = 1;
2344 static TRANSLATE_BIG = 10;
2345 static get _keyboardManager() {
2346 const proto = AnnotationEditorUIManager.prototype;
2347 const arrowChecker = self => self.#container.contains(document.activeElement) && document.activeElement.tagName !== "BUTTON" && self.hasSomethingToControl();
2348 const textInputChecker = (_self, {
2349 target: el
2350 }) => {
2351 if (el instanceof HTMLInputElement) {
2352 const {
2353 type
2354 } = el;
2355 return type !== "text" && type !== "number";
2356 }
2357 return true;
2358 };
2359 const small = this.TRANSLATE_SMALL;
2360 const big = this.TRANSLATE_BIG;
2361 return shadow(this, "_keyboardManager", new KeyboardManager([[["ctrl+a", "mac+meta+a"], proto.selectAll, {
2362 checker: textInputChecker
2363 }], [["ctrl+z", "mac+meta+z"], proto.undo, {
2364 checker: textInputChecker
2365 }], [["ctrl+y", "ctrl+shift+z", "mac+meta+shift+z", "ctrl+shift+Z", "mac+meta+shift+Z"], proto.redo, {
2366 checker: textInputChecker
2367 }], [["Backspace", "alt+Backspace", "ctrl+Backspace", "shift+Backspace", "mac+Backspace", "mac+alt+Backspace", "mac+ctrl+Backspace", "Delete", "ctrl+Delete", "shift+Delete", "mac+Delete"], proto.delete, {
2368 checker: textInputChecker
2369 }], [["Enter", "mac+Enter"], proto.addNewEditorFromKeyboard, {
2370 checker: (self, {
2371 target: el
2372 }) => !(el instanceof HTMLButtonElement) && self.#container.contains(el) && !self.isEnterHandled
2373 }], [[" ", "mac+ "], proto.addNewEditorFromKeyboard, {
2374 checker: (self, {
2375 target: el
2376 }) => !(el instanceof HTMLButtonElement) && self.#container.contains(document.activeElement)
2377 }], [["Escape", "mac+Escape"], proto.unselectAll], [["ArrowLeft", "mac+ArrowLeft"], proto.translateSelectedEditors, {
2378 args: [-small, 0],
2379 checker: arrowChecker
2380 }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], proto.translateSelectedEditors, {
2381 args: [-big, 0],
2382 checker: arrowChecker
2383 }], [["ArrowRight", "mac+ArrowRight"], proto.translateSelectedEditors, {
2384 args: [small, 0],
2385 checker: arrowChecker
2386 }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], proto.translateSelectedEditors, {
2387 args: [big, 0],
2388 checker: arrowChecker
2389 }], [["ArrowUp", "mac+ArrowUp"], proto.translateSelectedEditors, {
2390 args: [0, -small],
2391 checker: arrowChecker
2392 }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], proto.translateSelectedEditors, {
2393 args: [0, -big],
2394 checker: arrowChecker
2395 }], [["ArrowDown", "mac+ArrowDown"], proto.translateSelectedEditors, {
2396 args: [0, small],
2397 checker: arrowChecker
2398 }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], proto.translateSelectedEditors, {
2399 args: [0, big],
2400 checker: arrowChecker
2401 }]]));
2402 }
2403 constructor(container, viewer, altTextManager, eventBus, pdfDocument, pageColors, highlightColors, enableHighlightFloatingButton, enableUpdatedAddImage, enableNewAltTextWhenAddingImage, mlManager) {
2404 const signal = this._signal = this.#abortController.signal;
2405 this.#container = container;
2406 this.#viewer = viewer;
2407 this.#altTextManager = altTextManager;
2408 this._eventBus = eventBus;
2409 eventBus._on("editingaction", this.onEditingAction.bind(this), {
2410 signal
2411 });
2412 eventBus._on("pagechanging", this.onPageChanging.bind(this), {
2413 signal
2414 });
2415 eventBus._on("scalechanging", this.onScaleChanging.bind(this), {
2416 signal
2417 });
2418 eventBus._on("rotationchanging", this.onRotationChanging.bind(this), {
2419 signal
2420 });
2421 eventBus._on("setpreference", this.onSetPreference.bind(this), {
2422 signal
2423 });
2424 eventBus._on("switchannotationeditorparams", evt => this.updateParams(evt.type, evt.value), {
2425 signal
2426 });
2427 this.#addSelectionListener();
2428 this.#addDragAndDropListeners();
2429 this.#addKeyboardManager();
2430 this.#annotationStorage = pdfDocument.annotationStorage;
2431 this.#filterFactory = pdfDocument.filterFactory;
2432 this.#pageColors = pageColors;
2433 this.#highlightColors = highlightColors || null;
2434 this.#enableHighlightFloatingButton = enableHighlightFloatingButton;
2435 this.#enableUpdatedAddImage = enableUpdatedAddImage;
2436 this.#enableNewAltTextWhenAddingImage = enableNewAltTextWhenAddingImage;
2437 this.#mlManager = mlManager || null;
2438 this.viewParameters = {
2439 realScale: PixelsPerInch.PDF_TO_CSS_UNITS,
2440 rotation: 0
2441 };
2442 this.isShiftKeyDown = false;
2443 }
2444 destroy() {
2445 this.#updateModeCapability?.resolve();
2446 this.#updateModeCapability = null;
2447 this.#abortController?.abort();
2448 this.#abortController = null;
2449 this._signal = null;
2450 for (const layer of this.#allLayers.values()) {
2451 layer.destroy();
2452 }
2453 this.#allLayers.clear();
2454 this.#allEditors.clear();
2455 this.#editorsToRescale.clear();
2456 this.#activeEditor = null;
2457 this.#selectedEditors.clear();
2458 this.#commandManager.destroy();
2459 this.#altTextManager?.destroy();
2460 this.#highlightToolbar?.hide();
2461 this.#highlightToolbar = null;
2462 if (this.#focusMainContainerTimeoutId) {
2463 clearTimeout(this.#focusMainContainerTimeoutId);
2464 this.#focusMainContainerTimeoutId = null;
2465 }
2466 if (this.#translationTimeoutId) {
2467 clearTimeout(this.#translationTimeoutId);
2468 this.#translationTimeoutId = null;
2469 }
2470 }
2471 combinedSignal(ac) {
2472 return AbortSignal.any([this._signal, ac.signal]);
2473 }
2474 get mlManager() {
2475 return this.#mlManager;
2476 }
2477 get useNewAltTextFlow() {
2478 return this.#enableUpdatedAddImage;
2479 }
2480 get useNewAltTextWhenAddingImage() {
2481 return this.#enableNewAltTextWhenAddingImage;
2482 }
2483 get hcmFilter() {
2484 return shadow(this, "hcmFilter", this.#pageColors ? this.#filterFactory.addHCMFilter(this.#pageColors.foreground, this.#pageColors.background) : "none");
2485 }
2486 get direction() {
2487 return shadow(this, "direction", getComputedStyle(this.#container).direction);
2488 }
2489 get highlightColors() {
2490 return shadow(this, "highlightColors", this.#highlightColors ? new Map(this.#highlightColors.split(",").map(pair => pair.split("=").map(x => x.trim()))) : null);
2491 }
2492 get highlightColorNames() {
2493 return shadow(this, "highlightColorNames", this.highlightColors ? new Map(Array.from(this.highlightColors, e => e.reverse())) : null);
2494 }
2495 setMainHighlightColorPicker(colorPicker) {
2496 this.#mainHighlightColorPicker = colorPicker;
2497 }
2498 editAltText(editor, firstTime = false) {
2499 this.#altTextManager?.editAltText(this, editor, firstTime);
2500 }
2501 switchToMode(mode, callback) {
2502 this._eventBus.on("annotationeditormodechanged", callback, {
2503 once: true,
2504 signal: this._signal
2505 });
2506 this._eventBus.dispatch("showannotationeditorui", {
2507 source: this,
2508 mode
2509 });
2510 }
2511 setPreference(name, value) {
2512 this._eventBus.dispatch("setpreference", {
2513 source: this,
2514 name,
2515 value
2516 });
2517 }
2518 onSetPreference({
2519 name,
2520 value
2521 }) {
2522 switch (name) {
2523 case "enableNewAltTextWhenAddingImage":
2524 this.#enableNewAltTextWhenAddingImage = value;
2525 break;
2526 }
2527 }
2528 onPageChanging({
2529 pageNumber
2530 }) {
2531 this.#currentPageIndex = pageNumber - 1;
2532 }
2533 focusMainContainer() {
2534 this.#container.focus();
2535 }
2536 findParent(x, y) {
2537 for (const layer of this.#allLayers.values()) {
2538 const {
2539 x: layerX,
2540 y: layerY,
2541 width,
2542 height
2543 } = layer.div.getBoundingClientRect();
2544 if (x >= layerX && x <= layerX + width && y >= layerY && y <= layerY + height) {
2545 return layer;
2546 }
2547 }
2548 return null;
2549 }
2550 disableUserSelect(value = false) {
2551 this.#viewer.classList.toggle("noUserSelect", value);
2552 }
2553 addShouldRescale(editor) {
2554 this.#editorsToRescale.add(editor);
2555 }
2556 removeShouldRescale(editor) {
2557 this.#editorsToRescale.delete(editor);
2558 }
2559 onScaleChanging({
2560 scale
2561 }) {
2562 this.commitOrRemove();
2563 this.viewParameters.realScale = scale * PixelsPerInch.PDF_TO_CSS_UNITS;
2564 for (const editor of this.#editorsToRescale) {
2565 editor.onScaleChanging();
2566 }
2567 }
2568 onRotationChanging({
2569 pagesRotation
2570 }) {
2571 this.commitOrRemove();
2572 this.viewParameters.rotation = pagesRotation;
2573 }
2574 #getAnchorElementForSelection({
2575 anchorNode
2576 }) {
2577 return anchorNode.nodeType === Node.TEXT_NODE ? anchorNode.parentElement : anchorNode;
2578 }
2579 #getLayerForTextLayer(textLayer) {
2580 const {
2581 currentLayer
2582 } = this;
2583 if (currentLayer.hasTextLayer(textLayer)) {
2584 return currentLayer;
2585 }
2586 for (const layer of this.#allLayers.values()) {
2587 if (layer.hasTextLayer(textLayer)) {
2588 return layer;
2589 }
2590 }
2591 return null;
2592 }
2593 highlightSelection(methodOfCreation = "") {
2594 const selection = document.getSelection();
2595 if (!selection || selection.isCollapsed) {
2596 return;
2597 }
2598 const {
2599 anchorNode,
2600 anchorOffset,
2601 focusNode,
2602 focusOffset
2603 } = selection;
2604 const text = selection.toString();
2605 const anchorElement = this.#getAnchorElementForSelection(selection);
2606 const textLayer = anchorElement.closest(".textLayer");
2607 const boxes = this.getSelectionBoxes(textLayer);
2608 if (!boxes) {
2609 return;
2610 }
2611 selection.empty();
2612 const layer = this.#getLayerForTextLayer(textLayer);
2613 const isNoneMode = this.#mode === AnnotationEditorType.NONE;
2614 const callback = () => {
2615 layer?.createAndAddNewEditor({
2616 x: 0,
2617 y: 0
2618 }, false, {
2619 methodOfCreation,
2620 boxes,
2621 anchorNode,
2622 anchorOffset,
2623 focusNode,
2624 focusOffset,
2625 text
2626 });
2627 if (isNoneMode) {
2628 this.showAllEditors("highlight", true, true);
2629 }
2630 };
2631 if (isNoneMode) {
2632 this.switchToMode(AnnotationEditorType.HIGHLIGHT, callback);
2633 return;
2634 }
2635 callback();
2636 }
2637 #displayHighlightToolbar() {
2638 const selection = document.getSelection();
2639 if (!selection || selection.isCollapsed) {
2640 return;
2641 }
2642 const anchorElement = this.#getAnchorElementForSelection(selection);
2643 const textLayer = anchorElement.closest(".textLayer");
2644 const boxes = this.getSelectionBoxes(textLayer);
2645 if (!boxes) {
2646 return;
2647 }
2648 this.#highlightToolbar ||= new HighlightToolbar(this);
2649 this.#highlightToolbar.show(textLayer, boxes, this.direction === "ltr");
2650 }
2651 addToAnnotationStorage(editor) {
2652 if (!editor.isEmpty() && this.#annotationStorage && !this.#annotationStorage.has(editor.id)) {
2653 this.#annotationStorage.setValue(editor.id, editor);
2654 }
2655 }
2656 #selectionChange() {
2657 const selection = document.getSelection();
2658 if (!selection || selection.isCollapsed) {
2659 if (this.#selectedTextNode) {
2660 this.#highlightToolbar?.hide();
2661 this.#selectedTextNode = null;
2662 this.#dispatchUpdateStates({
2663 hasSelectedText: false
2664 });
2665 }
2666 return;
2667 }
2668 const {
2669 anchorNode
2670 } = selection;
2671 if (anchorNode === this.#selectedTextNode) {
2672 return;
2673 }
2674 const anchorElement = this.#getAnchorElementForSelection(selection);
2675 const textLayer = anchorElement.closest(".textLayer");
2676 if (!textLayer) {
2677 if (this.#selectedTextNode) {
2678 this.#highlightToolbar?.hide();
2679 this.#selectedTextNode = null;
2680 this.#dispatchUpdateStates({
2681 hasSelectedText: false
2682 });
2683 }
2684 return;
2685 }
2686 this.#highlightToolbar?.hide();
2687 this.#selectedTextNode = anchorNode;
2688 this.#dispatchUpdateStates({
2689 hasSelectedText: true
2690 });
2691 if (this.#mode !== AnnotationEditorType.HIGHLIGHT && this.#mode !== AnnotationEditorType.NONE) {
2692 return;
2693 }
2694 if (this.#mode === AnnotationEditorType.HIGHLIGHT) {
2695 this.showAllEditors("highlight", true, true);
2696 }
2697 this.#highlightWhenShiftUp = this.isShiftKeyDown;
2698 if (!this.isShiftKeyDown) {
2699 const activeLayer = this.#mode === AnnotationEditorType.HIGHLIGHT ? this.#getLayerForTextLayer(textLayer) : null;
2700 activeLayer?.toggleDrawing();
2701 const ac = new AbortController();
2702 const signal = this.combinedSignal(ac);
2703 const pointerup = e => {
2704 if (e.type === "pointerup" && e.button !== 0) {
2705 return;
2706 }
2707 ac.abort();
2708 activeLayer?.toggleDrawing(true);
2709 if (e.type === "pointerup") {
2710 this.#onSelectEnd("main_toolbar");
2711 }
2712 };
2713 window.addEventListener("pointerup", pointerup, {
2714 signal
2715 });
2716 window.addEventListener("blur", pointerup, {
2717 signal
2718 });
2719 }
2720 }
2721 #onSelectEnd(methodOfCreation = "") {
2722 if (this.#mode === AnnotationEditorType.HIGHLIGHT) {
2723 this.highlightSelection(methodOfCreation);
2724 } else if (this.#enableHighlightFloatingButton) {
2725 this.#displayHighlightToolbar();
2726 }
2727 }
2728 #addSelectionListener() {
2729 document.addEventListener("selectionchange", this.#selectionChange.bind(this), {
2730 signal: this._signal
2731 });
2732 }
2733 #addFocusManager() {
2734 if (this.#focusManagerAC) {
2735 return;
2736 }
2737 this.#focusManagerAC = new AbortController();
2738 const signal = this.combinedSignal(this.#focusManagerAC);
2739 window.addEventListener("focus", this.focus.bind(this), {
2740 signal
2741 });
2742 window.addEventListener("blur", this.blur.bind(this), {
2743 signal
2744 });
2745 }
2746 #removeFocusManager() {
2747 this.#focusManagerAC?.abort();
2748 this.#focusManagerAC = null;
2749 }
2750 blur() {
2751 this.isShiftKeyDown = false;
2752 if (this.#highlightWhenShiftUp) {
2753 this.#highlightWhenShiftUp = false;
2754 this.#onSelectEnd("main_toolbar");
2755 }
2756 if (!this.hasSelection) {
2757 return;
2758 }
2759 const {
2760 activeElement
2761 } = document;
2762 for (const editor of this.#selectedEditors) {
2763 if (editor.div.contains(activeElement)) {
2764 this.#lastActiveElement = [editor, activeElement];
2765 editor._focusEventsAllowed = false;
2766 break;
2767 }
2768 }
2769 }
2770 focus() {
2771 if (!this.#lastActiveElement) {
2772 return;
2773 }
2774 const [lastEditor, lastActiveElement] = this.#lastActiveElement;
2775 this.#lastActiveElement = null;
2776 lastActiveElement.addEventListener("focusin", () => {
2777 lastEditor._focusEventsAllowed = true;
2778 }, {
2779 once: true,
2780 signal: this._signal
2781 });
2782 lastActiveElement.focus();
2783 }
2784 #addKeyboardManager() {
2785 if (this.#keyboardManagerAC) {
2786 return;
2787 }
2788 this.#keyboardManagerAC = new AbortController();
2789 const signal = this.combinedSignal(this.#keyboardManagerAC);
2790 window.addEventListener("keydown", this.keydown.bind(this), {
2791 signal
2792 });
2793 window.addEventListener("keyup", this.keyup.bind(this), {
2794 signal
2795 });
2796 }
2797 #removeKeyboardManager() {
2798 this.#keyboardManagerAC?.abort();
2799 this.#keyboardManagerAC = null;
2800 }
2801 #addCopyPasteListeners() {
2802 if (this.#copyPasteAC) {
2803 return;
2804 }
2805 this.#copyPasteAC = new AbortController();
2806 const signal = this.combinedSignal(this.#copyPasteAC);
2807 document.addEventListener("copy", this.copy.bind(this), {
2808 signal
2809 });
2810 document.addEventListener("cut", this.cut.bind(this), {
2811 signal
2812 });
2813 document.addEventListener("paste", this.paste.bind(this), {
2814 signal
2815 });
2816 }
2817 #removeCopyPasteListeners() {
2818 this.#copyPasteAC?.abort();
2819 this.#copyPasteAC = null;
2820 }
2821 #addDragAndDropListeners() {
2822 const signal = this._signal;
2823 document.addEventListener("dragover", this.dragOver.bind(this), {
2824 signal
2825 });
2826 document.addEventListener("drop", this.drop.bind(this), {
2827 signal
2828 });
2829 }
2830 addEditListeners() {
2831 this.#addKeyboardManager();
2832 this.#addCopyPasteListeners();
2833 }
2834 removeEditListeners() {
2835 this.#removeKeyboardManager();
2836 this.#removeCopyPasteListeners();
2837 }
2838 dragOver(event) {
2839 for (const {
2840 type
2841 } of event.dataTransfer.items) {
2842 for (const editorType of this.#editorTypes) {
2843 if (editorType.isHandlingMimeForPasting(type)) {
2844 event.dataTransfer.dropEffect = "copy";
2845 event.preventDefault();
2846 return;
2847 }
2848 }
2849 }
2850 }
2851 drop(event) {
2852 for (const item of event.dataTransfer.items) {
2853 for (const editorType of this.#editorTypes) {
2854 if (editorType.isHandlingMimeForPasting(item.type)) {
2855 editorType.paste(item, this.currentLayer);
2856 event.preventDefault();
2857 return;
2858 }
2859 }
2860 }
2861 }
2862 copy(event) {
2863 event.preventDefault();
2864 this.#activeEditor?.commitOrRemove();
2865 if (!this.hasSelection) {
2866 return;
2867 }
2868 const editors = [];
2869 for (const editor of this.#selectedEditors) {
2870 const serialized = editor.serialize(true);
2871 if (serialized) {
2872 editors.push(serialized);
2873 }
2874 }
2875 if (editors.length === 0) {
2876 return;
2877 }
2878 event.clipboardData.setData("application/pdfjs", JSON.stringify(editors));
2879 }
2880 cut(event) {
2881 this.copy(event);
2882 this.delete();
2883 }
2884 async paste(event) {
2885 event.preventDefault();
2886 const {
2887 clipboardData
2888 } = event;
2889 for (const item of clipboardData.items) {
2890 for (const editorType of this.#editorTypes) {
2891 if (editorType.isHandlingMimeForPasting(item.type)) {
2892 editorType.paste(item, this.currentLayer);
2893 return;
2894 }
2895 }
2896 }
2897 let data = clipboardData.getData("application/pdfjs");
2898 if (!data) {
2899 return;
2900 }
2901 try {
2902 data = JSON.parse(data);
2903 } catch (ex) {
2904 warn(`paste: "${ex.message}".`);
2905 return;
2906 }
2907 if (!Array.isArray(data)) {
2908 return;
2909 }
2910 this.unselectAll();
2911 const layer = this.currentLayer;
2912 try {
2913 const newEditors = [];
2914 for (const editor of data) {
2915 const deserializedEditor = await layer.deserialize(editor);
2916 if (!deserializedEditor) {
2917 return;
2918 }
2919 newEditors.push(deserializedEditor);
2920 }
2921 const cmd = () => {
2922 for (const editor of newEditors) {
2923 this.#addEditorToLayer(editor);
2924 }
2925 this.#selectEditors(newEditors);
2926 };
2927 const undo = () => {
2928 for (const editor of newEditors) {
2929 editor.remove();
2930 }
2931 };
2932 this.addCommands({
2933 cmd,
2934 undo,
2935 mustExec: true
2936 });
2937 } catch (ex) {
2938 warn(`paste: "${ex.message}".`);
2939 }
2940 }
2941 keydown(event) {
2942 if (!this.isShiftKeyDown && event.key === "Shift") {
2943 this.isShiftKeyDown = true;
2944 }
2945 if (this.#mode !== AnnotationEditorType.NONE && !this.isEditorHandlingKeyboard) {
2946 AnnotationEditorUIManager._keyboardManager.exec(this, event);
2947 }
2948 }
2949 keyup(event) {
2950 if (this.isShiftKeyDown && event.key === "Shift") {
2951 this.isShiftKeyDown = false;
2952 if (this.#highlightWhenShiftUp) {
2953 this.#highlightWhenShiftUp = false;
2954 this.#onSelectEnd("main_toolbar");
2955 }
2956 }
2957 }
2958 onEditingAction({
2959 name
2960 }) {
2961 switch (name) {
2962 case "undo":
2963 case "redo":
2964 case "delete":
2965 case "selectAll":
2966 this[name]();
2967 break;
2968 case "highlightSelection":
2969 this.highlightSelection("context_menu");
2970 break;
2971 }
2972 }
2973 #dispatchUpdateStates(details) {
2974 const hasChanged = Object.entries(details).some(([key, value]) => this.#previousStates[key] !== value);
2975 if (hasChanged) {
2976 this._eventBus.dispatch("annotationeditorstateschanged", {
2977 source: this,
2978 details: Object.assign(this.#previousStates, details)
2979 });
2980 if (this.#mode === AnnotationEditorType.HIGHLIGHT && details.hasSelectedEditor === false) {
2981 this.#dispatchUpdateUI([[AnnotationEditorParamsType.HIGHLIGHT_FREE, true]]);
2982 }
2983 }
2984 }
2985 #dispatchUpdateUI(details) {
2986 this._eventBus.dispatch("annotationeditorparamschanged", {
2987 source: this,
2988 details
2989 });
2990 }
2991 setEditingState(isEditing) {
2992 if (isEditing) {
2993 this.#addFocusManager();
2994 this.#addCopyPasteListeners();
2995 this.#dispatchUpdateStates({
2996 isEditing: this.#mode !== AnnotationEditorType.NONE,
2997 isEmpty: this.#isEmpty(),
2998 hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
2999 hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
3000 hasSelectedEditor: false
3001 });
3002 } else {
3003 this.#removeFocusManager();
3004 this.#removeCopyPasteListeners();
3005 this.#dispatchUpdateStates({
3006 isEditing: false
3007 });
3008 this.disableUserSelect(false);
3009 }
3010 }
3011 registerEditorTypes(types) {
3012 if (this.#editorTypes) {
3013 return;
3014 }
3015 this.#editorTypes = types;
3016 for (const editorType of this.#editorTypes) {
3017 this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate);
3018 }
3019 }
3020 getId() {
3021 return this.#idManager.id;
3022 }
3023 get currentLayer() {
3024 return this.#allLayers.get(this.#currentPageIndex);
3025 }
3026 getLayer(pageIndex) {
3027 return this.#allLayers.get(pageIndex);
3028 }
3029 get currentPageIndex() {
3030 return this.#currentPageIndex;
3031 }
3032 addLayer(layer) {
3033 this.#allLayers.set(layer.pageIndex, layer);
3034 if (this.#isEnabled) {
3035 layer.enable();
3036 } else {
3037 layer.disable();
3038 }
3039 }
3040 removeLayer(layer) {
3041 this.#allLayers.delete(layer.pageIndex);
3042 }
3043 async updateMode(mode, editId = null, isFromKeyboard = false) {
3044 if (this.#mode === mode) {
3045 return;
3046 }
3047 if (this.#updateModeCapability) {
3048 await this.#updateModeCapability.promise;
3049 if (!this.#updateModeCapability) {
3050 return;
3051 }
3052 }
3053 this.#updateModeCapability = Promise.withResolvers();
3054 this.#mode = mode;
3055 if (mode === AnnotationEditorType.NONE) {
3056 this.setEditingState(false);
3057 this.#disableAll();
3058 this.#updateModeCapability.resolve();
3059 return;
3060 }
3061 this.setEditingState(true);
3062 await this.#enableAll();
3063 this.unselectAll();
3064 for (const layer of this.#allLayers.values()) {
3065 layer.updateMode(mode);
3066 }
3067 if (!editId) {
3068 if (isFromKeyboard) {
3069 this.addNewEditorFromKeyboard();
3070 }
3071 this.#updateModeCapability.resolve();
3072 return;
3073 }
3074 for (const editor of this.#allEditors.values()) {
3075 if (editor.annotationElementId === editId) {
3076 this.setSelected(editor);
3077 editor.enterInEditMode();
3078 } else {
3079 editor.unselect();
3080 }
3081 }
3082 this.#updateModeCapability.resolve();
3083 }
3084 addNewEditorFromKeyboard() {
3085 if (this.currentLayer.canCreateNewEmptyEditor()) {
3086 this.currentLayer.addNewEditor();
3087 }
3088 }
3089 updateToolbar(mode) {
3090 if (mode === this.#mode) {
3091 return;
3092 }
3093 this._eventBus.dispatch("switchannotationeditormode", {
3094 source: this,
3095 mode
3096 });
3097 }
3098 updateParams(type, value) {
3099 if (!this.#editorTypes) {
3100 return;
3101 }
3102 switch (type) {
3103 case AnnotationEditorParamsType.CREATE:
3104 this.currentLayer.addNewEditor();
3105 return;
3106 case AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR:
3107 this.#mainHighlightColorPicker?.updateColor(value);
3108 break;
3109 case AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL:
3110 this._eventBus.dispatch("reporttelemetry", {
3111 source: this,
3112 details: {
3113 type: "editing",
3114 data: {
3115 type: "highlight",
3116 action: "toggle_visibility"
3117 }
3118 }
3119 });
3120 (this.#showAllStates ||= new Map()).set(type, value);
3121 this.showAllEditors("highlight", value);
3122 break;
3123 }
3124 for (const editor of this.#selectedEditors) {
3125 editor.updateParams(type, value);
3126 }
3127 for (const editorType of this.#editorTypes) {
3128 editorType.updateDefaultParams(type, value);
3129 }
3130 }
3131 showAllEditors(type, visible, updateButton = false) {
3132 for (const editor of this.#allEditors.values()) {
3133 if (editor.editorType === type) {
3134 editor.show(visible);
3135 }
3136 }
3137 const state = this.#showAllStates?.get(AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL) ?? true;
3138 if (state !== visible) {
3139 this.#dispatchUpdateUI([[AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL, visible]]);
3140 }
3141 }
3142 enableWaiting(mustWait = false) {
3143 if (this.#isWaiting === mustWait) {
3144 return;
3145 }
3146 this.#isWaiting = mustWait;
3147 for (const layer of this.#allLayers.values()) {
3148 if (mustWait) {
3149 layer.disableClick();
3150 } else {
3151 layer.enableClick();
3152 }
3153 layer.div.classList.toggle("waiting", mustWait);
3154 }
3155 }
3156 async #enableAll() {
3157 if (!this.#isEnabled) {
3158 this.#isEnabled = true;
3159 const promises = [];
3160 for (const layer of this.#allLayers.values()) {
3161 promises.push(layer.enable());
3162 }
3163 await Promise.all(promises);
3164 for (const editor of this.#allEditors.values()) {
3165 editor.enable();
3166 }
3167 }
3168 }
3169 #disableAll() {
3170 this.unselectAll();
3171 if (this.#isEnabled) {
3172 this.#isEnabled = false;
3173 for (const layer of this.#allLayers.values()) {
3174 layer.disable();
3175 }
3176 for (const editor of this.#allEditors.values()) {
3177 editor.disable();
3178 }
3179 }
3180 }
3181 getEditors(pageIndex) {
3182 const editors = [];
3183 for (const editor of this.#allEditors.values()) {
3184 if (editor.pageIndex === pageIndex) {
3185 editors.push(editor);
3186 }
3187 }
3188 return editors;
3189 }
3190 getEditor(id) {
3191 return this.#allEditors.get(id);
3192 }
3193 addEditor(editor) {
3194 this.#allEditors.set(editor.id, editor);
3195 }
3196 removeEditor(editor) {
3197 if (editor.div.contains(document.activeElement)) {
3198 if (this.#focusMainContainerTimeoutId) {
3199 clearTimeout(this.#focusMainContainerTimeoutId);
3200 }
3201 this.#focusMainContainerTimeoutId = setTimeout(() => {
3202 this.focusMainContainer();
3203 this.#focusMainContainerTimeoutId = null;
3204 }, 0);
3205 }
3206 this.#allEditors.delete(editor.id);
3207 this.unselect(editor);
3208 if (!editor.annotationElementId || !this.#deletedAnnotationsElementIds.has(editor.annotationElementId)) {
3209 this.#annotationStorage?.remove(editor.id);
3210 }
3211 }
3212 addDeletedAnnotationElement(editor) {
3213 this.#deletedAnnotationsElementIds.add(editor.annotationElementId);
3214 this.addChangedExistingAnnotation(editor);
3215 editor.deleted = true;
3216 }
3217 isDeletedAnnotationElement(annotationElementId) {
3218 return this.#deletedAnnotationsElementIds.has(annotationElementId);
3219 }
3220 removeDeletedAnnotationElement(editor) {
3221 this.#deletedAnnotationsElementIds.delete(editor.annotationElementId);
3222 this.removeChangedExistingAnnotation(editor);
3223 editor.deleted = false;
3224 }
3225 #addEditorToLayer(editor) {
3226 const layer = this.#allLayers.get(editor.pageIndex);
3227 if (layer) {
3228 layer.addOrRebuild(editor);
3229 } else {
3230 this.addEditor(editor);
3231 this.addToAnnotationStorage(editor);
3232 }
3233 }
3234 setActiveEditor(editor) {
3235 if (this.#activeEditor === editor) {
3236 return;
3237 }
3238 this.#activeEditor = editor;
3239 if (editor) {
3240 this.#dispatchUpdateUI(editor.propertiesToUpdate);
3241 }
3242 }
3243 get #lastSelectedEditor() {
3244 let ed = null;
3245 for (ed of this.#selectedEditors) {}
3246 return ed;
3247 }
3248 updateUI(editor) {
3249 if (this.#lastSelectedEditor === editor) {
3250 this.#dispatchUpdateUI(editor.propertiesToUpdate);
3251 }
3252 }
3253 toggleSelected(editor) {
3254 if (this.#selectedEditors.has(editor)) {
3255 this.#selectedEditors.delete(editor);
3256 editor.unselect();
3257 this.#dispatchUpdateStates({
3258 hasSelectedEditor: this.hasSelection
3259 });
3260 return;
3261 }
3262 this.#selectedEditors.add(editor);
3263 editor.select();
3264 this.#dispatchUpdateUI(editor.propertiesToUpdate);
3265 this.#dispatchUpdateStates({
3266 hasSelectedEditor: true
3267 });
3268 }
3269 setSelected(editor) {
3270 for (const ed of this.#selectedEditors) {
3271 if (ed !== editor) {
3272 ed.unselect();
3273 }
3274 }
3275 this.#selectedEditors.clear();
3276 this.#selectedEditors.add(editor);
3277 editor.select();
3278 this.#dispatchUpdateUI(editor.propertiesToUpdate);
3279 this.#dispatchUpdateStates({
3280 hasSelectedEditor: true
3281 });
3282 }
3283 isSelected(editor) {
3284 return this.#selectedEditors.has(editor);
3285 }
3286 get firstSelectedEditor() {
3287 return this.#selectedEditors.values().next().value;
3288 }
3289 unselect(editor) {
3290 editor.unselect();
3291 this.#selectedEditors.delete(editor);
3292 this.#dispatchUpdateStates({
3293 hasSelectedEditor: this.hasSelection
3294 });
3295 }
3296 get hasSelection() {
3297 return this.#selectedEditors.size !== 0;
3298 }
3299 get isEnterHandled() {
3300 return this.#selectedEditors.size === 1 && this.firstSelectedEditor.isEnterHandled;
3301 }
3302 undo() {
3303 this.#commandManager.undo();
3304 this.#dispatchUpdateStates({
3305 hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
3306 hasSomethingToRedo: true,
3307 isEmpty: this.#isEmpty()
3308 });
3309 }
3310 redo() {
3311 this.#commandManager.redo();
3312 this.#dispatchUpdateStates({
3313 hasSomethingToUndo: true,
3314 hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
3315 isEmpty: this.#isEmpty()
3316 });
3317 }
3318 addCommands(params) {
3319 this.#commandManager.add(params);
3320 this.#dispatchUpdateStates({
3321 hasSomethingToUndo: true,
3322 hasSomethingToRedo: false,
3323 isEmpty: this.#isEmpty()
3324 });
3325 }
3326 #isEmpty() {
3327 if (this.#allEditors.size === 0) {
3328 return true;
3329 }
3330 if (this.#allEditors.size === 1) {
3331 for (const editor of this.#allEditors.values()) {
3332 return editor.isEmpty();
3333 }
3334 }
3335 return false;
3336 }
3337 delete() {
3338 this.commitOrRemove();
3339 if (!this.hasSelection) {
3340 return;
3341 }
3342 const editors = [...this.#selectedEditors];
3343 const cmd = () => {
3344 for (const editor of editors) {
3345 editor.remove();
3346 }
3347 };
3348 const undo = () => {
3349 for (const editor of editors) {
3350 this.#addEditorToLayer(editor);
3351 }
3352 };
3353 this.addCommands({
3354 cmd,
3355 undo,
3356 mustExec: true
3357 });
3358 }
3359 commitOrRemove() {
3360 this.#activeEditor?.commitOrRemove();
3361 }
3362 hasSomethingToControl() {
3363 return this.#activeEditor || this.hasSelection;
3364 }
3365 #selectEditors(editors) {
3366 for (const editor of this.#selectedEditors) {
3367 editor.unselect();
3368 }
3369 this.#selectedEditors.clear();
3370 for (const editor of editors) {
3371 if (editor.isEmpty()) {
3372 continue;
3373 }
3374 this.#selectedEditors.add(editor);
3375 editor.select();
3376 }
3377 this.#dispatchUpdateStates({
3378 hasSelectedEditor: this.hasSelection
3379 });
3380 }
3381 selectAll() {
3382 for (const editor of this.#selectedEditors) {
3383 editor.commit();
3384 }
3385 this.#selectEditors(this.#allEditors.values());
3386 }
3387 unselectAll() {
3388 if (this.#activeEditor) {
3389 this.#activeEditor.commitOrRemove();
3390 if (this.#mode !== AnnotationEditorType.NONE) {
3391 return;
3392 }
3393 }
3394 if (!this.hasSelection) {
3395 return;
3396 }
3397 for (const editor of this.#selectedEditors) {
3398 editor.unselect();
3399 }
3400 this.#selectedEditors.clear();
3401 this.#dispatchUpdateStates({
3402 hasSelectedEditor: false
3403 });
3404 }
3405 translateSelectedEditors(x, y, noCommit = false) {
3406 if (!noCommit) {
3407 this.commitOrRemove();
3408 }
3409 if (!this.hasSelection) {
3410 return;
3411 }
3412 this.#translation[0] += x;
3413 this.#translation[1] += y;
3414 const [totalX, totalY] = this.#translation;
3415 const editors = [...this.#selectedEditors];
3416 const TIME_TO_WAIT = 1000;
3417 if (this.#translationTimeoutId) {
3418 clearTimeout(this.#translationTimeoutId);
3419 }
3420 this.#translationTimeoutId = setTimeout(() => {
3421 this.#translationTimeoutId = null;
3422 this.#translation[0] = this.#translation[1] = 0;
3423 this.addCommands({
3424 cmd: () => {
3425 for (const editor of editors) {
3426 if (this.#allEditors.has(editor.id)) {
3427 editor.translateInPage(totalX, totalY);
3428 }
3429 }
3430 },
3431 undo: () => {
3432 for (const editor of editors) {
3433 if (this.#allEditors.has(editor.id)) {
3434 editor.translateInPage(-totalX, -totalY);
3435 }
3436 }
3437 },
3438 mustExec: false
3439 });
3440 }, TIME_TO_WAIT);
3441 for (const editor of editors) {
3442 editor.translateInPage(x, y);
3443 }
3444 }
3445 setUpDragSession() {
3446 if (!this.hasSelection) {
3447 return;
3448 }
3449 this.disableUserSelect(true);
3450 this.#draggingEditors = new Map();
3451 for (const editor of this.#selectedEditors) {
3452 this.#draggingEditors.set(editor, {
3453 savedX: editor.x,
3454 savedY: editor.y,
3455 savedPageIndex: editor.pageIndex,
3456 newX: 0,
3457 newY: 0,
3458 newPageIndex: -1
3459 });
3460 }
3461 }
3462 endDragSession() {
3463 if (!this.#draggingEditors) {
3464 return false;
3465 }
3466 this.disableUserSelect(false);
3467 const map = this.#draggingEditors;
3468 this.#draggingEditors = null;
3469 let mustBeAddedInUndoStack = false;
3470 for (const [{
3471 x,
3472 y,
3473 pageIndex
3474 }, value] of map) {
3475 value.newX = x;
3476 value.newY = y;
3477 value.newPageIndex = pageIndex;
3478 mustBeAddedInUndoStack ||= x !== value.savedX || y !== value.savedY || pageIndex !== value.savedPageIndex;
3479 }
3480 if (!mustBeAddedInUndoStack) {
3481 return false;
3482 }
3483 const move = (editor, x, y, pageIndex) => {
3484 if (this.#allEditors.has(editor.id)) {
3485 const parent = this.#allLayers.get(pageIndex);
3486 if (parent) {
3487 editor._setParentAndPosition(parent, x, y);
3488 } else {
3489 editor.pageIndex = pageIndex;
3490 editor.x = x;
3491 editor.y = y;
3492 }
3493 }
3494 };
3495 this.addCommands({
3496 cmd: () => {
3497 for (const [editor, {
3498 newX,
3499 newY,
3500 newPageIndex
3501 }] of map) {
3502 move(editor, newX, newY, newPageIndex);
3503 }
3504 },
3505 undo: () => {
3506 for (const [editor, {
3507 savedX,
3508 savedY,
3509 savedPageIndex
3510 }] of map) {
3511 move(editor, savedX, savedY, savedPageIndex);
3512 }
3513 },
3514 mustExec: true
3515 });
3516 return true;
3517 }
3518 dragSelectedEditors(tx, ty) {
3519 if (!this.#draggingEditors) {
3520 return;
3521 }
3522 for (const editor of this.#draggingEditors.keys()) {
3523 editor.drag(tx, ty);
3524 }
3525 }
3526 rebuild(editor) {
3527 if (editor.parent === null) {
3528 const parent = this.getLayer(editor.pageIndex);
3529 if (parent) {
3530 parent.changeParent(editor);
3531 parent.addOrRebuild(editor);
3532 } else {
3533 this.addEditor(editor);
3534 this.addToAnnotationStorage(editor);
3535 editor.rebuild();
3536 }
3537 } else {
3538 editor.parent.addOrRebuild(editor);
3539 }
3540 }
3541 get isEditorHandlingKeyboard() {
3542 return this.getActive()?.shouldGetKeyboardEvents() || this.#selectedEditors.size === 1 && this.firstSelectedEditor.shouldGetKeyboardEvents();
3543 }
3544 isActive(editor) {
3545 return this.#activeEditor === editor;
3546 }
3547 getActive() {
3548 return this.#activeEditor;
3549 }
3550 getMode() {
3551 return this.#mode;
3552 }
3553 get imageManager() {
3554 return shadow(this, "imageManager", new ImageManager());
3555 }
3556 getSelectionBoxes(textLayer) {
3557 if (!textLayer) {
3558 return null;
3559 }
3560 const selection = document.getSelection();
3561 for (let i = 0, ii = selection.rangeCount; i < ii; i++) {
3562 if (!textLayer.contains(selection.getRangeAt(i).commonAncestorContainer)) {
3563 return null;
3564 }
3565 }
3566 const {
3567 x: layerX,
3568 y: layerY,
3569 width: parentWidth,
3570 height: parentHeight
3571 } = textLayer.getBoundingClientRect();
3572 let rotator;
3573 switch (textLayer.getAttribute("data-main-rotation")) {
3574 case "90":
3575 rotator = (x, y, w, h) => ({
3576 x: (y - layerY) / parentHeight,
3577 y: 1 - (x + w - layerX) / parentWidth,
3578 width: h / parentHeight,
3579 height: w / parentWidth
3580 });
3581 break;
3582 case "180":
3583 rotator = (x, y, w, h) => ({
3584 x: 1 - (x + w - layerX) / parentWidth,
3585 y: 1 - (y + h - layerY) / parentHeight,
3586 width: w / parentWidth,
3587 height: h / parentHeight
3588 });
3589 break;
3590 case "270":
3591 rotator = (x, y, w, h) => ({
3592 x: 1 - (y + h - layerY) / parentHeight,
3593 y: (x - layerX) / parentWidth,
3594 width: h / parentHeight,
3595 height: w / parentWidth
3596 });
3597 break;
3598 default:
3599 rotator = (x, y, w, h) => ({
3600 x: (x - layerX) / parentWidth,
3601 y: (y - layerY) / parentHeight,
3602 width: w / parentWidth,
3603 height: h / parentHeight
3604 });
3605 break;
3606 }
3607 const boxes = [];
3608 for (let i = 0, ii = selection.rangeCount; i < ii; i++) {
3609 const range = selection.getRangeAt(i);
3610 if (range.collapsed) {
3611 continue;
3612 }
3613 for (const {
3614 x,
3615 y,
3616 width,
3617 height
3618 } of range.getClientRects()) {
3619 if (width === 0 || height === 0) {
3620 continue;
3621 }
3622 boxes.push(rotator(x, y, width, height));
3623 }
3624 }
3625 return boxes.length === 0 ? null : boxes;
3626 }
3627 addChangedExistingAnnotation({
3628 annotationElementId,
3629 id
3630 }) {
3631 (this.#changedExistingAnnotations ||= new Map()).set(annotationElementId, id);
3632 }
3633 removeChangedExistingAnnotation({
3634 annotationElementId
3635 }) {
3636 this.#changedExistingAnnotations?.delete(annotationElementId);
3637 }
3638 renderAnnotationElement(annotation) {
3639 const editorId = this.#changedExistingAnnotations?.get(annotation.data.id);
3640 if (!editorId) {
3641 return;
3642 }
3643 const editor = this.#annotationStorage.getRawValue(editorId);
3644 if (!editor) {
3645 return;
3646 }
3647 if (this.#mode === AnnotationEditorType.NONE && !editor.hasBeenModified) {
3648 return;
3649 }
3650 editor.renderAnnotationElement(annotation);
3651 }
3652 }
3653
3654 ;// ./src/display/editor/alt_text.js
3655
3656 class AltText {
3657 #altText = null;
3658 #altTextDecorative = false;
3659 #altTextButton = null;
3660 #altTextTooltip = null;
3661 #altTextTooltipTimeout = null;
3662 #altTextWasFromKeyBoard = false;
3663 #badge = null;
3664 #editor = null;
3665 #guessedText = null;
3666 #textWithDisclaimer = null;
3667 #useNewAltTextFlow = false;
3668 static #l10nNewButton = null;
3669 static _l10nPromise = null;
3670 constructor(editor) {
3671 this.#editor = editor;
3672 this.#useNewAltTextFlow = editor._uiManager.useNewAltTextFlow;
3673 AltText.#l10nNewButton ||= Object.freeze({
3674 added: "pdfjs-editor-new-alt-text-added-button-label",
3675 missing: "pdfjs-editor-new-alt-text-missing-button-label",
3676 review: "pdfjs-editor-new-alt-text-to-review-button-label"
3677 });
3678 }
3679 static initialize(l10nPromise) {
3680 AltText._l10nPromise ||= l10nPromise;
3681 }
3682 async render() {
3683 const altText = this.#altTextButton = document.createElement("button");
3684 altText.className = "altText";
3685 let msg;
3686 if (this.#useNewAltTextFlow) {
3687 altText.classList.add("new");
3688 msg = await AltText._l10nPromise.get(AltText.#l10nNewButton.missing);
3689 } else {
3690 msg = await AltText._l10nPromise.get("pdfjs-editor-alt-text-button-label");
3691 }
3692 altText.textContent = msg;
3693 altText.setAttribute("aria-label", msg);
3694 altText.tabIndex = "0";
3695 const signal = this.#editor._uiManager._signal;
3696 altText.addEventListener("contextmenu", noContextMenu, {
3697 signal
3698 });
3699 altText.addEventListener("pointerdown", event => event.stopPropagation(), {
3700 signal
3701 });
3702 const onClick = event => {
3703 event.preventDefault();
3704 this.#editor._uiManager.editAltText(this.#editor);
3705 if (this.#useNewAltTextFlow) {
3706 this.#editor._reportTelemetry({
3707 action: "pdfjs.image.alt_text.image_status_label_clicked",
3708 data: {
3709 label: this.#label
3710 }
3711 });
3712 }
3713 };
3714 altText.addEventListener("click", onClick, {
3715 capture: true,
3716 signal
3717 });
3718 altText.addEventListener("keydown", event => {
3719 if (event.target === altText && event.key === "Enter") {
3720 this.#altTextWasFromKeyBoard = true;
3721 onClick(event);
3722 }
3723 }, {
3724 signal
3725 });
3726 await this.#setState();
3727 return altText;
3728 }
3729 get #label() {
3730 return this.#altText && "added" || this.#altText === null && this.guessedText && "review" || "missing";
3731 }
3732 finish() {
3733 if (!this.#altTextButton) {
3734 return;
3735 }
3736 this.#altTextButton.focus({
3737 focusVisible: this.#altTextWasFromKeyBoard
3738 });
3739 this.#altTextWasFromKeyBoard = false;
3740 }
3741 isEmpty() {
3742 if (this.#useNewAltTextFlow) {
3743 return this.#altText === null;
3744 }
3745 return !this.#altText && !this.#altTextDecorative;
3746 }
3747 hasData() {
3748 if (this.#useNewAltTextFlow) {
3749 return this.#altText !== null || !!this.#guessedText;
3750 }
3751 return this.isEmpty();
3752 }
3753 get guessedText() {
3754 return this.#guessedText;
3755 }
3756 async setGuessedText(guessedText) {
3757 if (this.#altText !== null) {
3758 return;
3759 }
3760 this.#guessedText = guessedText;
3761 this.#textWithDisclaimer = await AltText._l10nPromise.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer")({
3762 generatedAltText: guessedText
3763 });
3764 this.#setState();
3765 }
3766 toggleAltTextBadge(visibility = false) {
3767 if (!this.#useNewAltTextFlow || this.#altText) {
3768 this.#badge?.remove();
3769 this.#badge = null;
3770 return;
3771 }
3772 if (!this.#badge) {
3773 const badge = this.#badge = document.createElement("div");
3774 badge.className = "noAltTextBadge";
3775 this.#editor.div.append(badge);
3776 }
3777 this.#badge.classList.toggle("hidden", !visibility);
3778 }
3779 serialize(isForCopying) {
3780 let altText = this.#altText;
3781 if (!isForCopying && this.#guessedText === altText) {
3782 altText = this.#textWithDisclaimer;
3783 }
3784 return {
3785 altText,
3786 decorative: this.#altTextDecorative,
3787 guessedText: this.#guessedText,
3788 textWithDisclaimer: this.#textWithDisclaimer
3789 };
3790 }
3791 get data() {
3792 return {
3793 altText: this.#altText,
3794 decorative: this.#altTextDecorative
3795 };
3796 }
3797 set data({
3798 altText,
3799 decorative,
3800 guessedText,
3801 textWithDisclaimer,
3802 cancel = false
3803 }) {
3804 if (guessedText) {
3805 this.#guessedText = guessedText;
3806 this.#textWithDisclaimer = textWithDisclaimer;
3807 }
3808 if (this.#altText === altText && this.#altTextDecorative === decorative) {
3809 return;
3810 }
3811 if (!cancel) {
3812 this.#altText = altText;
3813 this.#altTextDecorative = decorative;
3814 }
3815 this.#setState();
3816 }
3817 toggle(enabled = false) {
3818 if (!this.#altTextButton) {
3819 return;
3820 }
3821 if (!enabled && this.#altTextTooltipTimeout) {
3822 clearTimeout(this.#altTextTooltipTimeout);
3823 this.#altTextTooltipTimeout = null;
3824 }
3825 this.#altTextButton.disabled = !enabled;
3826 }
3827 shown() {
3828 this.#editor._reportTelemetry({
3829 action: "pdfjs.image.alt_text.image_status_label_displayed",
3830 data: {
3831 label: this.#label
3832 }
3833 });
3834 }
3835 destroy() {
3836 this.#altTextButton?.remove();
3837 this.#altTextButton = null;
3838 this.#altTextTooltip = null;
3839 this.#badge?.remove();
3840 this.#badge = null;
3841 }
3842 async #setState() {
3843 const button = this.#altTextButton;
3844 if (!button) {
3845 return;
3846 }
3847 if (this.#useNewAltTextFlow) {
3848 button.classList.toggle("done", !!this.#altText);
3849 AltText._l10nPromise.get(AltText.#l10nNewButton[this.#label]).then(msg => {
3850 button.setAttribute("aria-label", msg);
3851 for (const child of button.childNodes) {
3852 if (child.nodeType === Node.TEXT_NODE) {
3853 child.textContent = msg;
3854 break;
3855 }
3856 }
3857 });
3858 if (!this.#altText) {
3859 this.#altTextTooltip?.remove();
3860 return;
3861 }
3862 } else {
3863 if (!this.#altText && !this.#altTextDecorative) {
3864 button.classList.remove("done");
3865 this.#altTextTooltip?.remove();
3866 return;
3867 }
3868 button.classList.add("done");
3869 AltText._l10nPromise.get("pdfjs-editor-alt-text-edit-button-label").then(msg => {
3870 button.setAttribute("aria-label", msg);
3871 });
3872 }
3873 let tooltip = this.#altTextTooltip;
3874 if (!tooltip) {
3875 this.#altTextTooltip = tooltip = document.createElement("span");
3876 tooltip.className = "tooltip";
3877 tooltip.setAttribute("role", "tooltip");
3878 tooltip.id = `alt-text-tooltip-${this.#editor.id}`;
3879 const DELAY_TO_SHOW_TOOLTIP = 100;
3880 const signal = this.#editor._uiManager._signal;
3881 signal.addEventListener("abort", () => {
3882 clearTimeout(this.#altTextTooltipTimeout);
3883 this.#altTextTooltipTimeout = null;
3884 }, {
3885 once: true
3886 });
3887 button.addEventListener("mouseenter", () => {
3888 this.#altTextTooltipTimeout = setTimeout(() => {
3889 this.#altTextTooltipTimeout = null;
3890 this.#altTextTooltip.classList.add("show");
3891 this.#editor._reportTelemetry({
3892 action: "alt_text_tooltip"
3893 });
3894 }, DELAY_TO_SHOW_TOOLTIP);
3895 }, {
3896 signal
3897 });
3898 button.addEventListener("mouseleave", () => {
3899 if (this.#altTextTooltipTimeout) {
3900 clearTimeout(this.#altTextTooltipTimeout);
3901 this.#altTextTooltipTimeout = null;
3902 }
3903 this.#altTextTooltip?.classList.remove("show");
3904 }, {
3905 signal
3906 });
3907 }
3908 tooltip.innerText = this.#altTextDecorative ? await AltText._l10nPromise.get("pdfjs-editor-alt-text-decorative-tooltip") : this.#altText;
3909 if (!tooltip.parentNode) {
3910 button.append(tooltip);
3911 }
3912 const element = this.#editor.getImageForAltText();
3913 element?.setAttribute("aria-describedby", tooltip.id);
3914 }
3915 }
3916
3917 ;// ./src/display/editor/editor.js
3918
3919
3920
3921
3922
3923 class AnnotationEditor {
3924 #accessibilityData = null;
3925 #allResizerDivs = null;
3926 #altText = null;
3927 #disabled = false;
3928 #keepAspectRatio = false;
3929 #resizersDiv = null;
3930 #savedDimensions = null;
3931 #focusAC = null;
3932 #focusedResizerName = "";
3933 #hasBeenClicked = false;
3934 #initialPosition = null;
3935 #isEditing = false;
3936 #isInEditMode = false;
3937 #isResizerEnabledForKeyboard = false;
3938 #moveInDOMTimeout = null;
3939 #prevDragX = 0;
3940 #prevDragY = 0;
3941 #telemetryTimeouts = null;
3942 _editToolbar = null;
3943 _initialOptions = Object.create(null);
3944 _initialData = null;
3945 _isVisible = true;
3946 _uiManager = null;
3947 _focusEventsAllowed = true;
3948 static _l10nPromise = null;
3949 static _l10nResizer = null;
3950 #isDraggable = false;
3951 #zIndex = AnnotationEditor._zIndex++;
3952 static _borderLineWidth = -1;
3953 static _colorManager = new ColorManager();
3954 static _zIndex = 1;
3955 static _telemetryTimeout = 1000;
3956 static get _resizerKeyboardManager() {
3957 const resize = AnnotationEditor.prototype._resizeWithKeyboard;
3958 const small = AnnotationEditorUIManager.TRANSLATE_SMALL;
3959 const big = AnnotationEditorUIManager.TRANSLATE_BIG;
3960 return shadow(this, "_resizerKeyboardManager", new KeyboardManager([[["ArrowLeft", "mac+ArrowLeft"], resize, {
3961 args: [-small, 0]
3962 }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], resize, {
3963 args: [-big, 0]
3964 }], [["ArrowRight", "mac+ArrowRight"], resize, {
3965 args: [small, 0]
3966 }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], resize, {
3967 args: [big, 0]
3968 }], [["ArrowUp", "mac+ArrowUp"], resize, {
3969 args: [0, -small]
3970 }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], resize, {
3971 args: [0, -big]
3972 }], [["ArrowDown", "mac+ArrowDown"], resize, {
3973 args: [0, small]
3974 }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], resize, {
3975 args: [0, big]
3976 }], [["Escape", "mac+Escape"], AnnotationEditor.prototype._stopResizingWithKeyboard]]));
3977 }
3978 constructor(parameters) {
3979 this.parent = parameters.parent;
3980 this.id = parameters.id;
3981 this.width = this.height = null;
3982 this.pageIndex = parameters.parent.pageIndex;
3983 this.name = parameters.name;
3984 this.div = null;
3985 this._uiManager = parameters.uiManager;
3986 this.annotationElementId = null;
3987 this._willKeepAspectRatio = false;
3988 this._initialOptions.isCentered = parameters.isCentered;
3989 this._structTreeParentId = null;
3990 const {
3991 rotation,
3992 rawDims: {
3993 pageWidth,
3994 pageHeight,
3995 pageX,
3996 pageY
3997 }
3998 } = this.parent.viewport;
3999 this.rotation = rotation;
4000 this.pageRotation = (360 + rotation - this._uiManager.viewParameters.rotation) % 360;
4001 this.pageDimensions = [pageWidth, pageHeight];
4002 this.pageTranslation = [pageX, pageY];
4003 const [width, height] = this.parentDimensions;
4004 this.x = parameters.x / width;
4005 this.y = parameters.y / height;
4006 this.isAttachedToDOM = false;
4007 this.deleted = false;
4008 }
4009 get editorType() {
4010 return Object.getPrototypeOf(this).constructor._type;
4011 }
4012 static get _defaultLineColor() {
4013 return shadow(this, "_defaultLineColor", this._colorManager.getHexCode("CanvasText"));
4014 }
4015 static deleteAnnotationElement(editor) {
4016 const fakeEditor = new FakeEditor({
4017 id: editor.parent.getNextId(),
4018 parent: editor.parent,
4019 uiManager: editor._uiManager
4020 });
4021 fakeEditor.annotationElementId = editor.annotationElementId;
4022 fakeEditor.deleted = true;
4023 fakeEditor._uiManager.addToAnnotationStorage(fakeEditor);
4024 }
4025 static initialize(l10n, _uiManager, options) {
4026 AnnotationEditor._l10nResizer ||= Object.freeze({
4027 topLeft: "pdfjs-editor-resizer-top-left",
4028 topMiddle: "pdfjs-editor-resizer-top-middle",
4029 topRight: "pdfjs-editor-resizer-top-right",
4030 middleRight: "pdfjs-editor-resizer-middle-right",
4031 bottomRight: "pdfjs-editor-resizer-bottom-right",
4032 bottomMiddle: "pdfjs-editor-resizer-bottom-middle",
4033 bottomLeft: "pdfjs-editor-resizer-bottom-left",
4034 middleLeft: "pdfjs-editor-resizer-middle-left"
4035 });
4036 AnnotationEditor._l10nPromise ||= new Map([...["pdfjs-editor-alt-text-button-label", "pdfjs-editor-alt-text-edit-button-label", "pdfjs-editor-alt-text-decorative-tooltip", "pdfjs-editor-new-alt-text-added-button-label", "pdfjs-editor-new-alt-text-missing-button-label", "pdfjs-editor-new-alt-text-to-review-button-label"].map(str => [str, l10n.get(str)]), ...["pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer"].map(str => [str, l10n.get.bind(l10n, str)])]);
4037 if (options?.strings) {
4038 for (const str of options.strings) {
4039 AnnotationEditor._l10nPromise.set(str, l10n.get(str));
4040 }
4041 }
4042 if (AnnotationEditor._borderLineWidth !== -1) {
4043 return;
4044 }
4045 const style = getComputedStyle(document.documentElement);
4046 AnnotationEditor._borderLineWidth = parseFloat(style.getPropertyValue("--outline-width")) || 0;
4047 }
4048 static updateDefaultParams(_type, _value) {}
4049 static get defaultPropertiesToUpdate() {
4050 return [];
4051 }
4052 static isHandlingMimeForPasting(mime) {
4053 return false;
4054 }
4055 static paste(item, parent) {
4056 unreachable("Not implemented");
4057 }
4058 get propertiesToUpdate() {
4059 return [];
4060 }
4061 get _isDraggable() {
4062 return this.#isDraggable;
4063 }
4064 set _isDraggable(value) {
4065 this.#isDraggable = value;
4066 this.div?.classList.toggle("draggable", value);
4067 }
4068 get isEnterHandled() {
4069 return true;
4070 }
4071 center() {
4072 const [pageWidth, pageHeight] = this.pageDimensions;
4073 switch (this.parentRotation) {
4074 case 90:
4075 this.x -= this.height * pageHeight / (pageWidth * 2);
4076 this.y += this.width * pageWidth / (pageHeight * 2);
4077 break;
4078 case 180:
4079 this.x += this.width / 2;
4080 this.y += this.height / 2;
4081 break;
4082 case 270:
4083 this.x += this.height * pageHeight / (pageWidth * 2);
4084 this.y -= this.width * pageWidth / (pageHeight * 2);
4085 break;
4086 default:
4087 this.x -= this.width / 2;
4088 this.y -= this.height / 2;
4089 break;
4090 }
4091 this.fixAndSetPosition();
4092 }
4093 addCommands(params) {
4094 this._uiManager.addCommands(params);
4095 }
4096 get currentLayer() {
4097 return this._uiManager.currentLayer;
4098 }
4099 setInBackground() {
4100 this.div.style.zIndex = 0;
4101 }
4102 setInForeground() {
4103 this.div.style.zIndex = this.#zIndex;
4104 }
4105 setParent(parent) {
4106 if (parent !== null) {
4107 this.pageIndex = parent.pageIndex;
4108 this.pageDimensions = parent.pageDimensions;
4109 } else {
4110 this.#stopResizing();
4111 }
4112 this.parent = parent;
4113 }
4114 focusin(event) {
4115 if (!this._focusEventsAllowed) {
4116 return;
4117 }
4118 if (!this.#hasBeenClicked) {
4119 this.parent.setSelected(this);
4120 } else {
4121 this.#hasBeenClicked = false;
4122 }
4123 }
4124 focusout(event) {
4125 if (!this._focusEventsAllowed) {
4126 return;
4127 }
4128 if (!this.isAttachedToDOM) {
4129 return;
4130 }
4131 const target = event.relatedTarget;
4132 if (target?.closest(`#${this.id}`)) {
4133 return;
4134 }
4135 event.preventDefault();
4136 if (!this.parent?.isMultipleSelection) {
4137 this.commitOrRemove();
4138 }
4139 }
4140 commitOrRemove() {
4141 if (this.isEmpty()) {
4142 this.remove();
4143 } else {
4144 this.commit();
4145 }
4146 }
4147 commit() {
4148 this.addToAnnotationStorage();
4149 }
4150 addToAnnotationStorage() {
4151 this._uiManager.addToAnnotationStorage(this);
4152 }
4153 setAt(x, y, tx, ty) {
4154 const [width, height] = this.parentDimensions;
4155 [tx, ty] = this.screenToPageTranslation(tx, ty);
4156 this.x = (x + tx) / width;
4157 this.y = (y + ty) / height;
4158 this.fixAndSetPosition();
4159 }
4160 #translate([width, height], x, y) {
4161 [x, y] = this.screenToPageTranslation(x, y);
4162 this.x += x / width;
4163 this.y += y / height;
4164 this.fixAndSetPosition();
4165 }
4166 translate(x, y) {
4167 this.#translate(this.parentDimensions, x, y);
4168 }
4169 translateInPage(x, y) {
4170 this.#initialPosition ||= [this.x, this.y];
4171 this.#translate(this.pageDimensions, x, y);
4172 this.div.scrollIntoView({
4173 block: "nearest"
4174 });
4175 }
4176 drag(tx, ty) {
4177 this.#initialPosition ||= [this.x, this.y];
4178 const [parentWidth, parentHeight] = this.parentDimensions;
4179 this.x += tx / parentWidth;
4180 this.y += ty / parentHeight;
4181 if (this.parent && (this.x < 0 || this.x > 1 || this.y < 0 || this.y > 1)) {
4182 const {
4183 x,
4184 y
4185 } = this.div.getBoundingClientRect();
4186 if (this.parent.findNewParent(this, x, y)) {
4187 this.x -= Math.floor(this.x);
4188 this.y -= Math.floor(this.y);
4189 }
4190 }
4191 let {
4192 x,
4193 y
4194 } = this;
4195 const [bx, by] = this.getBaseTranslation();
4196 x += bx;
4197 y += by;
4198 this.div.style.left = `${(100 * x).toFixed(2)}%`;
4199 this.div.style.top = `${(100 * y).toFixed(2)}%`;
4200 this.div.scrollIntoView({
4201 block: "nearest"
4202 });
4203 }
4204 get _hasBeenMoved() {
4205 return !!this.#initialPosition && (this.#initialPosition[0] !== this.x || this.#initialPosition[1] !== this.y);
4206 }
4207 getBaseTranslation() {
4208 const [parentWidth, parentHeight] = this.parentDimensions;
4209 const {
4210 _borderLineWidth
4211 } = AnnotationEditor;
4212 const x = _borderLineWidth / parentWidth;
4213 const y = _borderLineWidth / parentHeight;
4214 switch (this.rotation) {
4215 case 90:
4216 return [-x, y];
4217 case 180:
4218 return [x, y];
4219 case 270:
4220 return [x, -y];
4221 default:
4222 return [-x, -y];
4223 }
4224 }
4225 get _mustFixPosition() {
4226 return true;
4227 }
4228 fixAndSetPosition(rotation = this.rotation) {
4229 const [pageWidth, pageHeight] = this.pageDimensions;
4230 let {
4231 x,
4232 y,
4233 width,
4234 height
4235 } = this;
4236 width *= pageWidth;
4237 height *= pageHeight;
4238 x *= pageWidth;
4239 y *= pageHeight;
4240 if (this._mustFixPosition) {
4241 switch (rotation) {
4242 case 0:
4243 x = Math.max(0, Math.min(pageWidth - width, x));
4244 y = Math.max(0, Math.min(pageHeight - height, y));
4245 break;
4246 case 90:
4247 x = Math.max(0, Math.min(pageWidth - height, x));
4248 y = Math.min(pageHeight, Math.max(width, y));
4249 break;
4250 case 180:
4251 x = Math.min(pageWidth, Math.max(width, x));
4252 y = Math.min(pageHeight, Math.max(height, y));
4253 break;
4254 case 270:
4255 x = Math.min(pageWidth, Math.max(height, x));
4256 y = Math.max(0, Math.min(pageHeight - width, y));
4257 break;
4258 }
4259 }
4260 this.x = x /= pageWidth;
4261 this.y = y /= pageHeight;
4262 const [bx, by] = this.getBaseTranslation();
4263 x += bx;
4264 y += by;
4265 const {
4266 style
4267 } = this.div;
4268 style.left = `${(100 * x).toFixed(2)}%`;
4269 style.top = `${(100 * y).toFixed(2)}%`;
4270 this.moveInDOM();
4271 }
4272 static #rotatePoint(x, y, angle) {
4273 switch (angle) {
4274 case 90:
4275 return [y, -x];
4276 case 180:
4277 return [-x, -y];
4278 case 270:
4279 return [-y, x];
4280 default:
4281 return [x, y];
4282 }
4283 }
4284 screenToPageTranslation(x, y) {
4285 return AnnotationEditor.#rotatePoint(x, y, this.parentRotation);
4286 }
4287 pageTranslationToScreen(x, y) {
4288 return AnnotationEditor.#rotatePoint(x, y, 360 - this.parentRotation);
4289 }
4290 #getRotationMatrix(rotation) {
4291 switch (rotation) {
4292 case 90:
4293 {
4294 const [pageWidth, pageHeight] = this.pageDimensions;
4295 return [0, -pageWidth / pageHeight, pageHeight / pageWidth, 0];
4296 }
4297 case 180:
4298 return [-1, 0, 0, -1];
4299 case 270:
4300 {
4301 const [pageWidth, pageHeight] = this.pageDimensions;
4302 return [0, pageWidth / pageHeight, -pageHeight / pageWidth, 0];
4303 }
4304 default:
4305 return [1, 0, 0, 1];
4306 }
4307 }
4308 get parentScale() {
4309 return this._uiManager.viewParameters.realScale;
4310 }
4311 get parentRotation() {
4312 return (this._uiManager.viewParameters.rotation + this.pageRotation) % 360;
4313 }
4314 get parentDimensions() {
4315 const {
4316 parentScale,
4317 pageDimensions: [pageWidth, pageHeight]
4318 } = this;
4319 return [pageWidth * parentScale, pageHeight * parentScale];
4320 }
4321 setDims(width, height) {
4322 const [parentWidth, parentHeight] = this.parentDimensions;
4323 this.div.style.width = `${(100 * width / parentWidth).toFixed(2)}%`;
4324 if (!this.#keepAspectRatio) {
4325 this.div.style.height = `${(100 * height / parentHeight).toFixed(2)}%`;
4326 }
4327 }
4328 fixDims() {
4329 const {
4330 style
4331 } = this.div;
4332 const {
4333 height,
4334 width
4335 } = style;
4336 const widthPercent = width.endsWith("%");
4337 const heightPercent = !this.#keepAspectRatio && height.endsWith("%");
4338 if (widthPercent && heightPercent) {
4339 return;
4340 }
4341 const [parentWidth, parentHeight] = this.parentDimensions;
4342 if (!widthPercent) {
4343 style.width = `${(100 * parseFloat(width) / parentWidth).toFixed(2)}%`;
4344 }
4345 if (!this.#keepAspectRatio && !heightPercent) {
4346 style.height = `${(100 * parseFloat(height) / parentHeight).toFixed(2)}%`;
4347 }
4348 }
4349 getInitialTranslation() {
4350 return [0, 0];
4351 }
4352 #createResizers() {
4353 if (this.#resizersDiv) {
4354 return;
4355 }
4356 this.#resizersDiv = document.createElement("div");
4357 this.#resizersDiv.classList.add("resizers");
4358 const classes = this._willKeepAspectRatio ? ["topLeft", "topRight", "bottomRight", "bottomLeft"] : ["topLeft", "topMiddle", "topRight", "middleRight", "bottomRight", "bottomMiddle", "bottomLeft", "middleLeft"];
4359 const signal = this._uiManager._signal;
4360 for (const name of classes) {
4361 const div = document.createElement("div");
4362 this.#resizersDiv.append(div);
4363 div.classList.add("resizer", name);
4364 div.setAttribute("data-resizer-name", name);
4365 div.addEventListener("pointerdown", this.#resizerPointerdown.bind(this, name), {
4366 signal
4367 });
4368 div.addEventListener("contextmenu", noContextMenu, {
4369 signal
4370 });
4371 div.tabIndex = -1;
4372 }
4373 this.div.prepend(this.#resizersDiv);
4374 }
4375 #resizerPointerdown(name, event) {
4376 event.preventDefault();
4377 const {
4378 isMac
4379 } = util_FeatureTest.platform;
4380 if (event.button !== 0 || event.ctrlKey && isMac) {
4381 return;
4382 }
4383 this.#altText?.toggle(false);
4384 const savedDraggable = this._isDraggable;
4385 this._isDraggable = false;
4386 const ac = new AbortController();
4387 const signal = this._uiManager.combinedSignal(ac);
4388 this.parent.togglePointerEvents(false);
4389 window.addEventListener("pointermove", this.#resizerPointermove.bind(this, name), {
4390 passive: true,
4391 capture: true,
4392 signal
4393 });
4394 window.addEventListener("contextmenu", noContextMenu, {
4395 signal
4396 });
4397 const savedX = this.x;
4398 const savedY = this.y;
4399 const savedWidth = this.width;
4400 const savedHeight = this.height;
4401 const savedParentCursor = this.parent.div.style.cursor;
4402 const savedCursor = this.div.style.cursor;
4403 this.div.style.cursor = this.parent.div.style.cursor = window.getComputedStyle(event.target).cursor;
4404 const pointerUpCallback = () => {
4405 ac.abort();
4406 this.parent.togglePointerEvents(true);
4407 this.#altText?.toggle(true);
4408 this._isDraggable = savedDraggable;
4409 this.parent.div.style.cursor = savedParentCursor;
4410 this.div.style.cursor = savedCursor;
4411 this.#addResizeToUndoStack(savedX, savedY, savedWidth, savedHeight);
4412 };
4413 window.addEventListener("pointerup", pointerUpCallback, {
4414 signal
4415 });
4416 window.addEventListener("blur", pointerUpCallback, {
4417 signal
4418 });
4419 }
4420 #addResizeToUndoStack(savedX, savedY, savedWidth, savedHeight) {
4421 const newX = this.x;
4422 const newY = this.y;
4423 const newWidth = this.width;
4424 const newHeight = this.height;
4425 if (newX === savedX && newY === savedY && newWidth === savedWidth && newHeight === savedHeight) {
4426 return;
4427 }
4428 this.addCommands({
4429 cmd: () => {
4430 this.width = newWidth;
4431 this.height = newHeight;
4432 this.x = newX;
4433 this.y = newY;
4434 const [parentWidth, parentHeight] = this.parentDimensions;
4435 this.setDims(parentWidth * newWidth, parentHeight * newHeight);
4436 this.fixAndSetPosition();
4437 },
4438 undo: () => {
4439 this.width = savedWidth;
4440 this.height = savedHeight;
4441 this.x = savedX;
4442 this.y = savedY;
4443 const [parentWidth, parentHeight] = this.parentDimensions;
4444 this.setDims(parentWidth * savedWidth, parentHeight * savedHeight);
4445 this.fixAndSetPosition();
4446 },
4447 mustExec: true
4448 });
4449 }
4450 #resizerPointermove(name, event) {
4451 const [parentWidth, parentHeight] = this.parentDimensions;
4452 const savedX = this.x;
4453 const savedY = this.y;
4454 const savedWidth = this.width;
4455 const savedHeight = this.height;
4456 const minWidth = AnnotationEditor.MIN_SIZE / parentWidth;
4457 const minHeight = AnnotationEditor.MIN_SIZE / parentHeight;
4458 const round = x => Math.round(x * 10000) / 10000;
4459 const rotationMatrix = this.#getRotationMatrix(this.rotation);
4460 const transf = (x, y) => [rotationMatrix[0] * x + rotationMatrix[2] * y, rotationMatrix[1] * x + rotationMatrix[3] * y];
4461 const invRotationMatrix = this.#getRotationMatrix(360 - this.rotation);
4462 const invTransf = (x, y) => [invRotationMatrix[0] * x + invRotationMatrix[2] * y, invRotationMatrix[1] * x + invRotationMatrix[3] * y];
4463 let getPoint;
4464 let getOpposite;
4465 let isDiagonal = false;
4466 let isHorizontal = false;
4467 switch (name) {
4468 case "topLeft":
4469 isDiagonal = true;
4470 getPoint = (w, h) => [0, 0];
4471 getOpposite = (w, h) => [w, h];
4472 break;
4473 case "topMiddle":
4474 getPoint = (w, h) => [w / 2, 0];
4475 getOpposite = (w, h) => [w / 2, h];
4476 break;
4477 case "topRight":
4478 isDiagonal = true;
4479 getPoint = (w, h) => [w, 0];
4480 getOpposite = (w, h) => [0, h];
4481 break;
4482 case "middleRight":
4483 isHorizontal = true;
4484 getPoint = (w, h) => [w, h / 2];
4485 getOpposite = (w, h) => [0, h / 2];
4486 break;
4487 case "bottomRight":
4488 isDiagonal = true;
4489 getPoint = (w, h) => [w, h];
4490 getOpposite = (w, h) => [0, 0];
4491 break;
4492 case "bottomMiddle":
4493 getPoint = (w, h) => [w / 2, h];
4494 getOpposite = (w, h) => [w / 2, 0];
4495 break;
4496 case "bottomLeft":
4497 isDiagonal = true;
4498 getPoint = (w, h) => [0, h];
4499 getOpposite = (w, h) => [w, 0];
4500 break;
4501 case "middleLeft":
4502 isHorizontal = true;
4503 getPoint = (w, h) => [0, h / 2];
4504 getOpposite = (w, h) => [w, h / 2];
4505 break;
4506 }
4507 const point = getPoint(savedWidth, savedHeight);
4508 const oppositePoint = getOpposite(savedWidth, savedHeight);
4509 let transfOppositePoint = transf(...oppositePoint);
4510 const oppositeX = round(savedX + transfOppositePoint[0]);
4511 const oppositeY = round(savedY + transfOppositePoint[1]);
4512 let ratioX = 1;
4513 let ratioY = 1;
4514 let [deltaX, deltaY] = this.screenToPageTranslation(event.movementX, event.movementY);
4515 [deltaX, deltaY] = invTransf(deltaX / parentWidth, deltaY / parentHeight);
4516 if (isDiagonal) {
4517 const oldDiag = Math.hypot(savedWidth, savedHeight);
4518 ratioX = ratioY = Math.max(Math.min(Math.hypot(oppositePoint[0] - point[0] - deltaX, oppositePoint[1] - point[1] - deltaY) / oldDiag, 1 / savedWidth, 1 / savedHeight), minWidth / savedWidth, minHeight / savedHeight);
4519 } else if (isHorizontal) {
4520 ratioX = Math.max(minWidth, Math.min(1, Math.abs(oppositePoint[0] - point[0] - deltaX))) / savedWidth;
4521 } else {
4522 ratioY = Math.max(minHeight, Math.min(1, Math.abs(oppositePoint[1] - point[1] - deltaY))) / savedHeight;
4523 }
4524 const newWidth = round(savedWidth * ratioX);
4525 const newHeight = round(savedHeight * ratioY);
4526 transfOppositePoint = transf(...getOpposite(newWidth, newHeight));
4527 const newX = oppositeX - transfOppositePoint[0];
4528 const newY = oppositeY - transfOppositePoint[1];
4529 this.width = newWidth;
4530 this.height = newHeight;
4531 this.x = newX;
4532 this.y = newY;
4533 this.setDims(parentWidth * newWidth, parentHeight * newHeight);
4534 this.fixAndSetPosition();
4535 }
4536 altTextFinish() {
4537 this.#altText?.finish();
4538 }
4539 async addEditToolbar() {
4540 if (this._editToolbar || this.#isInEditMode) {
4541 return this._editToolbar;
4542 }
4543 this._editToolbar = new EditorToolbar(this);
4544 this.div.append(this._editToolbar.render());
4545 if (this.#altText) {
4546 await this._editToolbar.addAltText(this.#altText);
4547 }
4548 return this._editToolbar;
4549 }
4550 removeEditToolbar() {
4551 if (!this._editToolbar) {
4552 return;
4553 }
4554 this._editToolbar.remove();
4555 this._editToolbar = null;
4556 this.#altText?.destroy();
4557 }
4558 addContainer(container) {
4559 const editToolbarDiv = this._editToolbar?.div;
4560 if (editToolbarDiv) {
4561 editToolbarDiv.before(container);
4562 } else {
4563 this.div.append(container);
4564 }
4565 }
4566 getClientDimensions() {
4567 return this.div.getBoundingClientRect();
4568 }
4569 async addAltTextButton() {
4570 if (this.#altText) {
4571 return;
4572 }
4573 AltText.initialize(AnnotationEditor._l10nPromise);
4574 this.#altText = new AltText(this);
4575 if (this.#accessibilityData) {
4576 this.#altText.data = this.#accessibilityData;
4577 this.#accessibilityData = null;
4578 }
4579 await this.addEditToolbar();
4580 }
4581 get altTextData() {
4582 return this.#altText?.data;
4583 }
4584 set altTextData(data) {
4585 if (!this.#altText) {
4586 return;
4587 }
4588 this.#altText.data = data;
4589 }
4590 get guessedAltText() {
4591 return this.#altText?.guessedText;
4592 }
4593 async setGuessedAltText(text) {
4594 await this.#altText?.setGuessedText(text);
4595 }
4596 serializeAltText(isForCopying) {
4597 return this.#altText?.serialize(isForCopying);
4598 }
4599 hasAltText() {
4600 return !!this.#altText && !this.#altText.isEmpty();
4601 }
4602 hasAltTextData() {
4603 return this.#altText?.hasData() ?? false;
4604 }
4605 render() {
4606 this.div = document.createElement("div");
4607 this.div.setAttribute("data-editor-rotation", (360 - this.rotation) % 360);
4608 this.div.className = this.name;
4609 this.div.setAttribute("id", this.id);
4610 this.div.tabIndex = this.#disabled ? -1 : 0;
4611 if (!this._isVisible) {
4612 this.div.classList.add("hidden");
4613 }
4614 this.setInForeground();
4615 this.#addFocusListeners();
4616 const [parentWidth, parentHeight] = this.parentDimensions;
4617 if (this.parentRotation % 180 !== 0) {
4618 this.div.style.maxWidth = `${(100 * parentHeight / parentWidth).toFixed(2)}%`;
4619 this.div.style.maxHeight = `${(100 * parentWidth / parentHeight).toFixed(2)}%`;
4620 }
4621 const [tx, ty] = this.getInitialTranslation();
4622 this.translate(tx, ty);
4623 bindEvents(this, this.div, ["pointerdown"]);
4624 return this.div;
4625 }
4626 pointerdown(event) {
4627 const {
4628 isMac
4629 } = util_FeatureTest.platform;
4630 if (event.button !== 0 || event.ctrlKey && isMac) {
4631 event.preventDefault();
4632 return;
4633 }
4634 this.#hasBeenClicked = true;
4635 if (this._isDraggable) {
4636 this.#setUpDragSession(event);
4637 return;
4638 }
4639 this.#selectOnPointerEvent(event);
4640 }
4641 #selectOnPointerEvent(event) {
4642 const {
4643 isMac
4644 } = util_FeatureTest.platform;
4645 if (event.ctrlKey && !isMac || event.shiftKey || event.metaKey && isMac) {
4646 this.parent.toggleSelected(this);
4647 } else {
4648 this.parent.setSelected(this);
4649 }
4650 }
4651 #setUpDragSession(event) {
4652 const isSelected = this._uiManager.isSelected(this);
4653 this._uiManager.setUpDragSession();
4654 const ac = new AbortController();
4655 const signal = this._uiManager.combinedSignal(ac);
4656 if (isSelected) {
4657 this.div.classList.add("moving");
4658 this.#prevDragX = event.clientX;
4659 this.#prevDragY = event.clientY;
4660 const pointerMoveCallback = e => {
4661 const {
4662 clientX: x,
4663 clientY: y
4664 } = e;
4665 const [tx, ty] = this.screenToPageTranslation(x - this.#prevDragX, y - this.#prevDragY);
4666 this.#prevDragX = x;
4667 this.#prevDragY = y;
4668 this._uiManager.dragSelectedEditors(tx, ty);
4669 };
4670 window.addEventListener("pointermove", pointerMoveCallback, {
4671 passive: true,
4672 capture: true,
4673 signal
4674 });
4675 }
4676 const pointerUpCallback = () => {
4677 ac.abort();
4678 if (isSelected) {
4679 this.div.classList.remove("moving");
4680 }
4681 this.#hasBeenClicked = false;
4682 if (!this._uiManager.endDragSession()) {
4683 this.#selectOnPointerEvent(event);
4684 }
4685 };
4686 window.addEventListener("pointerup", pointerUpCallback, {
4687 signal
4688 });
4689 window.addEventListener("blur", pointerUpCallback, {
4690 signal
4691 });
4692 }
4693 moveInDOM() {
4694 if (this.#moveInDOMTimeout) {
4695 clearTimeout(this.#moveInDOMTimeout);
4696 }
4697 this.#moveInDOMTimeout = setTimeout(() => {
4698 this.#moveInDOMTimeout = null;
4699 this.parent?.moveEditorInDOM(this);
4700 }, 0);
4701 }
4702 _setParentAndPosition(parent, x, y) {
4703 parent.changeParent(this);
4704 this.x = x;
4705 this.y = y;
4706 this.fixAndSetPosition();
4707 }
4708 getRect(tx, ty, rotation = this.rotation) {
4709 const scale = this.parentScale;
4710 const [pageWidth, pageHeight] = this.pageDimensions;
4711 const [pageX, pageY] = this.pageTranslation;
4712 const shiftX = tx / scale;
4713 const shiftY = ty / scale;
4714 const x = this.x * pageWidth;
4715 const y = this.y * pageHeight;
4716 const width = this.width * pageWidth;
4717 const height = this.height * pageHeight;
4718 switch (rotation) {
4719 case 0:
4720 return [x + shiftX + pageX, pageHeight - y - shiftY - height + pageY, x + shiftX + width + pageX, pageHeight - y - shiftY + pageY];
4721 case 90:
4722 return [x + shiftY + pageX, pageHeight - y + shiftX + pageY, x + shiftY + height + pageX, pageHeight - y + shiftX + width + pageY];
4723 case 180:
4724 return [x - shiftX - width + pageX, pageHeight - y + shiftY + pageY, x - shiftX + pageX, pageHeight - y + shiftY + height + pageY];
4725 case 270:
4726 return [x - shiftY - height + pageX, pageHeight - y - shiftX - width + pageY, x - shiftY + pageX, pageHeight - y - shiftX + pageY];
4727 default:
4728 throw new Error("Invalid rotation");
4729 }
4730 }
4731 getRectInCurrentCoords(rect, pageHeight) {
4732 const [x1, y1, x2, y2] = rect;
4733 const width = x2 - x1;
4734 const height = y2 - y1;
4735 switch (this.rotation) {
4736 case 0:
4737 return [x1, pageHeight - y2, width, height];
4738 case 90:
4739 return [x1, pageHeight - y1, height, width];
4740 case 180:
4741 return [x2, pageHeight - y1, width, height];
4742 case 270:
4743 return [x2, pageHeight - y2, height, width];
4744 default:
4745 throw new Error("Invalid rotation");
4746 }
4747 }
4748 onceAdded() {}
4749 isEmpty() {
4750 return false;
4751 }
4752 enableEditMode() {
4753 this.#isInEditMode = true;
4754 }
4755 disableEditMode() {
4756 this.#isInEditMode = false;
4757 }
4758 isInEditMode() {
4759 return this.#isInEditMode;
4760 }
4761 shouldGetKeyboardEvents() {
4762 return this.#isResizerEnabledForKeyboard;
4763 }
4764 needsToBeRebuilt() {
4765 return this.div && !this.isAttachedToDOM;
4766 }
4767 #addFocusListeners() {
4768 if (this.#focusAC || !this.div) {
4769 return;
4770 }
4771 this.#focusAC = new AbortController();
4772 const signal = this._uiManager.combinedSignal(this.#focusAC);
4773 this.div.addEventListener("focusin", this.focusin.bind(this), {
4774 signal
4775 });
4776 this.div.addEventListener("focusout", this.focusout.bind(this), {
4777 signal
4778 });
4779 }
4780 rebuild() {
4781 this.#addFocusListeners();
4782 }
4783 rotate(_angle) {}
4784 serializeDeleted() {
4785 return {
4786 id: this.annotationElementId,
4787 deleted: true,
4788 pageIndex: this.pageIndex,
4789 popupRef: this._initialData?.popupRef || ""
4790 };
4791 }
4792 serialize(isForCopying = false, context = null) {
4793 unreachable("An editor must be serializable");
4794 }
4795 static async deserialize(data, parent, uiManager) {
4796 const editor = new this.prototype.constructor({
4797 parent,
4798 id: parent.getNextId(),
4799 uiManager
4800 });
4801 editor.rotation = data.rotation;
4802 editor.#accessibilityData = data.accessibilityData;
4803 const [pageWidth, pageHeight] = editor.pageDimensions;
4804 const [x, y, width, height] = editor.getRectInCurrentCoords(data.rect, pageHeight);
4805 editor.x = x / pageWidth;
4806 editor.y = y / pageHeight;
4807 editor.width = width / pageWidth;
4808 editor.height = height / pageHeight;
4809 return editor;
4810 }
4811 get hasBeenModified() {
4812 return !!this.annotationElementId && (this.deleted || this.serialize() !== null);
4813 }
4814 remove() {
4815 this.#focusAC?.abort();
4816 this.#focusAC = null;
4817 if (!this.isEmpty()) {
4818 this.commit();
4819 }
4820 if (this.parent) {
4821 this.parent.remove(this);
4822 } else {
4823 this._uiManager.removeEditor(this);
4824 }
4825 if (this.#moveInDOMTimeout) {
4826 clearTimeout(this.#moveInDOMTimeout);
4827 this.#moveInDOMTimeout = null;
4828 }
4829 this.#stopResizing();
4830 this.removeEditToolbar();
4831 if (this.#telemetryTimeouts) {
4832 for (const timeout of this.#telemetryTimeouts.values()) {
4833 clearTimeout(timeout);
4834 }
4835 this.#telemetryTimeouts = null;
4836 }
4837 this.parent = null;
4838 }
4839 get isResizable() {
4840 return false;
4841 }
4842 makeResizable() {
4843 if (this.isResizable) {
4844 this.#createResizers();
4845 this.#resizersDiv.classList.remove("hidden");
4846 bindEvents(this, this.div, ["keydown"]);
4847 }
4848 }
4849 get toolbarPosition() {
4850 return null;
4851 }
4852 keydown(event) {
4853 if (!this.isResizable || event.target !== this.div || event.key !== "Enter") {
4854 return;
4855 }
4856 this._uiManager.setSelected(this);
4857 this.#savedDimensions = {
4858 savedX: this.x,
4859 savedY: this.y,
4860 savedWidth: this.width,
4861 savedHeight: this.height
4862 };
4863 const children = this.#resizersDiv.children;
4864 if (!this.#allResizerDivs) {
4865 this.#allResizerDivs = Array.from(children);
4866 const boundResizerKeydown = this.#resizerKeydown.bind(this);
4867 const boundResizerBlur = this.#resizerBlur.bind(this);
4868 const signal = this._uiManager._signal;
4869 for (const div of this.#allResizerDivs) {
4870 const name = div.getAttribute("data-resizer-name");
4871 div.setAttribute("role", "spinbutton");
4872 div.addEventListener("keydown", boundResizerKeydown, {
4873 signal
4874 });
4875 div.addEventListener("blur", boundResizerBlur, {
4876 signal
4877 });
4878 div.addEventListener("focus", this.#resizerFocus.bind(this, name), {
4879 signal
4880 });
4881 div.setAttribute("data-l10n-id", AnnotationEditor._l10nResizer[name]);
4882 }
4883 }
4884 const first = this.#allResizerDivs[0];
4885 let firstPosition = 0;
4886 for (const div of children) {
4887 if (div === first) {
4888 break;
4889 }
4890 firstPosition++;
4891 }
4892 const nextFirstPosition = (360 - this.rotation + this.parentRotation) % 360 / 90 * (this.#allResizerDivs.length / 4);
4893 if (nextFirstPosition !== firstPosition) {
4894 if (nextFirstPosition < firstPosition) {
4895 for (let i = 0; i < firstPosition - nextFirstPosition; i++) {
4896 this.#resizersDiv.append(this.#resizersDiv.firstChild);
4897 }
4898 } else if (nextFirstPosition > firstPosition) {
4899 for (let i = 0; i < nextFirstPosition - firstPosition; i++) {
4900 this.#resizersDiv.firstChild.before(this.#resizersDiv.lastChild);
4901 }
4902 }
4903 let i = 0;
4904 for (const child of children) {
4905 const div = this.#allResizerDivs[i++];
4906 const name = div.getAttribute("data-resizer-name");
4907 child.setAttribute("data-l10n-id", AnnotationEditor._l10nResizer[name]);
4908 }
4909 }
4910 this.#setResizerTabIndex(0);
4911 this.#isResizerEnabledForKeyboard = true;
4912 this.#resizersDiv.firstChild.focus({
4913 focusVisible: true
4914 });
4915 event.preventDefault();
4916 event.stopImmediatePropagation();
4917 }
4918 #resizerKeydown(event) {
4919 AnnotationEditor._resizerKeyboardManager.exec(this, event);
4920 }
4921 #resizerBlur(event) {
4922 if (this.#isResizerEnabledForKeyboard && event.relatedTarget?.parentNode !== this.#resizersDiv) {
4923 this.#stopResizing();
4924 }
4925 }
4926 #resizerFocus(name) {
4927 this.#focusedResizerName = this.#isResizerEnabledForKeyboard ? name : "";
4928 }
4929 #setResizerTabIndex(value) {
4930 if (!this.#allResizerDivs) {
4931 return;
4932 }
4933 for (const div of this.#allResizerDivs) {
4934 div.tabIndex = value;
4935 }
4936 }
4937 _resizeWithKeyboard(x, y) {
4938 if (!this.#isResizerEnabledForKeyboard) {
4939 return;
4940 }
4941 this.#resizerPointermove(this.#focusedResizerName, {
4942 movementX: x,
4943 movementY: y
4944 });
4945 }
4946 #stopResizing() {
4947 this.#isResizerEnabledForKeyboard = false;
4948 this.#setResizerTabIndex(-1);
4949 if (this.#savedDimensions) {
4950 const {
4951 savedX,
4952 savedY,
4953 savedWidth,
4954 savedHeight
4955 } = this.#savedDimensions;
4956 this.#addResizeToUndoStack(savedX, savedY, savedWidth, savedHeight);
4957 this.#savedDimensions = null;
4958 }
4959 }
4960 _stopResizingWithKeyboard() {
4961 this.#stopResizing();
4962 this.div.focus();
4963 }
4964 select() {
4965 this.makeResizable();
4966 this.div?.classList.add("selectedEditor");
4967 if (!this._editToolbar) {
4968 this.addEditToolbar().then(() => {
4969 if (this.div?.classList.contains("selectedEditor")) {
4970 this._editToolbar?.show();
4971 }
4972 });
4973 return;
4974 }
4975 this._editToolbar?.show();
4976 this.#altText?.toggleAltTextBadge(false);
4977 }
4978 unselect() {
4979 this.#resizersDiv?.classList.add("hidden");
4980 this.div?.classList.remove("selectedEditor");
4981 if (this.div?.contains(document.activeElement)) {
4982 this._uiManager.currentLayer.div.focus({
4983 preventScroll: true
4984 });
4985 }
4986 this._editToolbar?.hide();
4987 this.#altText?.toggleAltTextBadge(true);
4988 }
4989 updateParams(type, value) {}
4990 disableEditing() {}
4991 enableEditing() {}
4992 enterInEditMode() {}
4993 getImageForAltText() {
4994 return null;
4995 }
4996 get contentDiv() {
4997 return this.div;
4998 }
4999 get isEditing() {
5000 return this.#isEditing;
5001 }
5002 set isEditing(value) {
5003 this.#isEditing = value;
5004 if (!this.parent) {
5005 return;
5006 }
5007 if (value) {
5008 this.parent.setSelected(this);
5009 this.parent.setActiveEditor(this);
5010 } else {
5011 this.parent.setActiveEditor(null);
5012 }
5013 }
5014 setAspectRatio(width, height) {
5015 this.#keepAspectRatio = true;
5016 const aspectRatio = width / height;
5017 const {
5018 style
5019 } = this.div;
5020 style.aspectRatio = aspectRatio;
5021 style.height = "auto";
5022 }
5023 static get MIN_SIZE() {
5024 return 16;
5025 }
5026 static canCreateNewEmptyEditor() {
5027 return true;
5028 }
5029 get telemetryInitialData() {
5030 return {
5031 action: "added"
5032 };
5033 }
5034 get telemetryFinalData() {
5035 return null;
5036 }
5037 _reportTelemetry(data, mustWait = false) {
5038 if (mustWait) {
5039 this.#telemetryTimeouts ||= new Map();
5040 const {
5041 action
5042 } = data;
5043 let timeout = this.#telemetryTimeouts.get(action);
5044 if (timeout) {
5045 clearTimeout(timeout);
5046 }
5047 timeout = setTimeout(() => {
5048 this._reportTelemetry(data);
5049 this.#telemetryTimeouts.delete(action);
5050 if (this.#telemetryTimeouts.size === 0) {
5051 this.#telemetryTimeouts = null;
5052 }
5053 }, AnnotationEditor._telemetryTimeout);
5054 this.#telemetryTimeouts.set(action, timeout);
5055 return;
5056 }
5057 data.type ||= this.editorType;
5058 this._uiManager._eventBus.dispatch("reporttelemetry", {
5059 source: this,
5060 details: {
5061 type: "editing",
5062 data
5063 }
5064 });
5065 }
5066 show(visible = this._isVisible) {
5067 this.div.classList.toggle("hidden", !visible);
5068 this._isVisible = visible;
5069 }
5070 enable() {
5071 if (this.div) {
5072 this.div.tabIndex = 0;
5073 }
5074 this.#disabled = false;
5075 }
5076 disable() {
5077 if (this.div) {
5078 this.div.tabIndex = -1;
5079 }
5080 this.#disabled = true;
5081 }
5082 renderAnnotationElement(annotation) {
5083 let content = annotation.container.querySelector(".annotationContent");
5084 if (!content) {
5085 content = document.createElement("div");
5086 content.classList.add("annotationContent", this.editorType);
5087 annotation.container.prepend(content);
5088 } else if (content.nodeName === "CANVAS") {
5089 const canvas = content;
5090 content = document.createElement("div");
5091 content.classList.add("annotationContent", this.editorType);
5092 canvas.before(content);
5093 }
5094 return content;
5095 }
5096 resetAnnotationElement(annotation) {
5097 const {
5098 firstChild
5099 } = annotation.container;
5100 if (firstChild?.nodeName === "DIV" && firstChild.classList.contains("annotationContent")) {
5101 firstChild.remove();
5102 }
5103 }
5104 }
5105 class FakeEditor extends AnnotationEditor {
5106 constructor(params) {
5107 super(params);
5108 this.annotationElementId = params.annotationElementId;
5109 this.deleted = true;
5110 }
5111 serialize() {
5112 return this.serializeDeleted();
5113 }
5114 }
5115
5116 ;// ./src/shared/murmurhash3.js
5117 const SEED = 0xc3d2e1f0;
5118 const MASK_HIGH = 0xffff0000;
5119 const MASK_LOW = 0xffff;
5120 class MurmurHash3_64 {
5121 constructor(seed) {
5122 this.h1 = seed ? seed & 0xffffffff : SEED;
5123 this.h2 = seed ? seed & 0xffffffff : SEED;
5124 }
5125 update(input) {
5126 let data, length;
5127 if (typeof input === "string") {
5128 data = new Uint8Array(input.length * 2);
5129 length = 0;
5130 for (let i = 0, ii = input.length; i < ii; i++) {
5131 const code = input.charCodeAt(i);
5132 if (code <= 0xff) {
5133 data[length++] = code;
5134 } else {
5135 data[length++] = code >>> 8;
5136 data[length++] = code & 0xff;
5137 }
5138 }
5139 } else if (ArrayBuffer.isView(input)) {
5140 data = input.slice();
5141 length = data.byteLength;
5142 } else {
5143 throw new Error("Invalid data format, must be a string or TypedArray.");
5144 }
5145 const blockCounts = length >> 2;
5146 const tailLength = length - blockCounts * 4;
5147 const dataUint32 = new Uint32Array(data.buffer, 0, blockCounts);
5148 let k1 = 0,
5149 k2 = 0;
5150 let h1 = this.h1,
5151 h2 = this.h2;
5152 const C1 = 0xcc9e2d51,
5153 C2 = 0x1b873593;
5154 const C1_LOW = C1 & MASK_LOW,
5155 C2_LOW = C2 & MASK_LOW;
5156 for (let i = 0; i < blockCounts; i++) {
5157 if (i & 1) {
5158 k1 = dataUint32[i];
5159 k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
5160 k1 = k1 << 15 | k1 >>> 17;
5161 k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
5162 h1 ^= k1;
5163 h1 = h1 << 13 | h1 >>> 19;
5164 h1 = h1 * 5 + 0xe6546b64;
5165 } else {
5166 k2 = dataUint32[i];
5167 k2 = k2 * C1 & MASK_HIGH | k2 * C1_LOW & MASK_LOW;
5168 k2 = k2 << 15 | k2 >>> 17;
5169 k2 = k2 * C2 & MASK_HIGH | k2 * C2_LOW & MASK_LOW;
5170 h2 ^= k2;
5171 h2 = h2 << 13 | h2 >>> 19;
5172 h2 = h2 * 5 + 0xe6546b64;
5173 }
5174 }
5175 k1 = 0;
5176 switch (tailLength) {
5177 case 3:
5178 k1 ^= data[blockCounts * 4 + 2] << 16;
5179 case 2:
5180 k1 ^= data[blockCounts * 4 + 1] << 8;
5181 case 1:
5182 k1 ^= data[blockCounts * 4];
5183 k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
5184 k1 = k1 << 15 | k1 >>> 17;
5185 k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
5186 if (blockCounts & 1) {
5187 h1 ^= k1;
5188 } else {
5189 h2 ^= k1;
5190 }
5191 }
5192 this.h1 = h1;
5193 this.h2 = h2;
5194 }
5195 hexdigest() {
5196 let h1 = this.h1,
5197 h2 = this.h2;
5198 h1 ^= h2 >>> 1;
5199 h1 = h1 * 0xed558ccd & MASK_HIGH | h1 * 0x8ccd & MASK_LOW;
5200 h2 = h2 * 0xff51afd7 & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xafd7ed55 & MASK_HIGH) >>> 16;
5201 h1 ^= h2 >>> 1;
5202 h1 = h1 * 0x1a85ec53 & MASK_HIGH | h1 * 0xec53 & MASK_LOW;
5203 h2 = h2 * 0xc4ceb9fe & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xb9fe1a85 & MASK_HIGH) >>> 16;
5204 h1 ^= h2 >>> 1;
5205 return (h1 >>> 0).toString(16).padStart(8, "0") + (h2 >>> 0).toString(16).padStart(8, "0");
5206 }
5207 }
5208
5209 ;// ./src/display/annotation_storage.js
5210
5211
5212
5213 const SerializableEmpty = Object.freeze({
5214 map: null,
5215 hash: "",
5216 transfer: undefined
5217 });
5218 class AnnotationStorage {
5219 #modified = false;
5220 #modifiedIds = null;
5221 #storage = new Map();
5222 constructor() {
5223 this.onSetModified = null;
5224 this.onResetModified = null;
5225 this.onAnnotationEditor = null;
5226 }
5227 getValue(key, defaultValue) {
5228 const value = this.#storage.get(key);
5229 if (value === undefined) {
5230 return defaultValue;
5231 }
5232 return Object.assign(defaultValue, value);
5233 }
5234 getRawValue(key) {
5235 return this.#storage.get(key);
5236 }
5237 remove(key) {
5238 this.#storage.delete(key);
5239 if (this.#storage.size === 0) {
5240 this.resetModified();
5241 }
5242 if (typeof this.onAnnotationEditor === "function") {
5243 for (const value of this.#storage.values()) {
5244 if (value instanceof AnnotationEditor) {
5245 return;
5246 }
5247 }
5248 this.onAnnotationEditor(null);
5249 }
5250 }
5251 setValue(key, value) {
5252 const obj = this.#storage.get(key);
5253 let modified = false;
5254 if (obj !== undefined) {
5255 for (const [entry, val] of Object.entries(value)) {
5256 if (obj[entry] !== val) {
5257 modified = true;
5258 obj[entry] = val;
5259 }
5260 }
5261 } else {
5262 modified = true;
5263 this.#storage.set(key, value);
5264 }
5265 if (modified) {
5266 this.#setModified();
5267 }
5268 if (value instanceof AnnotationEditor && typeof this.onAnnotationEditor === "function") {
5269 this.onAnnotationEditor(value.constructor._type);
5270 }
5271 }
5272 has(key) {
5273 return this.#storage.has(key);
5274 }
5275 getAll() {
5276 return this.#storage.size > 0 ? objectFromMap(this.#storage) : null;
5277 }
5278 setAll(obj) {
5279 for (const [key, val] of Object.entries(obj)) {
5280 this.setValue(key, val);
5281 }
5282 }
5283 get size() {
5284 return this.#storage.size;
5285 }
5286 #setModified() {
5287 if (!this.#modified) {
5288 this.#modified = true;
5289 if (typeof this.onSetModified === "function") {
5290 this.onSetModified();
5291 }
5292 }
5293 }
5294 resetModified() {
5295 if (this.#modified) {
5296 this.#modified = false;
5297 if (typeof this.onResetModified === "function") {
5298 this.onResetModified();
5299 }
5300 }
5301 }
5302 get print() {
5303 return new PrintAnnotationStorage(this);
5304 }
5305 get serializable() {
5306 if (this.#storage.size === 0) {
5307 return SerializableEmpty;
5308 }
5309 const map = new Map(),
5310 hash = new MurmurHash3_64(),
5311 transfer = [];
5312 const context = Object.create(null);
5313 let hasBitmap = false;
5314 for (const [key, val] of this.#storage) {
5315 const serialized = val instanceof AnnotationEditor ? val.serialize(false, context) : val;
5316 if (serialized) {
5317 map.set(key, serialized);
5318 hash.update(`${key}:${JSON.stringify(serialized)}`);
5319 hasBitmap ||= !!serialized.bitmap;
5320 }
5321 }
5322 if (hasBitmap) {
5323 for (const value of map.values()) {
5324 if (value.bitmap) {
5325 transfer.push(value.bitmap);
5326 }
5327 }
5328 }
5329 return map.size > 0 ? {
5330 map,
5331 hash: hash.hexdigest(),
5332 transfer
5333 } : SerializableEmpty;
5334 }
5335 get editorStats() {
5336 let stats = null;
5337 const typeToEditor = new Map();
5338 for (const value of this.#storage.values()) {
5339 if (!(value instanceof AnnotationEditor)) {
5340 continue;
5341 }
5342 const editorStats = value.telemetryFinalData;
5343 if (!editorStats) {
5344 continue;
5345 }
5346 const {
5347 type
5348 } = editorStats;
5349 if (!typeToEditor.has(type)) {
5350 typeToEditor.set(type, Object.getPrototypeOf(value).constructor);
5351 }
5352 stats ||= Object.create(null);
5353 const map = stats[type] ||= new Map();
5354 for (const [key, val] of Object.entries(editorStats)) {
5355 if (key === "type") {
5356 continue;
5357 }
5358 let counters = map.get(key);
5359 if (!counters) {
5360 counters = new Map();
5361 map.set(key, counters);
5362 }
5363 const count = counters.get(val) ?? 0;
5364 counters.set(val, count + 1);
5365 }
5366 }
5367 for (const [type, editor] of typeToEditor) {
5368 stats[type] = editor.computeTelemetryFinalData(stats[type]);
5369 }
5370 return stats;
5371 }
5372 resetModifiedIds() {
5373 this.#modifiedIds = null;
5374 }
5375 get modifiedIds() {
5376 if (this.#modifiedIds) {
5377 return this.#modifiedIds;
5378 }
5379 const ids = [];
5380 for (const value of this.#storage.values()) {
5381 if (!(value instanceof AnnotationEditor) || !value.annotationElementId || !value.serialize()) {
5382 continue;
5383 }
5384 ids.push(value.annotationElementId);
5385 }
5386 return this.#modifiedIds = {
5387 ids: new Set(ids),
5388 hash: ids.join(",")
5389 };
5390 }
5391 }
5392 class PrintAnnotationStorage extends AnnotationStorage {
5393 #serializable;
5394 constructor(parent) {
5395 super();
5396 const {
5397 map,
5398 hash,
5399 transfer
5400 } = parent.serializable;
5401 const clone = structuredClone(map, transfer ? {
5402 transfer
5403 } : null);
5404 this.#serializable = {
5405 map: clone,
5406 hash,
5407 transfer
5408 };
5409 }
5410 get print() {
5411 unreachable("Should not call PrintAnnotationStorage.print");
5412 }
5413 get serializable() {
5414 return this.#serializable;
5415 }
5416 get modifiedIds() {
5417 return shadow(this, "modifiedIds", {
5418 ids: new Set(),
5419 hash: ""
5420 });
5421 }
5422 }
5423
5424 ;// ./src/display/font_loader.js
5425
5426 class FontLoader {
5427 #systemFonts = new Set();
5428 constructor({
5429 ownerDocument = globalThis.document,
5430 styleElement = null
5431 }) {
5432 this._document = ownerDocument;
5433 this.nativeFontFaces = new Set();
5434 this.styleElement = null;
5435 this.loadingRequests = [];
5436 this.loadTestFontId = 0;
5437 }
5438 addNativeFontFace(nativeFontFace) {
5439 this.nativeFontFaces.add(nativeFontFace);
5440 this._document.fonts.add(nativeFontFace);
5441 }
5442 removeNativeFontFace(nativeFontFace) {
5443 this.nativeFontFaces.delete(nativeFontFace);
5444 this._document.fonts.delete(nativeFontFace);
5445 }
5446 insertRule(rule) {
5447 if (!this.styleElement) {
5448 this.styleElement = this._document.createElement("style");
5449 this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement);
5450 }
5451 const styleSheet = this.styleElement.sheet;
5452 styleSheet.insertRule(rule, styleSheet.cssRules.length);
5453 }
5454 clear() {
5455 for (const nativeFontFace of this.nativeFontFaces) {
5456 this._document.fonts.delete(nativeFontFace);
5457 }
5458 this.nativeFontFaces.clear();
5459 this.#systemFonts.clear();
5460 if (this.styleElement) {
5461 this.styleElement.remove();
5462 this.styleElement = null;
5463 }
5464 }
5465 async loadSystemFont({
5466 systemFontInfo: info,
5467 _inspectFont
5468 }) {
5469 if (!info || this.#systemFonts.has(info.loadedName)) {
5470 return;
5471 }
5472 assert(!this.disableFontFace, "loadSystemFont shouldn't be called when `disableFontFace` is set.");
5473 if (this.isFontLoadingAPISupported) {
5474 const {
5475 loadedName,
5476 src,
5477 style
5478 } = info;
5479 const fontFace = new FontFace(loadedName, src, style);
5480 this.addNativeFontFace(fontFace);
5481 try {
5482 await fontFace.load();
5483 this.#systemFonts.add(loadedName);
5484 _inspectFont?.(info);
5485 } catch {
5486 warn(`Cannot load system font: ${info.baseFontName}, installing it could help to improve PDF rendering.`);
5487 this.removeNativeFontFace(fontFace);
5488 }
5489 return;
5490 }
5491 unreachable("Not implemented: loadSystemFont without the Font Loading API.");
5492 }
5493 async bind(font) {
5494 if (font.attached || font.missingFile && !font.systemFontInfo) {
5495 return;
5496 }
5497 font.attached = true;
5498 if (font.systemFontInfo) {
5499 await this.loadSystemFont(font);
5500 return;
5501 }
5502 if (this.isFontLoadingAPISupported) {
5503 const nativeFontFace = font.createNativeFontFace();
5504 if (nativeFontFace) {
5505 this.addNativeFontFace(nativeFontFace);
5506 try {
5507 await nativeFontFace.loaded;
5508 } catch (ex) {
5509 warn(`Failed to load font '${nativeFontFace.family}': '${ex}'.`);
5510 font.disableFontFace = true;
5511 throw ex;
5512 }
5513 }
5514 return;
5515 }
5516 const rule = font.createFontFaceRule();
5517 if (rule) {
5518 this.insertRule(rule);
5519 if (this.isSyncFontLoadingSupported) {
5520 return;
5521 }
5522 await new Promise(resolve => {
5523 const request = this._queueLoadingCallback(resolve);
5524 this._prepareFontLoadEvent(font, request);
5525 });
5526 }
5527 }
5528 get isFontLoadingAPISupported() {
5529 const hasFonts = !!this._document?.fonts;
5530 return shadow(this, "isFontLoadingAPISupported", hasFonts);
5531 }
5532 get isSyncFontLoadingSupported() {
5533 let supported = false;
5534 if (isNodeJS) {
5535 supported = true;
5536 } else if (typeof navigator !== "undefined" && typeof navigator?.userAgent === "string" && /Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent)) {
5537 supported = true;
5538 }
5539 return shadow(this, "isSyncFontLoadingSupported", supported);
5540 }
5541 _queueLoadingCallback(callback) {
5542 function completeRequest() {
5543 assert(!request.done, "completeRequest() cannot be called twice.");
5544 request.done = true;
5545 while (loadingRequests.length > 0 && loadingRequests[0].done) {
5546 const otherRequest = loadingRequests.shift();
5547 setTimeout(otherRequest.callback, 0);
5548 }
5549 }
5550 const {
5551 loadingRequests
5552 } = this;
5553 const request = {
5554 done: false,
5555 complete: completeRequest,
5556 callback
5557 };
5558 loadingRequests.push(request);
5559 return request;
5560 }
5561 get _loadTestFont() {
5562 const testFont = atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQA" + "FQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAA" + "ALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgA" + "AAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1" + "AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD" + "6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACM" + "AooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4D" + "IP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAA" + "AAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUA" + "AQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgAB" + "AAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABY" + "AAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAA" + "AC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAA" + "AAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQAC" + "AQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3" + "Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTj" + "FQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");
5563 return shadow(this, "_loadTestFont", testFont);
5564 }
5565 _prepareFontLoadEvent(font, request) {
5566 function int32(data, offset) {
5567 return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff;
5568 }
5569 function spliceString(s, offset, remove, insert) {
5570 const chunk1 = s.substring(0, offset);
5571 const chunk2 = s.substring(offset + remove);
5572 return chunk1 + insert + chunk2;
5573 }
5574 let i, ii;
5575 const canvas = this._document.createElement("canvas");
5576 canvas.width = 1;
5577 canvas.height = 1;
5578 const ctx = canvas.getContext("2d");
5579 let called = 0;
5580 function isFontReady(name, callback) {
5581 if (++called > 30) {
5582 warn("Load test font never loaded.");
5583 callback();
5584 return;
5585 }
5586 ctx.font = "30px " + name;
5587 ctx.fillText(".", 0, 20);
5588 const imageData = ctx.getImageData(0, 0, 1, 1);
5589 if (imageData.data[3] > 0) {
5590 callback();
5591 return;
5592 }
5593 setTimeout(isFontReady.bind(null, name, callback));
5594 }
5595 const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`;
5596 let data = this._loadTestFont;
5597 const COMMENT_OFFSET = 976;
5598 data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId);
5599 const CFF_CHECKSUM_OFFSET = 16;
5600 const XXXX_VALUE = 0x58585858;
5601 let checksum = int32(data, CFF_CHECKSUM_OFFSET);
5602 for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
5603 checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0;
5604 }
5605 if (i < loadTestFontId.length) {
5606 checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i) | 0;
5607 }
5608 data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
5609 const url = `url(data:font/opentype;base64,${btoa(data)});`;
5610 const rule = `@font-face {font-family:"${loadTestFontId}";src:${url}}`;
5611 this.insertRule(rule);
5612 const div = this._document.createElement("div");
5613 div.style.visibility = "hidden";
5614 div.style.width = div.style.height = "10px";
5615 div.style.position = "absolute";
5616 div.style.top = div.style.left = "0px";
5617 for (const name of [font.loadedName, loadTestFontId]) {
5618 const span = this._document.createElement("span");
5619 span.textContent = "Hi";
5620 span.style.fontFamily = name;
5621 div.append(span);
5622 }
5623 this._document.body.append(div);
5624 isFontReady(loadTestFontId, () => {
5625 div.remove();
5626 request.complete();
5627 });
5628 }
5629 }
5630 class FontFaceObject {
5631 constructor(translatedData, {
5632 disableFontFace = false,
5633 inspectFont = null
5634 }) {
5635 this.compiledGlyphs = Object.create(null);
5636 for (const i in translatedData) {
5637 this[i] = translatedData[i];
5638 }
5639 this.disableFontFace = disableFontFace === true;
5640 this._inspectFont = inspectFont;
5641 }
5642 createNativeFontFace() {
5643 if (!this.data || this.disableFontFace) {
5644 return null;
5645 }
5646 let nativeFontFace;
5647 if (!this.cssFontInfo) {
5648 nativeFontFace = new FontFace(this.loadedName, this.data, {});
5649 } else {
5650 const css = {
5651 weight: this.cssFontInfo.fontWeight
5652 };
5653 if (this.cssFontInfo.italicAngle) {
5654 css.style = `oblique ${this.cssFontInfo.italicAngle}deg`;
5655 }
5656 nativeFontFace = new FontFace(this.cssFontInfo.fontFamily, this.data, css);
5657 }
5658 this._inspectFont?.(this);
5659 return nativeFontFace;
5660 }
5661 createFontFaceRule() {
5662 if (!this.data || this.disableFontFace) {
5663 return null;
5664 }
5665 const data = bytesToString(this.data);
5666 const url = `url(data:${this.mimetype};base64,${btoa(data)});`;
5667 let rule;
5668 if (!this.cssFontInfo) {
5669 rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`;
5670 } else {
5671 let css = `font-weight: ${this.cssFontInfo.fontWeight};`;
5672 if (this.cssFontInfo.italicAngle) {
5673 css += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`;
5674 }
5675 rule = `@font-face {font-family:"${this.cssFontInfo.fontFamily}";${css}src:${url}}`;
5676 }
5677 this._inspectFont?.(this, url);
5678 return rule;
5679 }
5680 getPathGenerator(objs, character) {
5681 if (this.compiledGlyphs[character] !== undefined) {
5682 return this.compiledGlyphs[character];
5683 }
5684 let cmds;
5685 try {
5686 cmds = objs.get(this.loadedName + "_path_" + character);
5687 } catch (ex) {
5688 warn(`getPathGenerator - ignoring character: "${ex}".`);
5689 }
5690 if (!Array.isArray(cmds) || cmds.length === 0) {
5691 return this.compiledGlyphs[character] = function (c, size) {};
5692 }
5693 const commands = [];
5694 for (let i = 0, ii = cmds.length; i < ii;) {
5695 switch (cmds[i++]) {
5696 case FontRenderOps.BEZIER_CURVE_TO:
5697 {
5698 const [a, b, c, d, e, f] = cmds.slice(i, i + 6);
5699 commands.push(ctx => ctx.bezierCurveTo(a, b, c, d, e, f));
5700 i += 6;
5701 }
5702 break;
5703 case FontRenderOps.MOVE_TO:
5704 {
5705 const [a, b] = cmds.slice(i, i + 2);
5706 commands.push(ctx => ctx.moveTo(a, b));
5707 i += 2;
5708 }
5709 break;
5710 case FontRenderOps.LINE_TO:
5711 {
5712 const [a, b] = cmds.slice(i, i + 2);
5713 commands.push(ctx => ctx.lineTo(a, b));
5714 i += 2;
5715 }
5716 break;
5717 case FontRenderOps.QUADRATIC_CURVE_TO:
5718 {
5719 const [a, b, c, d] = cmds.slice(i, i + 4);
5720 commands.push(ctx => ctx.quadraticCurveTo(a, b, c, d));
5721 i += 4;
5722 }
5723 break;
5724 case FontRenderOps.RESTORE:
5725 commands.push(ctx => ctx.restore());
5726 break;
5727 case FontRenderOps.SAVE:
5728 commands.push(ctx => ctx.save());
5729 break;
5730 case FontRenderOps.SCALE:
5731 assert(commands.length === 2, "Scale command is only valid at the third position.");
5732 break;
5733 case FontRenderOps.TRANSFORM:
5734 {
5735 const [a, b, c, d, e, f] = cmds.slice(i, i + 6);
5736 commands.push(ctx => ctx.transform(a, b, c, d, e, f));
5737 i += 6;
5738 }
5739 break;
5740 case FontRenderOps.TRANSLATE:
5741 {
5742 const [a, b] = cmds.slice(i, i + 2);
5743 commands.push(ctx => ctx.translate(a, b));
5744 i += 2;
5745 }
5746 break;
5747 }
5748 }
5749 return this.compiledGlyphs[character] = function glyphDrawer(ctx, size) {
5750 commands[0](ctx);
5751 commands[1](ctx);
5752 ctx.scale(size, -size);
5753 for (let i = 2, ii = commands.length; i < ii; i++) {
5754 commands[i](ctx);
5755 }
5756 };
5757 }
5758 }
5759
5760 ;// ./src/display/node_utils.js
5761
5762
5763 if (isNodeJS) {
5764 var packageCapability = Promise.withResolvers();
5765 var packageMap = null;
5766 const loadPackages = async () => {
5767 const fs = await import(/*webpackIgnore: true*/"fs"),
5768 http = await import(/*webpackIgnore: true*/"http"),
5769 https = await import(/*webpackIgnore: true*/"https"),
5770 url = await import(/*webpackIgnore: true*/"url");
5771 let canvas, path2d;
5772 return new Map(Object.entries({
5773 fs,
5774 http,
5775 https,
5776 url,
5777 canvas,
5778 path2d
5779 }));
5780 };
5781 loadPackages().then(map => {
5782 packageMap = map;
5783 packageCapability.resolve();
5784 }, reason => {
5785 warn(`loadPackages: ${reason}`);
5786 packageMap = new Map();
5787 packageCapability.resolve();
5788 });
5789 }
5790 class NodePackages {
5791 static get promise() {
5792 return packageCapability.promise;
5793 }
5794 static get(name) {
5795 return packageMap?.get(name);
5796 }
5797 }
5798 const node_utils_fetchData = function (url) {
5799 const fs = NodePackages.get("fs");
5800 return fs.promises.readFile(url).then(data => new Uint8Array(data));
5801 };
5802 class NodeFilterFactory extends BaseFilterFactory {}
5803 class NodeCanvasFactory extends BaseCanvasFactory {
5804 _createCanvas(width, height) {
5805 const canvas = NodePackages.get("canvas");
5806 return canvas.createCanvas(width, height);
5807 }
5808 }
5809 class NodeCMapReaderFactory extends BaseCMapReaderFactory {
5810 _fetchData(url, compressionType) {
5811 return node_utils_fetchData(url).then(data => ({
5812 cMapData: data,
5813 compressionType
5814 }));
5815 }
5816 }
5817 class NodeStandardFontDataFactory extends BaseStandardFontDataFactory {
5818 _fetchData(url) {
5819 return node_utils_fetchData(url);
5820 }
5821 }
5822
5823 ;// ./src/display/pattern_helper.js
5824
5825
5826 const PathType = {
5827 FILL: "Fill",
5828 STROKE: "Stroke",
5829 SHADING: "Shading"
5830 };
5831 function applyBoundingBox(ctx, bbox) {
5832 if (!bbox) {
5833 return;
5834 }
5835 const width = bbox[2] - bbox[0];
5836 const height = bbox[3] - bbox[1];
5837 const region = new Path2D();
5838 region.rect(bbox[0], bbox[1], width, height);
5839 ctx.clip(region);
5840 }
5841 class BaseShadingPattern {
5842 getPattern() {
5843 unreachable("Abstract method `getPattern` called.");
5844 }
5845 }
5846 class RadialAxialShadingPattern extends BaseShadingPattern {
5847 constructor(IR) {
5848 super();
5849 this._type = IR[1];
5850 this._bbox = IR[2];
5851 this._colorStops = IR[3];
5852 this._p0 = IR[4];
5853 this._p1 = IR[5];
5854 this._r0 = IR[6];
5855 this._r1 = IR[7];
5856 this.matrix = null;
5857 }
5858 _createGradient(ctx) {
5859 let grad;
5860 if (this._type === "axial") {
5861 grad = ctx.createLinearGradient(this._p0[0], this._p0[1], this._p1[0], this._p1[1]);
5862 } else if (this._type === "radial") {
5863 grad = ctx.createRadialGradient(this._p0[0], this._p0[1], this._r0, this._p1[0], this._p1[1], this._r1);
5864 }
5865 for (const colorStop of this._colorStops) {
5866 grad.addColorStop(colorStop[0], colorStop[1]);
5867 }
5868 return grad;
5869 }
5870 getPattern(ctx, owner, inverse, pathType) {
5871 let pattern;
5872 if (pathType === PathType.STROKE || pathType === PathType.FILL) {
5873 const ownerBBox = owner.current.getClippedPathBoundingBox(pathType, getCurrentTransform(ctx)) || [0, 0, 0, 0];
5874 const width = Math.ceil(ownerBBox[2] - ownerBBox[0]) || 1;
5875 const height = Math.ceil(ownerBBox[3] - ownerBBox[1]) || 1;
5876 const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", width, height);
5877 const tmpCtx = tmpCanvas.context;
5878 tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
5879 tmpCtx.beginPath();
5880 tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
5881 tmpCtx.translate(-ownerBBox[0], -ownerBBox[1]);
5882 inverse = Util.transform(inverse, [1, 0, 0, 1, ownerBBox[0], ownerBBox[1]]);
5883 tmpCtx.transform(...owner.baseTransform);
5884 if (this.matrix) {
5885 tmpCtx.transform(...this.matrix);
5886 }
5887 applyBoundingBox(tmpCtx, this._bbox);
5888 tmpCtx.fillStyle = this._createGradient(tmpCtx);
5889 tmpCtx.fill();
5890 pattern = ctx.createPattern(tmpCanvas.canvas, "no-repeat");
5891 const domMatrix = new DOMMatrix(inverse);
5892 pattern.setTransform(domMatrix);
5893 } else {
5894 applyBoundingBox(ctx, this._bbox);
5895 pattern = this._createGradient(ctx);
5896 }
5897 return pattern;
5898 }
5899 }
5900 function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
5901 const coords = context.coords,
5902 colors = context.colors;
5903 const bytes = data.data,
5904 rowSize = data.width * 4;
5905 let tmp;
5906 if (coords[p1 + 1] > coords[p2 + 1]) {
5907 tmp = p1;
5908 p1 = p2;
5909 p2 = tmp;
5910 tmp = c1;
5911 c1 = c2;
5912 c2 = tmp;
5913 }
5914 if (coords[p2 + 1] > coords[p3 + 1]) {
5915 tmp = p2;
5916 p2 = p3;
5917 p3 = tmp;
5918 tmp = c2;
5919 c2 = c3;
5920 c3 = tmp;
5921 }
5922 if (coords[p1 + 1] > coords[p2 + 1]) {
5923 tmp = p1;
5924 p1 = p2;
5925 p2 = tmp;
5926 tmp = c1;
5927 c1 = c2;
5928 c2 = tmp;
5929 }
5930 const x1 = (coords[p1] + context.offsetX) * context.scaleX;
5931 const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
5932 const x2 = (coords[p2] + context.offsetX) * context.scaleX;
5933 const y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
5934 const x3 = (coords[p3] + context.offsetX) * context.scaleX;
5935 const y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
5936 if (y1 >= y3) {
5937 return;
5938 }
5939 const c1r = colors[c1],
5940 c1g = colors[c1 + 1],
5941 c1b = colors[c1 + 2];
5942 const c2r = colors[c2],
5943 c2g = colors[c2 + 1],
5944 c2b = colors[c2 + 2];
5945 const c3r = colors[c3],
5946 c3g = colors[c3 + 1],
5947 c3b = colors[c3 + 2];
5948 const minY = Math.round(y1),
5949 maxY = Math.round(y3);
5950 let xa, car, cag, cab;
5951 let xb, cbr, cbg, cbb;
5952 for (let y = minY; y <= maxY; y++) {
5953 if (y < y2) {
5954 const k = y < y1 ? 0 : (y1 - y) / (y1 - y2);
5955 xa = x1 - (x1 - x2) * k;
5956 car = c1r - (c1r - c2r) * k;
5957 cag = c1g - (c1g - c2g) * k;
5958 cab = c1b - (c1b - c2b) * k;
5959 } else {
5960 let k;
5961 if (y > y3) {
5962 k = 1;
5963 } else if (y2 === y3) {
5964 k = 0;
5965 } else {
5966 k = (y2 - y) / (y2 - y3);
5967 }
5968 xa = x2 - (x2 - x3) * k;
5969 car = c2r - (c2r - c3r) * k;
5970 cag = c2g - (c2g - c3g) * k;
5971 cab = c2b - (c2b - c3b) * k;
5972 }
5973 let k;
5974 if (y < y1) {
5975 k = 0;
5976 } else if (y > y3) {
5977 k = 1;
5978 } else {
5979 k = (y1 - y) / (y1 - y3);
5980 }
5981 xb = x1 - (x1 - x3) * k;
5982 cbr = c1r - (c1r - c3r) * k;
5983 cbg = c1g - (c1g - c3g) * k;
5984 cbb = c1b - (c1b - c3b) * k;
5985 const x1_ = Math.round(Math.min(xa, xb));
5986 const x2_ = Math.round(Math.max(xa, xb));
5987 let j = rowSize * y + x1_ * 4;
5988 for (let x = x1_; x <= x2_; x++) {
5989 k = (xa - x) / (xa - xb);
5990 if (k < 0) {
5991 k = 0;
5992 } else if (k > 1) {
5993 k = 1;
5994 }
5995 bytes[j++] = car - (car - cbr) * k | 0;
5996 bytes[j++] = cag - (cag - cbg) * k | 0;
5997 bytes[j++] = cab - (cab - cbb) * k | 0;
5998 bytes[j++] = 255;
5999 }
6000 }
6001 }
6002 function drawFigure(data, figure, context) {
6003 const ps = figure.coords;
6004 const cs = figure.colors;
6005 let i, ii;
6006 switch (figure.type) {
6007 case "lattice":
6008 const verticesPerRow = figure.verticesPerRow;
6009 const rows = Math.floor(ps.length / verticesPerRow) - 1;
6010 const cols = verticesPerRow - 1;
6011 for (i = 0; i < rows; i++) {
6012 let q = i * verticesPerRow;
6013 for (let j = 0; j < cols; j++, q++) {
6014 drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]);
6015 drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
6016 }
6017 }
6018 break;
6019 case "triangles":
6020 for (i = 0, ii = ps.length; i < ii; i += 3) {
6021 drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]);
6022 }
6023 break;
6024 default:
6025 throw new Error("illegal figure");
6026 }
6027 }
6028 class MeshShadingPattern extends BaseShadingPattern {
6029 constructor(IR) {
6030 super();
6031 this._coords = IR[2];
6032 this._colors = IR[3];
6033 this._figures = IR[4];
6034 this._bounds = IR[5];
6035 this._bbox = IR[7];
6036 this._background = IR[8];
6037 this.matrix = null;
6038 }
6039 _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) {
6040 const EXPECTED_SCALE = 1.1;
6041 const MAX_PATTERN_SIZE = 3000;
6042 const BORDER_SIZE = 2;
6043 const offsetX = Math.floor(this._bounds[0]);
6044 const offsetY = Math.floor(this._bounds[1]);
6045 const boundsWidth = Math.ceil(this._bounds[2]) - offsetX;
6046 const boundsHeight = Math.ceil(this._bounds[3]) - offsetY;
6047 const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
6048 const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
6049 const scaleX = boundsWidth / width;
6050 const scaleY = boundsHeight / height;
6051 const context = {
6052 coords: this._coords,
6053 colors: this._colors,
6054 offsetX: -offsetX,
6055 offsetY: -offsetY,
6056 scaleX: 1 / scaleX,
6057 scaleY: 1 / scaleY
6058 };
6059 const paddedWidth = width + BORDER_SIZE * 2;
6060 const paddedHeight = height + BORDER_SIZE * 2;
6061 const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight);
6062 const tmpCtx = tmpCanvas.context;
6063 const data = tmpCtx.createImageData(width, height);
6064 if (backgroundColor) {
6065 const bytes = data.data;
6066 for (let i = 0, ii = bytes.length; i < ii; i += 4) {
6067 bytes[i] = backgroundColor[0];
6068 bytes[i + 1] = backgroundColor[1];
6069 bytes[i + 2] = backgroundColor[2];
6070 bytes[i + 3] = 255;
6071 }
6072 }
6073 for (const figure of this._figures) {
6074 drawFigure(data, figure, context);
6075 }
6076 tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
6077 const canvas = tmpCanvas.canvas;
6078 return {
6079 canvas,
6080 offsetX: offsetX - BORDER_SIZE * scaleX,
6081 offsetY: offsetY - BORDER_SIZE * scaleY,
6082 scaleX,
6083 scaleY
6084 };
6085 }
6086 getPattern(ctx, owner, inverse, pathType) {
6087 applyBoundingBox(ctx, this._bbox);
6088 let scale;
6089 if (pathType === PathType.SHADING) {
6090 scale = Util.singularValueDecompose2dScale(getCurrentTransform(ctx));
6091 } else {
6092 scale = Util.singularValueDecompose2dScale(owner.baseTransform);
6093 if (this.matrix) {
6094 const matrixScale = Util.singularValueDecompose2dScale(this.matrix);
6095 scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]];
6096 }
6097 }
6098 const temporaryPatternCanvas = this._createMeshCanvas(scale, pathType === PathType.SHADING ? null : this._background, owner.cachedCanvases);
6099 if (pathType !== PathType.SHADING) {
6100 ctx.setTransform(...owner.baseTransform);
6101 if (this.matrix) {
6102 ctx.transform(...this.matrix);
6103 }
6104 }
6105 ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
6106 ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
6107 return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat");
6108 }
6109 }
6110 class DummyShadingPattern extends BaseShadingPattern {
6111 getPattern() {
6112 return "hotpink";
6113 }
6114 }
6115 function getShadingPattern(IR) {
6116 switch (IR[0]) {
6117 case "RadialAxial":
6118 return new RadialAxialShadingPattern(IR);
6119 case "Mesh":
6120 return new MeshShadingPattern(IR);
6121 case "Dummy":
6122 return new DummyShadingPattern();
6123 }
6124 throw new Error(`Unknown IR type: ${IR[0]}`);
6125 }
6126 const PaintType = {
6127 COLORED: 1,
6128 UNCOLORED: 2
6129 };
6130 class TilingPattern {
6131 static MAX_PATTERN_SIZE = 3000;
6132 constructor(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
6133 this.operatorList = IR[2];
6134 this.matrix = IR[3];
6135 this.bbox = IR[4];
6136 this.xstep = IR[5];
6137 this.ystep = IR[6];
6138 this.paintType = IR[7];
6139 this.tilingType = IR[8];
6140 this.color = color;
6141 this.ctx = ctx;
6142 this.canvasGraphicsFactory = canvasGraphicsFactory;
6143 this.baseTransform = baseTransform;
6144 }
6145 createPatternCanvas(owner) {
6146 const {
6147 bbox,
6148 operatorList,
6149 paintType,
6150 tilingType,
6151 color,
6152 canvasGraphicsFactory
6153 } = this;
6154 let {
6155 xstep,
6156 ystep
6157 } = this;
6158 xstep = Math.abs(xstep);
6159 ystep = Math.abs(ystep);
6160 info("TilingType: " + tilingType);
6161 const x0 = bbox[0],
6162 y0 = bbox[1],
6163 x1 = bbox[2],
6164 y1 = bbox[3];
6165 const width = x1 - x0;
6166 const height = y1 - y0;
6167 const matrixScale = Util.singularValueDecompose2dScale(this.matrix);
6168 const curMatrixScale = Util.singularValueDecompose2dScale(this.baseTransform);
6169 const combinedScaleX = matrixScale[0] * curMatrixScale[0];
6170 const combinedScaleY = matrixScale[1] * curMatrixScale[1];
6171 let canvasWidth = width,
6172 canvasHeight = height,
6173 redrawHorizontally = false,
6174 redrawVertically = false;
6175 const xScaledStep = Math.ceil(xstep * combinedScaleX);
6176 const yScaledStep = Math.ceil(ystep * combinedScaleY);
6177 const xScaledWidth = Math.ceil(width * combinedScaleX);
6178 const yScaledHeight = Math.ceil(height * combinedScaleY);
6179 if (xScaledStep >= xScaledWidth) {
6180 canvasWidth = xstep;
6181 } else {
6182 redrawHorizontally = true;
6183 }
6184 if (yScaledStep >= yScaledHeight) {
6185 canvasHeight = ystep;
6186 } else {
6187 redrawVertically = true;
6188 }
6189 const dimx = this.getSizeAndScale(canvasWidth, this.ctx.canvas.width, combinedScaleX);
6190 const dimy = this.getSizeAndScale(canvasHeight, this.ctx.canvas.height, combinedScaleY);
6191 const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size);
6192 const tmpCtx = tmpCanvas.context;
6193 const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
6194 graphics.groupLevel = owner.groupLevel;
6195 this.setFillAndStrokeStyleToContext(graphics, paintType, color);
6196 tmpCtx.translate(-dimx.scale * x0, -dimy.scale * y0);
6197 graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0);
6198 tmpCtx.save();
6199 this.clipBbox(graphics, x0, y0, x1, y1);
6200 graphics.baseTransform = getCurrentTransform(graphics.ctx);
6201 graphics.executeOperatorList(operatorList);
6202 graphics.endDrawing();
6203 tmpCtx.restore();
6204 if (redrawHorizontally || redrawVertically) {
6205 const image = tmpCanvas.canvas;
6206 if (redrawHorizontally) {
6207 canvasWidth = xstep;
6208 }
6209 if (redrawVertically) {
6210 canvasHeight = ystep;
6211 }
6212 const dimx2 = this.getSizeAndScale(canvasWidth, this.ctx.canvas.width, combinedScaleX);
6213 const dimy2 = this.getSizeAndScale(canvasHeight, this.ctx.canvas.height, combinedScaleY);
6214 const xSize = dimx2.size;
6215 const ySize = dimy2.size;
6216 const tmpCanvas2 = owner.cachedCanvases.getCanvas("pattern-workaround", xSize, ySize);
6217 const tmpCtx2 = tmpCanvas2.context;
6218 const ii = redrawHorizontally ? Math.floor(width / xstep) : 0;
6219 const jj = redrawVertically ? Math.floor(height / ystep) : 0;
6220 for (let i = 0; i <= ii; i++) {
6221 for (let j = 0; j <= jj; j++) {
6222 tmpCtx2.drawImage(image, xSize * i, ySize * j, xSize, ySize, 0, 0, xSize, ySize);
6223 }
6224 }
6225 return {
6226 canvas: tmpCanvas2.canvas,
6227 scaleX: dimx2.scale,
6228 scaleY: dimy2.scale,
6229 offsetX: x0,
6230 offsetY: y0
6231 };
6232 }
6233 return {
6234 canvas: tmpCanvas.canvas,
6235 scaleX: dimx.scale,
6236 scaleY: dimy.scale,
6237 offsetX: x0,
6238 offsetY: y0
6239 };
6240 }
6241 getSizeAndScale(step, realOutputSize, scale) {
6242 const maxSize = Math.max(TilingPattern.MAX_PATTERN_SIZE, realOutputSize);
6243 let size = Math.ceil(step * scale);
6244 if (size >= maxSize) {
6245 size = maxSize;
6246 } else {
6247 scale = size / step;
6248 }
6249 return {
6250 scale,
6251 size
6252 };
6253 }
6254 clipBbox(graphics, x0, y0, x1, y1) {
6255 const bboxWidth = x1 - x0;
6256 const bboxHeight = y1 - y0;
6257 graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
6258 graphics.current.updateRectMinMax(getCurrentTransform(graphics.ctx), [x0, y0, x1, y1]);
6259 graphics.clip();
6260 graphics.endPath();
6261 }
6262 setFillAndStrokeStyleToContext(graphics, paintType, color) {
6263 const context = graphics.ctx,
6264 current = graphics.current;
6265 switch (paintType) {
6266 case PaintType.COLORED:
6267 const ctx = this.ctx;
6268 context.fillStyle = ctx.fillStyle;
6269 context.strokeStyle = ctx.strokeStyle;
6270 current.fillColor = ctx.fillStyle;
6271 current.strokeColor = ctx.strokeStyle;
6272 break;
6273 case PaintType.UNCOLORED:
6274 const cssColor = Util.makeHexColor(color[0], color[1], color[2]);
6275 context.fillStyle = cssColor;
6276 context.strokeStyle = cssColor;
6277 current.fillColor = cssColor;
6278 current.strokeColor = cssColor;
6279 break;
6280 default:
6281 throw new FormatError(`Unsupported paint type: ${paintType}`);
6282 }
6283 }
6284 getPattern(ctx, owner, inverse, pathType) {
6285 let matrix = inverse;
6286 if (pathType !== PathType.SHADING) {
6287 matrix = Util.transform(matrix, owner.baseTransform);
6288 if (this.matrix) {
6289 matrix = Util.transform(matrix, this.matrix);
6290 }
6291 }
6292 const temporaryPatternCanvas = this.createPatternCanvas(owner);
6293 let domMatrix = new DOMMatrix(matrix);
6294 domMatrix = domMatrix.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
6295 domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY);
6296 const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat");
6297 pattern.setTransform(domMatrix);
6298 return pattern;
6299 }
6300 }
6301
6302 ;// ./src/shared/image_utils.js
6303
6304 function convertToRGBA(params) {
6305 switch (params.kind) {
6306 case ImageKind.GRAYSCALE_1BPP:
6307 return convertBlackAndWhiteToRGBA(params);
6308 case ImageKind.RGB_24BPP:
6309 return convertRGBToRGBA(params);
6310 }
6311 return null;
6312 }
6313 function convertBlackAndWhiteToRGBA({
6314 src,
6315 srcPos = 0,
6316 dest,
6317 width,
6318 height,
6319 nonBlackColor = 0xffffffff,
6320 inverseDecode = false
6321 }) {
6322 const black = util_FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
6323 const [zeroMapping, oneMapping] = inverseDecode ? [nonBlackColor, black] : [black, nonBlackColor];
6324 const widthInSource = width >> 3;
6325 const widthRemainder = width & 7;
6326 const srcLength = src.length;
6327 dest = new Uint32Array(dest.buffer);
6328 let destPos = 0;
6329 for (let i = 0; i < height; i++) {
6330 for (const max = srcPos + widthInSource; srcPos < max; srcPos++) {
6331 const elem = srcPos < srcLength ? src[srcPos] : 255;
6332 dest[destPos++] = elem & 0b10000000 ? oneMapping : zeroMapping;
6333 dest[destPos++] = elem & 0b1000000 ? oneMapping : zeroMapping;
6334 dest[destPos++] = elem & 0b100000 ? oneMapping : zeroMapping;
6335 dest[destPos++] = elem & 0b10000 ? oneMapping : zeroMapping;
6336 dest[destPos++] = elem & 0b1000 ? oneMapping : zeroMapping;
6337 dest[destPos++] = elem & 0b100 ? oneMapping : zeroMapping;
6338 dest[destPos++] = elem & 0b10 ? oneMapping : zeroMapping;
6339 dest[destPos++] = elem & 0b1 ? oneMapping : zeroMapping;
6340 }
6341 if (widthRemainder === 0) {
6342 continue;
6343 }
6344 const elem = srcPos < srcLength ? src[srcPos++] : 255;
6345 for (let j = 0; j < widthRemainder; j++) {
6346 dest[destPos++] = elem & 1 << 7 - j ? oneMapping : zeroMapping;
6347 }
6348 }
6349 return {
6350 srcPos,
6351 destPos
6352 };
6353 }
6354 function convertRGBToRGBA({
6355 src,
6356 srcPos = 0,
6357 dest,
6358 destPos = 0,
6359 width,
6360 height
6361 }) {
6362 let i = 0;
6363 const len32 = src.length >> 2;
6364 const src32 = new Uint32Array(src.buffer, srcPos, len32);
6365 if (FeatureTest.isLittleEndian) {
6366 for (; i < len32 - 2; i += 3, destPos += 4) {
6367 const s1 = src32[i];
6368 const s2 = src32[i + 1];
6369 const s3 = src32[i + 2];
6370 dest[destPos] = s1 | 0xff000000;
6371 dest[destPos + 1] = s1 >>> 24 | s2 << 8 | 0xff000000;
6372 dest[destPos + 2] = s2 >>> 16 | s3 << 16 | 0xff000000;
6373 dest[destPos + 3] = s3 >>> 8 | 0xff000000;
6374 }
6375 for (let j = i * 4, jj = src.length; j < jj; j += 3) {
6376 dest[destPos++] = src[j] | src[j + 1] << 8 | src[j + 2] << 16 | 0xff000000;
6377 }
6378 } else {
6379 for (; i < len32 - 2; i += 3, destPos += 4) {
6380 const s1 = src32[i];
6381 const s2 = src32[i + 1];
6382 const s3 = src32[i + 2];
6383 dest[destPos] = s1 | 0xff;
6384 dest[destPos + 1] = s1 << 24 | s2 >>> 8 | 0xff;
6385 dest[destPos + 2] = s2 << 16 | s3 >>> 16 | 0xff;
6386 dest[destPos + 3] = s3 << 8 | 0xff;
6387 }
6388 for (let j = i * 4, jj = src.length; j < jj; j += 3) {
6389 dest[destPos++] = src[j] << 24 | src[j + 1] << 16 | src[j + 2] << 8 | 0xff;
6390 }
6391 }
6392 return {
6393 srcPos,
6394 destPos
6395 };
6396 }
6397 function grayToRGBA(src, dest) {
6398 if (FeatureTest.isLittleEndian) {
6399 for (let i = 0, ii = src.length; i < ii; i++) {
6400 dest[i] = src[i] * 0x10101 | 0xff000000;
6401 }
6402 } else {
6403 for (let i = 0, ii = src.length; i < ii; i++) {
6404 dest[i] = src[i] * 0x1010100 | 0x000000ff;
6405 }
6406 }
6407 }
6408
6409 ;// ./src/display/canvas.js
6410
6411
6412
6413
6414 const MIN_FONT_SIZE = 16;
6415 const MAX_FONT_SIZE = 100;
6416 const EXECUTION_TIME = 15;
6417 const EXECUTION_STEPS = 10;
6418 const MAX_SIZE_TO_COMPILE = 1000;
6419 const FULL_CHUNK_HEIGHT = 16;
6420 function mirrorContextOperations(ctx, destCtx) {
6421 if (ctx._removeMirroring) {
6422 throw new Error("Context is already forwarding operations.");
6423 }
6424 ctx.__originalSave = ctx.save;
6425 ctx.__originalRestore = ctx.restore;
6426 ctx.__originalRotate = ctx.rotate;
6427 ctx.__originalScale = ctx.scale;
6428 ctx.__originalTranslate = ctx.translate;
6429 ctx.__originalTransform = ctx.transform;
6430 ctx.__originalSetTransform = ctx.setTransform;
6431 ctx.__originalResetTransform = ctx.resetTransform;
6432 ctx.__originalClip = ctx.clip;
6433 ctx.__originalMoveTo = ctx.moveTo;
6434 ctx.__originalLineTo = ctx.lineTo;
6435 ctx.__originalBezierCurveTo = ctx.bezierCurveTo;
6436 ctx.__originalRect = ctx.rect;
6437 ctx.__originalClosePath = ctx.closePath;
6438 ctx.__originalBeginPath = ctx.beginPath;
6439 ctx._removeMirroring = () => {
6440 ctx.save = ctx.__originalSave;
6441 ctx.restore = ctx.__originalRestore;
6442 ctx.rotate = ctx.__originalRotate;
6443 ctx.scale = ctx.__originalScale;
6444 ctx.translate = ctx.__originalTranslate;
6445 ctx.transform = ctx.__originalTransform;
6446 ctx.setTransform = ctx.__originalSetTransform;
6447 ctx.resetTransform = ctx.__originalResetTransform;
6448 ctx.clip = ctx.__originalClip;
6449 ctx.moveTo = ctx.__originalMoveTo;
6450 ctx.lineTo = ctx.__originalLineTo;
6451 ctx.bezierCurveTo = ctx.__originalBezierCurveTo;
6452 ctx.rect = ctx.__originalRect;
6453 ctx.closePath = ctx.__originalClosePath;
6454 ctx.beginPath = ctx.__originalBeginPath;
6455 delete ctx._removeMirroring;
6456 };
6457 ctx.save = function ctxSave() {
6458 destCtx.save();
6459 this.__originalSave();
6460 };
6461 ctx.restore = function ctxRestore() {
6462 destCtx.restore();
6463 this.__originalRestore();
6464 };
6465 ctx.translate = function ctxTranslate(x, y) {
6466 destCtx.translate(x, y);
6467 this.__originalTranslate(x, y);
6468 };
6469 ctx.scale = function ctxScale(x, y) {
6470 destCtx.scale(x, y);
6471 this.__originalScale(x, y);
6472 };
6473 ctx.transform = function ctxTransform(a, b, c, d, e, f) {
6474 destCtx.transform(a, b, c, d, e, f);
6475 this.__originalTransform(a, b, c, d, e, f);
6476 };
6477 ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
6478 destCtx.setTransform(a, b, c, d, e, f);
6479 this.__originalSetTransform(a, b, c, d, e, f);
6480 };
6481 ctx.resetTransform = function ctxResetTransform() {
6482 destCtx.resetTransform();
6483 this.__originalResetTransform();
6484 };
6485 ctx.rotate = function ctxRotate(angle) {
6486 destCtx.rotate(angle);
6487 this.__originalRotate(angle);
6488 };
6489 ctx.clip = function ctxRotate(rule) {
6490 destCtx.clip(rule);
6491 this.__originalClip(rule);
6492 };
6493 ctx.moveTo = function (x, y) {
6494 destCtx.moveTo(x, y);
6495 this.__originalMoveTo(x, y);
6496 };
6497 ctx.lineTo = function (x, y) {
6498 destCtx.lineTo(x, y);
6499 this.__originalLineTo(x, y);
6500 };
6501 ctx.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) {
6502 destCtx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
6503 this.__originalBezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
6504 };
6505 ctx.rect = function (x, y, width, height) {
6506 destCtx.rect(x, y, width, height);
6507 this.__originalRect(x, y, width, height);
6508 };
6509 ctx.closePath = function () {
6510 destCtx.closePath();
6511 this.__originalClosePath();
6512 };
6513 ctx.beginPath = function () {
6514 destCtx.beginPath();
6515 this.__originalBeginPath();
6516 };
6517 }
6518 class CachedCanvases {
6519 constructor(canvasFactory) {
6520 this.canvasFactory = canvasFactory;
6521 this.cache = Object.create(null);
6522 }
6523 getCanvas(id, width, height) {
6524 let canvasEntry;
6525 if (this.cache[id] !== undefined) {
6526 canvasEntry = this.cache[id];
6527 this.canvasFactory.reset(canvasEntry, width, height);
6528 } else {
6529 canvasEntry = this.canvasFactory.create(width, height);
6530 this.cache[id] = canvasEntry;
6531 }
6532 return canvasEntry;
6533 }
6534 delete(id) {
6535 delete this.cache[id];
6536 }
6537 clear() {
6538 for (const id in this.cache) {
6539 const canvasEntry = this.cache[id];
6540 this.canvasFactory.destroy(canvasEntry);
6541 delete this.cache[id];
6542 }
6543 }
6544 }
6545 function drawImageAtIntegerCoords(ctx, srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH) {
6546 const [a, b, c, d, tx, ty] = getCurrentTransform(ctx);
6547 if (b === 0 && c === 0) {
6548 const tlX = destX * a + tx;
6549 const rTlX = Math.round(tlX);
6550 const tlY = destY * d + ty;
6551 const rTlY = Math.round(tlY);
6552 const brX = (destX + destW) * a + tx;
6553 const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
6554 const brY = (destY + destH) * d + ty;
6555 const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
6556 ctx.setTransform(Math.sign(a), 0, 0, Math.sign(d), rTlX, rTlY);
6557 ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rWidth, rHeight);
6558 ctx.setTransform(a, b, c, d, tx, ty);
6559 return [rWidth, rHeight];
6560 }
6561 if (a === 0 && d === 0) {
6562 const tlX = destY * c + tx;
6563 const rTlX = Math.round(tlX);
6564 const tlY = destX * b + ty;
6565 const rTlY = Math.round(tlY);
6566 const brX = (destY + destH) * c + tx;
6567 const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
6568 const brY = (destX + destW) * b + ty;
6569 const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
6570 ctx.setTransform(0, Math.sign(b), Math.sign(c), 0, rTlX, rTlY);
6571 ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rHeight, rWidth);
6572 ctx.setTransform(a, b, c, d, tx, ty);
6573 return [rHeight, rWidth];
6574 }
6575 ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH);
6576 const scaleX = Math.hypot(a, b);
6577 const scaleY = Math.hypot(c, d);
6578 return [scaleX * destW, scaleY * destH];
6579 }
6580 function compileType3Glyph(imgData) {
6581 const {
6582 width,
6583 height
6584 } = imgData;
6585 if (width > MAX_SIZE_TO_COMPILE || height > MAX_SIZE_TO_COMPILE) {
6586 return null;
6587 }
6588 const POINT_TO_PROCESS_LIMIT = 1000;
6589 const POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
6590 const width1 = width + 1;
6591 let points = new Uint8Array(width1 * (height + 1));
6592 let i, j, j0;
6593 const lineSize = width + 7 & ~7;
6594 let data = new Uint8Array(lineSize * height),
6595 pos = 0;
6596 for (const elem of imgData.data) {
6597 let mask = 128;
6598 while (mask > 0) {
6599 data[pos++] = elem & mask ? 0 : 255;
6600 mask >>= 1;
6601 }
6602 }
6603 let count = 0;
6604 pos = 0;
6605 if (data[pos] !== 0) {
6606 points[0] = 1;
6607 ++count;
6608 }
6609 for (j = 1; j < width; j++) {
6610 if (data[pos] !== data[pos + 1]) {
6611 points[j] = data[pos] ? 2 : 1;
6612 ++count;
6613 }
6614 pos++;
6615 }
6616 if (data[pos] !== 0) {
6617 points[j] = 2;
6618 ++count;
6619 }
6620 for (i = 1; i < height; i++) {
6621 pos = i * lineSize;
6622 j0 = i * width1;
6623 if (data[pos - lineSize] !== data[pos]) {
6624 points[j0] = data[pos] ? 1 : 8;
6625 ++count;
6626 }
6627 let sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
6628 for (j = 1; j < width; j++) {
6629 sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0);
6630 if (POINT_TYPES[sum]) {
6631 points[j0 + j] = POINT_TYPES[sum];
6632 ++count;
6633 }
6634 pos++;
6635 }
6636 if (data[pos - lineSize] !== data[pos]) {
6637 points[j0 + j] = data[pos] ? 2 : 4;
6638 ++count;
6639 }
6640 if (count > POINT_TO_PROCESS_LIMIT) {
6641 return null;
6642 }
6643 }
6644 pos = lineSize * (height - 1);
6645 j0 = i * width1;
6646 if (data[pos] !== 0) {
6647 points[j0] = 8;
6648 ++count;
6649 }
6650 for (j = 1; j < width; j++) {
6651 if (data[pos] !== data[pos + 1]) {
6652 points[j0 + j] = data[pos] ? 4 : 8;
6653 ++count;
6654 }
6655 pos++;
6656 }
6657 if (data[pos] !== 0) {
6658 points[j0 + j] = 4;
6659 ++count;
6660 }
6661 if (count > POINT_TO_PROCESS_LIMIT) {
6662 return null;
6663 }
6664 const steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
6665 const path = new Path2D();
6666 for (i = 0; count && i <= height; i++) {
6667 let p = i * width1;
6668 const end = p + width;
6669 while (p < end && !points[p]) {
6670 p++;
6671 }
6672 if (p === end) {
6673 continue;
6674 }
6675 path.moveTo(p % width1, i);
6676 const p0 = p;
6677 let type = points[p];
6678 do {
6679 const step = steps[type];
6680 do {
6681 p += step;
6682 } while (!points[p]);
6683 const pp = points[p];
6684 if (pp !== 5 && pp !== 10) {
6685 type = pp;
6686 points[p] = 0;
6687 } else {
6688 type = pp & 0x33 * type >> 4;
6689 points[p] &= type >> 2 | type << 2;
6690 }
6691 path.lineTo(p % width1, p / width1 | 0);
6692 if (!points[p]) {
6693 --count;
6694 }
6695 } while (p0 !== p);
6696 --i;
6697 }
6698 data = null;
6699 points = null;
6700 const drawOutline = function (c) {
6701 c.save();
6702 c.scale(1 / width, -1 / height);
6703 c.translate(0, -height);
6704 c.fill(path);
6705 c.beginPath();
6706 c.restore();
6707 };
6708 return drawOutline;
6709 }
6710 class CanvasExtraState {
6711 constructor(width, height) {
6712 this.alphaIsShape = false;
6713 this.fontSize = 0;
6714 this.fontSizeScale = 1;
6715 this.textMatrix = IDENTITY_MATRIX;
6716 this.textMatrixScale = 1;
6717 this.fontMatrix = FONT_IDENTITY_MATRIX;
6718 this.leading = 0;
6719 this.x = 0;
6720 this.y = 0;
6721 this.lineX = 0;
6722 this.lineY = 0;
6723 this.charSpacing = 0;
6724 this.wordSpacing = 0;
6725 this.textHScale = 1;
6726 this.textRenderingMode = TextRenderingMode.FILL;
6727 this.textRise = 0;
6728 this.fillColor = "#000000";
6729 this.strokeColor = "#000000";
6730 this.patternFill = false;
6731 this.fillAlpha = 1;
6732 this.strokeAlpha = 1;
6733 this.lineWidth = 1;
6734 this.activeSMask = null;
6735 this.transferMaps = "none";
6736 this.startNewPathAndClipBox([0, 0, width, height]);
6737 }
6738 clone() {
6739 const clone = Object.create(this);
6740 clone.clipBox = this.clipBox.slice();
6741 return clone;
6742 }
6743 setCurrentPoint(x, y) {
6744 this.x = x;
6745 this.y = y;
6746 }
6747 updatePathMinMax(transform, x, y) {
6748 [x, y] = Util.applyTransform([x, y], transform);
6749 this.minX = Math.min(this.minX, x);
6750 this.minY = Math.min(this.minY, y);
6751 this.maxX = Math.max(this.maxX, x);
6752 this.maxY = Math.max(this.maxY, y);
6753 }
6754 updateRectMinMax(transform, rect) {
6755 const p1 = Util.applyTransform(rect, transform);
6756 const p2 = Util.applyTransform(rect.slice(2), transform);
6757 const p3 = Util.applyTransform([rect[0], rect[3]], transform);
6758 const p4 = Util.applyTransform([rect[2], rect[1]], transform);
6759 this.minX = Math.min(this.minX, p1[0], p2[0], p3[0], p4[0]);
6760 this.minY = Math.min(this.minY, p1[1], p2[1], p3[1], p4[1]);
6761 this.maxX = Math.max(this.maxX, p1[0], p2[0], p3[0], p4[0]);
6762 this.maxY = Math.max(this.maxY, p1[1], p2[1], p3[1], p4[1]);
6763 }
6764 updateScalingPathMinMax(transform, minMax) {
6765 Util.scaleMinMax(transform, minMax);
6766 this.minX = Math.min(this.minX, minMax[0]);
6767 this.minY = Math.min(this.minY, minMax[1]);
6768 this.maxX = Math.max(this.maxX, minMax[2]);
6769 this.maxY = Math.max(this.maxY, minMax[3]);
6770 }
6771 updateCurvePathMinMax(transform, x0, y0, x1, y1, x2, y2, x3, y3, minMax) {
6772 const box = Util.bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3, minMax);
6773 if (minMax) {
6774 return;
6775 }
6776 this.updateRectMinMax(transform, box);
6777 }
6778 getPathBoundingBox(pathType = PathType.FILL, transform = null) {
6779 const box = [this.minX, this.minY, this.maxX, this.maxY];
6780 if (pathType === PathType.STROKE) {
6781 if (!transform) {
6782 unreachable("Stroke bounding box must include transform.");
6783 }
6784 const scale = Util.singularValueDecompose2dScale(transform);
6785 const xStrokePad = scale[0] * this.lineWidth / 2;
6786 const yStrokePad = scale[1] * this.lineWidth / 2;
6787 box[0] -= xStrokePad;
6788 box[1] -= yStrokePad;
6789 box[2] += xStrokePad;
6790 box[3] += yStrokePad;
6791 }
6792 return box;
6793 }
6794 updateClipFromPath() {
6795 const intersect = Util.intersect(this.clipBox, this.getPathBoundingBox());
6796 this.startNewPathAndClipBox(intersect || [0, 0, 0, 0]);
6797 }
6798 isEmptyClip() {
6799 return this.minX === Infinity;
6800 }
6801 startNewPathAndClipBox(box) {
6802 this.clipBox = box;
6803 this.minX = Infinity;
6804 this.minY = Infinity;
6805 this.maxX = 0;
6806 this.maxY = 0;
6807 }
6808 getClippedPathBoundingBox(pathType = PathType.FILL, transform = null) {
6809 return Util.intersect(this.clipBox, this.getPathBoundingBox(pathType, transform));
6810 }
6811 }
6812 function putBinaryImageData(ctx, imgData) {
6813 if (typeof ImageData !== "undefined" && imgData instanceof ImageData) {
6814 ctx.putImageData(imgData, 0, 0);
6815 return;
6816 }
6817 const height = imgData.height,
6818 width = imgData.width;
6819 const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
6820 const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
6821 const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
6822 const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
6823 let srcPos = 0,
6824 destPos;
6825 const src = imgData.data;
6826 const dest = chunkImgData.data;
6827 let i, j, thisChunkHeight, elemsInThisChunk;
6828 if (imgData.kind === util_ImageKind.GRAYSCALE_1BPP) {
6829 const srcLength = src.byteLength;
6830 const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2);
6831 const dest32DataLength = dest32.length;
6832 const fullSrcDiff = width + 7 >> 3;
6833 const white = 0xffffffff;
6834 const black = util_FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
6835 for (i = 0; i < totalChunks; i++) {
6836 thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
6837 destPos = 0;
6838 for (j = 0; j < thisChunkHeight; j++) {
6839 const srcDiff = srcLength - srcPos;
6840 let k = 0;
6841 const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;
6842 const kEndUnrolled = kEnd & ~7;
6843 let mask = 0;
6844 let srcByte = 0;
6845 for (; k < kEndUnrolled; k += 8) {
6846 srcByte = src[srcPos++];
6847 dest32[destPos++] = srcByte & 128 ? white : black;
6848 dest32[destPos++] = srcByte & 64 ? white : black;
6849 dest32[destPos++] = srcByte & 32 ? white : black;
6850 dest32[destPos++] = srcByte & 16 ? white : black;
6851 dest32[destPos++] = srcByte & 8 ? white : black;
6852 dest32[destPos++] = srcByte & 4 ? white : black;
6853 dest32[destPos++] = srcByte & 2 ? white : black;
6854 dest32[destPos++] = srcByte & 1 ? white : black;
6855 }
6856 for (; k < kEnd; k++) {
6857 if (mask === 0) {
6858 srcByte = src[srcPos++];
6859 mask = 128;
6860 }
6861 dest32[destPos++] = srcByte & mask ? white : black;
6862 mask >>= 1;
6863 }
6864 }
6865 while (destPos < dest32DataLength) {
6866 dest32[destPos++] = 0;
6867 }
6868 ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
6869 }
6870 } else if (imgData.kind === util_ImageKind.RGBA_32BPP) {
6871 j = 0;
6872 elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
6873 for (i = 0; i < fullChunks; i++) {
6874 dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
6875 srcPos += elemsInThisChunk;
6876 ctx.putImageData(chunkImgData, 0, j);
6877 j += FULL_CHUNK_HEIGHT;
6878 }
6879 if (i < totalChunks) {
6880 elemsInThisChunk = width * partialChunkHeight * 4;
6881 dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
6882 ctx.putImageData(chunkImgData, 0, j);
6883 }
6884 } else if (imgData.kind === util_ImageKind.RGB_24BPP) {
6885 thisChunkHeight = FULL_CHUNK_HEIGHT;
6886 elemsInThisChunk = width * thisChunkHeight;
6887 for (i = 0; i < totalChunks; i++) {
6888 if (i >= fullChunks) {
6889 thisChunkHeight = partialChunkHeight;
6890 elemsInThisChunk = width * thisChunkHeight;
6891 }
6892 destPos = 0;
6893 for (j = elemsInThisChunk; j--;) {
6894 dest[destPos++] = src[srcPos++];
6895 dest[destPos++] = src[srcPos++];
6896 dest[destPos++] = src[srcPos++];
6897 dest[destPos++] = 255;
6898 }
6899 ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
6900 }
6901 } else {
6902 throw new Error(`bad image kind: ${imgData.kind}`);
6903 }
6904 }
6905 function putBinaryImageMask(ctx, imgData) {
6906 if (imgData.bitmap) {
6907 ctx.drawImage(imgData.bitmap, 0, 0);
6908 return;
6909 }
6910 const height = imgData.height,
6911 width = imgData.width;
6912 const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
6913 const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
6914 const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
6915 const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
6916 let srcPos = 0;
6917 const src = imgData.data;
6918 const dest = chunkImgData.data;
6919 for (let i = 0; i < totalChunks; i++) {
6920 const thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
6921 ({
6922 srcPos
6923 } = convertBlackAndWhiteToRGBA({
6924 src,
6925 srcPos,
6926 dest,
6927 width,
6928 height: thisChunkHeight,
6929 nonBlackColor: 0
6930 }));
6931 ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
6932 }
6933 }
6934 function copyCtxState(sourceCtx, destCtx) {
6935 const properties = ["strokeStyle", "fillStyle", "fillRule", "globalAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "globalCompositeOperation", "font", "filter"];
6936 for (const property of properties) {
6937 if (sourceCtx[property] !== undefined) {
6938 destCtx[property] = sourceCtx[property];
6939 }
6940 }
6941 if (sourceCtx.setLineDash !== undefined) {
6942 destCtx.setLineDash(sourceCtx.getLineDash());
6943 destCtx.lineDashOffset = sourceCtx.lineDashOffset;
6944 }
6945 }
6946 function resetCtxToDefault(ctx) {
6947 ctx.strokeStyle = ctx.fillStyle = "#000000";
6948 ctx.fillRule = "nonzero";
6949 ctx.globalAlpha = 1;
6950 ctx.lineWidth = 1;
6951 ctx.lineCap = "butt";
6952 ctx.lineJoin = "miter";
6953 ctx.miterLimit = 10;
6954 ctx.globalCompositeOperation = "source-over";
6955 ctx.font = "10px sans-serif";
6956 if (ctx.setLineDash !== undefined) {
6957 ctx.setLineDash([]);
6958 ctx.lineDashOffset = 0;
6959 }
6960 if (!isNodeJS) {
6961 const {
6962 filter
6963 } = ctx;
6964 if (filter !== "none" && filter !== "") {
6965 ctx.filter = "none";
6966 }
6967 }
6968 }
6969 function getImageSmoothingEnabled(transform, interpolate) {
6970 if (interpolate) {
6971 return true;
6972 }
6973 const scale = Util.singularValueDecompose2dScale(transform);
6974 scale[0] = Math.fround(scale[0]);
6975 scale[1] = Math.fround(scale[1]);
6976 const actualScale = Math.fround((globalThis.devicePixelRatio || 1) * PixelsPerInch.PDF_TO_CSS_UNITS);
6977 return scale[0] <= actualScale && scale[1] <= actualScale;
6978 }
6979 const LINE_CAP_STYLES = ["butt", "round", "square"];
6980 const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
6981 const NORMAL_CLIP = {};
6982 const EO_CLIP = {};
6983 class CanvasGraphics {
6984 constructor(canvasCtx, commonObjs, objs, canvasFactory, filterFactory, {
6985 optionalContentConfig,
6986 markedContentStack = null
6987 }, annotationCanvasMap, pageColors) {
6988 this.ctx = canvasCtx;
6989 this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
6990 this.stateStack = [];
6991 this.pendingClip = null;
6992 this.pendingEOFill = false;
6993 this.res = null;
6994 this.xobjs = null;
6995 this.commonObjs = commonObjs;
6996 this.objs = objs;
6997 this.canvasFactory = canvasFactory;
6998 this.filterFactory = filterFactory;
6999 this.groupStack = [];
7000 this.processingType3 = null;
7001 this.baseTransform = null;
7002 this.baseTransformStack = [];
7003 this.groupLevel = 0;
7004 this.smaskStack = [];
7005 this.smaskCounter = 0;
7006 this.tempSMask = null;
7007 this.suspendedCtx = null;
7008 this.contentVisible = true;
7009 this.markedContentStack = markedContentStack || [];
7010 this.optionalContentConfig = optionalContentConfig;
7011 this.cachedCanvases = new CachedCanvases(this.canvasFactory);
7012 this.cachedPatterns = new Map();
7013 this.annotationCanvasMap = annotationCanvasMap;
7014 this.viewportScale = 1;
7015 this.outputScaleX = 1;
7016 this.outputScaleY = 1;
7017 this.pageColors = pageColors;
7018 this._cachedScaleForStroking = [-1, 0];
7019 this._cachedGetSinglePixelWidth = null;
7020 this._cachedBitmapsMap = new Map();
7021 }
7022 getObject(data, fallback = null) {
7023 if (typeof data === "string") {
7024 return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data);
7025 }
7026 return fallback;
7027 }
7028 beginDrawing({
7029 transform,
7030 viewport,
7031 transparency = false,
7032 background = null
7033 }) {
7034 const width = this.ctx.canvas.width;
7035 const height = this.ctx.canvas.height;
7036 const savedFillStyle = this.ctx.fillStyle;
7037 this.ctx.fillStyle = background || "#ffffff";
7038 this.ctx.fillRect(0, 0, width, height);
7039 this.ctx.fillStyle = savedFillStyle;
7040 if (transparency) {
7041 const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height);
7042 this.compositeCtx = this.ctx;
7043 this.transparentCanvas = transparentCanvas.canvas;
7044 this.ctx = transparentCanvas.context;
7045 this.ctx.save();
7046 this.ctx.transform(...getCurrentTransform(this.compositeCtx));
7047 }
7048 this.ctx.save();
7049 resetCtxToDefault(this.ctx);
7050 if (transform) {
7051 this.ctx.transform(...transform);
7052 this.outputScaleX = transform[0];
7053 this.outputScaleY = transform[0];
7054 }
7055 this.ctx.transform(...viewport.transform);
7056 this.viewportScale = viewport.scale;
7057 this.baseTransform = getCurrentTransform(this.ctx);
7058 }
7059 executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) {
7060 const argsArray = operatorList.argsArray;
7061 const fnArray = operatorList.fnArray;
7062 let i = executionStartIdx || 0;
7063 const argsArrayLen = argsArray.length;
7064 if (argsArrayLen === i) {
7065 return i;
7066 }
7067 const chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === "function";
7068 const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
7069 let steps = 0;
7070 const commonObjs = this.commonObjs;
7071 const objs = this.objs;
7072 let fnId;
7073 while (true) {
7074 if (stepper !== undefined && i === stepper.nextBreakPoint) {
7075 stepper.breakIt(i, continueCallback);
7076 return i;
7077 }
7078 fnId = fnArray[i];
7079 if (fnId !== OPS.dependency) {
7080 this[fnId].apply(this, argsArray[i]);
7081 } else {
7082 for (const depObjId of argsArray[i]) {
7083 const objsPool = depObjId.startsWith("g_") ? commonObjs : objs;
7084 if (!objsPool.has(depObjId)) {
7085 objsPool.get(depObjId, continueCallback);
7086 return i;
7087 }
7088 }
7089 }
7090 i++;
7091 if (i === argsArrayLen) {
7092 return i;
7093 }
7094 if (chunkOperations && ++steps > EXECUTION_STEPS) {
7095 if (Date.now() > endTime) {
7096 continueCallback();
7097 return i;
7098 }
7099 steps = 0;
7100 }
7101 }
7102 }
7103 #restoreInitialState() {
7104 while (this.stateStack.length || this.inSMaskMode) {
7105 this.restore();
7106 }
7107 this.current.activeSMask = null;
7108 this.ctx.restore();
7109 if (this.transparentCanvas) {
7110 this.ctx = this.compositeCtx;
7111 this.ctx.save();
7112 this.ctx.setTransform(1, 0, 0, 1, 0, 0);
7113 this.ctx.drawImage(this.transparentCanvas, 0, 0);
7114 this.ctx.restore();
7115 this.transparentCanvas = null;
7116 }
7117 }
7118 endDrawing() {
7119 this.#restoreInitialState();
7120 this.cachedCanvases.clear();
7121 this.cachedPatterns.clear();
7122 for (const cache of this._cachedBitmapsMap.values()) {
7123 for (const canvas of cache.values()) {
7124 if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
7125 canvas.width = canvas.height = 0;
7126 }
7127 }
7128 cache.clear();
7129 }
7130 this._cachedBitmapsMap.clear();
7131 this.#drawFilter();
7132 }
7133 #drawFilter() {
7134 if (this.pageColors) {
7135 const hcmFilterId = this.filterFactory.addHCMFilter(this.pageColors.foreground, this.pageColors.background);
7136 if (hcmFilterId !== "none") {
7137 const savedFilter = this.ctx.filter;
7138 this.ctx.filter = hcmFilterId;
7139 this.ctx.drawImage(this.ctx.canvas, 0, 0);
7140 this.ctx.filter = savedFilter;
7141 }
7142 }
7143 }
7144 _scaleImage(img, inverseTransform) {
7145 const width = img.width;
7146 const height = img.height;
7147 let widthScale = Math.max(Math.hypot(inverseTransform[0], inverseTransform[1]), 1);
7148 let heightScale = Math.max(Math.hypot(inverseTransform[2], inverseTransform[3]), 1);
7149 let paintWidth = width,
7150 paintHeight = height;
7151 let tmpCanvasId = "prescale1";
7152 let tmpCanvas, tmpCtx;
7153 while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {
7154 let newWidth = paintWidth,
7155 newHeight = paintHeight;
7156 if (widthScale > 2 && paintWidth > 1) {
7157 newWidth = paintWidth >= 16384 ? Math.floor(paintWidth / 2) - 1 || 1 : Math.ceil(paintWidth / 2);
7158 widthScale /= paintWidth / newWidth;
7159 }
7160 if (heightScale > 2 && paintHeight > 1) {
7161 newHeight = paintHeight >= 16384 ? Math.floor(paintHeight / 2) - 1 || 1 : Math.ceil(paintHeight) / 2;
7162 heightScale /= paintHeight / newHeight;
7163 }
7164 tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
7165 tmpCtx = tmpCanvas.context;
7166 tmpCtx.clearRect(0, 0, newWidth, newHeight);
7167 tmpCtx.drawImage(img, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
7168 img = tmpCanvas.canvas;
7169 paintWidth = newWidth;
7170 paintHeight = newHeight;
7171 tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1";
7172 }
7173 return {
7174 img,
7175 paintWidth,
7176 paintHeight
7177 };
7178 }
7179 _createMaskCanvas(img) {
7180 const ctx = this.ctx;
7181 const {
7182 width,
7183 height
7184 } = img;
7185 const fillColor = this.current.fillColor;
7186 const isPatternFill = this.current.patternFill;
7187 const currentTransform = getCurrentTransform(ctx);
7188 let cache, cacheKey, scaled, maskCanvas;
7189 if ((img.bitmap || img.data) && img.count > 1) {
7190 const mainKey = img.bitmap || img.data.buffer;
7191 cacheKey = JSON.stringify(isPatternFill ? currentTransform : [currentTransform.slice(0, 4), fillColor]);
7192 cache = this._cachedBitmapsMap.get(mainKey);
7193 if (!cache) {
7194 cache = new Map();
7195 this._cachedBitmapsMap.set(mainKey, cache);
7196 }
7197 const cachedImage = cache.get(cacheKey);
7198 if (cachedImage && !isPatternFill) {
7199 const offsetX = Math.round(Math.min(currentTransform[0], currentTransform[2]) + currentTransform[4]);
7200 const offsetY = Math.round(Math.min(currentTransform[1], currentTransform[3]) + currentTransform[5]);
7201 return {
7202 canvas: cachedImage,
7203 offsetX,
7204 offsetY
7205 };
7206 }
7207 scaled = cachedImage;
7208 }
7209 if (!scaled) {
7210 maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
7211 putBinaryImageMask(maskCanvas.context, img);
7212 }
7213 let maskToCanvas = Util.transform(currentTransform, [1 / width, 0, 0, -1 / height, 0, 0]);
7214 maskToCanvas = Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]);
7215 const [minX, minY, maxX, maxY] = Util.getAxialAlignedBoundingBox([0, 0, width, height], maskToCanvas);
7216 const drawnWidth = Math.round(maxX - minX) || 1;
7217 const drawnHeight = Math.round(maxY - minY) || 1;
7218 const fillCanvas = this.cachedCanvases.getCanvas("fillCanvas", drawnWidth, drawnHeight);
7219 const fillCtx = fillCanvas.context;
7220 const offsetX = minX;
7221 const offsetY = minY;
7222 fillCtx.translate(-offsetX, -offsetY);
7223 fillCtx.transform(...maskToCanvas);
7224 if (!scaled) {
7225 scaled = this._scaleImage(maskCanvas.canvas, getCurrentTransformInverse(fillCtx));
7226 scaled = scaled.img;
7227 if (cache && isPatternFill) {
7228 cache.set(cacheKey, scaled);
7229 }
7230 }
7231 fillCtx.imageSmoothingEnabled = getImageSmoothingEnabled(getCurrentTransform(fillCtx), img.interpolate);
7232 drawImageAtIntegerCoords(fillCtx, scaled, 0, 0, scaled.width, scaled.height, 0, 0, width, height);
7233 fillCtx.globalCompositeOperation = "source-in";
7234 const inverse = Util.transform(getCurrentTransformInverse(fillCtx), [1, 0, 0, 1, -offsetX, -offsetY]);
7235 fillCtx.fillStyle = isPatternFill ? fillColor.getPattern(ctx, this, inverse, PathType.FILL) : fillColor;
7236 fillCtx.fillRect(0, 0, width, height);
7237 if (cache && !isPatternFill) {
7238 this.cachedCanvases.delete("fillCanvas");
7239 cache.set(cacheKey, fillCanvas.canvas);
7240 }
7241 return {
7242 canvas: fillCanvas.canvas,
7243 offsetX: Math.round(offsetX),
7244 offsetY: Math.round(offsetY)
7245 };
7246 }
7247 setLineWidth(width) {
7248 if (width !== this.current.lineWidth) {
7249 this._cachedScaleForStroking[0] = -1;
7250 }
7251 this.current.lineWidth = width;
7252 this.ctx.lineWidth = width;
7253 }
7254 setLineCap(style) {
7255 this.ctx.lineCap = LINE_CAP_STYLES[style];
7256 }
7257 setLineJoin(style) {
7258 this.ctx.lineJoin = LINE_JOIN_STYLES[style];
7259 }
7260 setMiterLimit(limit) {
7261 this.ctx.miterLimit = limit;
7262 }
7263 setDash(dashArray, dashPhase) {
7264 const ctx = this.ctx;
7265 if (ctx.setLineDash !== undefined) {
7266 ctx.setLineDash(dashArray);
7267 ctx.lineDashOffset = dashPhase;
7268 }
7269 }
7270 setRenderingIntent(intent) {}
7271 setFlatness(flatness) {}
7272 setGState(states) {
7273 for (const [key, value] of states) {
7274 switch (key) {
7275 case "LW":
7276 this.setLineWidth(value);
7277 break;
7278 case "LC":
7279 this.setLineCap(value);
7280 break;
7281 case "LJ":
7282 this.setLineJoin(value);
7283 break;
7284 case "ML":
7285 this.setMiterLimit(value);
7286 break;
7287 case "D":
7288 this.setDash(value[0], value[1]);
7289 break;
7290 case "RI":
7291 this.setRenderingIntent(value);
7292 break;
7293 case "FL":
7294 this.setFlatness(value);
7295 break;
7296 case "Font":
7297 this.setFont(value[0], value[1]);
7298 break;
7299 case "CA":
7300 this.current.strokeAlpha = value;
7301 break;
7302 case "ca":
7303 this.current.fillAlpha = value;
7304 this.ctx.globalAlpha = value;
7305 break;
7306 case "BM":
7307 this.ctx.globalCompositeOperation = value;
7308 break;
7309 case "SMask":
7310 this.current.activeSMask = value ? this.tempSMask : null;
7311 this.tempSMask = null;
7312 this.checkSMaskState();
7313 break;
7314 case "TR":
7315 this.ctx.filter = this.current.transferMaps = this.filterFactory.addFilter(value);
7316 break;
7317 }
7318 }
7319 }
7320 get inSMaskMode() {
7321 return !!this.suspendedCtx;
7322 }
7323 checkSMaskState() {
7324 const inSMaskMode = this.inSMaskMode;
7325 if (this.current.activeSMask && !inSMaskMode) {
7326 this.beginSMaskMode();
7327 } else if (!this.current.activeSMask && inSMaskMode) {
7328 this.endSMaskMode();
7329 }
7330 }
7331 beginSMaskMode() {
7332 if (this.inSMaskMode) {
7333 throw new Error("beginSMaskMode called while already in smask mode");
7334 }
7335 const drawnWidth = this.ctx.canvas.width;
7336 const drawnHeight = this.ctx.canvas.height;
7337 const cacheId = "smaskGroupAt" + this.groupLevel;
7338 const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
7339 this.suspendedCtx = this.ctx;
7340 this.ctx = scratchCanvas.context;
7341 const ctx = this.ctx;
7342 ctx.setTransform(...getCurrentTransform(this.suspendedCtx));
7343 copyCtxState(this.suspendedCtx, ctx);
7344 mirrorContextOperations(ctx, this.suspendedCtx);
7345 this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
7346 }
7347 endSMaskMode() {
7348 if (!this.inSMaskMode) {
7349 throw new Error("endSMaskMode called while not in smask mode");
7350 }
7351 this.ctx._removeMirroring();
7352 copyCtxState(this.ctx, this.suspendedCtx);
7353 this.ctx = this.suspendedCtx;
7354 this.suspendedCtx = null;
7355 }
7356 compose(dirtyBox) {
7357 if (!this.current.activeSMask) {
7358 return;
7359 }
7360 if (!dirtyBox) {
7361 dirtyBox = [0, 0, this.ctx.canvas.width, this.ctx.canvas.height];
7362 } else {
7363 dirtyBox[0] = Math.floor(dirtyBox[0]);
7364 dirtyBox[1] = Math.floor(dirtyBox[1]);
7365 dirtyBox[2] = Math.ceil(dirtyBox[2]);
7366 dirtyBox[3] = Math.ceil(dirtyBox[3]);
7367 }
7368 const smask = this.current.activeSMask;
7369 const suspendedCtx = this.suspendedCtx;
7370 this.composeSMask(suspendedCtx, smask, this.ctx, dirtyBox);
7371 this.ctx.save();
7372 this.ctx.setTransform(1, 0, 0, 1, 0, 0);
7373 this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
7374 this.ctx.restore();
7375 }
7376 composeSMask(ctx, smask, layerCtx, layerBox) {
7377 const layerOffsetX = layerBox[0];
7378 const layerOffsetY = layerBox[1];
7379 const layerWidth = layerBox[2] - layerOffsetX;
7380 const layerHeight = layerBox[3] - layerOffsetY;
7381 if (layerWidth === 0 || layerHeight === 0) {
7382 return;
7383 }
7384 this.genericComposeSMask(smask.context, layerCtx, layerWidth, layerHeight, smask.subtype, smask.backdrop, smask.transferMap, layerOffsetX, layerOffsetY, smask.offsetX, smask.offsetY);
7385 ctx.save();
7386 ctx.globalAlpha = 1;
7387 ctx.globalCompositeOperation = "source-over";
7388 ctx.setTransform(1, 0, 0, 1, 0, 0);
7389 ctx.drawImage(layerCtx.canvas, 0, 0);
7390 ctx.restore();
7391 }
7392 genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap, layerOffsetX, layerOffsetY, maskOffsetX, maskOffsetY) {
7393 let maskCanvas = maskCtx.canvas;
7394 let maskX = layerOffsetX - maskOffsetX;
7395 let maskY = layerOffsetY - maskOffsetY;
7396 if (backdrop) {
7397 if (maskX < 0 || maskY < 0 || maskX + width > maskCanvas.width || maskY + height > maskCanvas.height) {
7398 const canvas = this.cachedCanvases.getCanvas("maskExtension", width, height);
7399 const ctx = canvas.context;
7400 ctx.drawImage(maskCanvas, -maskX, -maskY);
7401 if (backdrop.some(c => c !== 0)) {
7402 ctx.globalCompositeOperation = "destination-atop";
7403 ctx.fillStyle = Util.makeHexColor(...backdrop);
7404 ctx.fillRect(0, 0, width, height);
7405 ctx.globalCompositeOperation = "source-over";
7406 }
7407 maskCanvas = canvas.canvas;
7408 maskX = maskY = 0;
7409 } else if (backdrop.some(c => c !== 0)) {
7410 maskCtx.save();
7411 maskCtx.globalAlpha = 1;
7412 maskCtx.setTransform(1, 0, 0, 1, 0, 0);
7413 const clip = new Path2D();
7414 clip.rect(maskX, maskY, width, height);
7415 maskCtx.clip(clip);
7416 maskCtx.globalCompositeOperation = "destination-atop";
7417 maskCtx.fillStyle = Util.makeHexColor(...backdrop);
7418 maskCtx.fillRect(maskX, maskY, width, height);
7419 maskCtx.restore();
7420 }
7421 }
7422 layerCtx.save();
7423 layerCtx.globalAlpha = 1;
7424 layerCtx.setTransform(1, 0, 0, 1, 0, 0);
7425 if (subtype === "Alpha" && transferMap) {
7426 layerCtx.filter = this.filterFactory.addAlphaFilter(transferMap);
7427 } else if (subtype === "Luminosity") {
7428 layerCtx.filter = this.filterFactory.addLuminosityFilter(transferMap);
7429 }
7430 const clip = new Path2D();
7431 clip.rect(layerOffsetX, layerOffsetY, width, height);
7432 layerCtx.clip(clip);
7433 layerCtx.globalCompositeOperation = "destination-in";
7434 layerCtx.drawImage(maskCanvas, maskX, maskY, width, height, layerOffsetX, layerOffsetY, width, height);
7435 layerCtx.restore();
7436 }
7437 save() {
7438 if (this.inSMaskMode) {
7439 copyCtxState(this.ctx, this.suspendedCtx);
7440 this.suspendedCtx.save();
7441 } else {
7442 this.ctx.save();
7443 }
7444 const old = this.current;
7445 this.stateStack.push(old);
7446 this.current = old.clone();
7447 }
7448 restore() {
7449 if (this.stateStack.length === 0 && this.inSMaskMode) {
7450 this.endSMaskMode();
7451 }
7452 if (this.stateStack.length !== 0) {
7453 this.current = this.stateStack.pop();
7454 if (this.inSMaskMode) {
7455 this.suspendedCtx.restore();
7456 copyCtxState(this.suspendedCtx, this.ctx);
7457 } else {
7458 this.ctx.restore();
7459 }
7460 this.checkSMaskState();
7461 this.pendingClip = null;
7462 this._cachedScaleForStroking[0] = -1;
7463 this._cachedGetSinglePixelWidth = null;
7464 }
7465 }
7466 transform(a, b, c, d, e, f) {
7467 this.ctx.transform(a, b, c, d, e, f);
7468 this._cachedScaleForStroking[0] = -1;
7469 this._cachedGetSinglePixelWidth = null;
7470 }
7471 constructPath(ops, args, minMax) {
7472 const ctx = this.ctx;
7473 const current = this.current;
7474 let x = current.x,
7475 y = current.y;
7476 let startX, startY;
7477 const currentTransform = getCurrentTransform(ctx);
7478 const isScalingMatrix = currentTransform[0] === 0 && currentTransform[3] === 0 || currentTransform[1] === 0 && currentTransform[2] === 0;
7479 const minMaxForBezier = isScalingMatrix ? minMax.slice(0) : null;
7480 for (let i = 0, j = 0, ii = ops.length; i < ii; i++) {
7481 switch (ops[i] | 0) {
7482 case OPS.rectangle:
7483 x = args[j++];
7484 y = args[j++];
7485 const width = args[j++];
7486 const height = args[j++];
7487 const xw = x + width;
7488 const yh = y + height;
7489 ctx.moveTo(x, y);
7490 if (width === 0 || height === 0) {
7491 ctx.lineTo(xw, yh);
7492 } else {
7493 ctx.lineTo(xw, y);
7494 ctx.lineTo(xw, yh);
7495 ctx.lineTo(x, yh);
7496 }
7497 if (!isScalingMatrix) {
7498 current.updateRectMinMax(currentTransform, [x, y, xw, yh]);
7499 }
7500 ctx.closePath();
7501 break;
7502 case OPS.moveTo:
7503 x = args[j++];
7504 y = args[j++];
7505 ctx.moveTo(x, y);
7506 if (!isScalingMatrix) {
7507 current.updatePathMinMax(currentTransform, x, y);
7508 }
7509 break;
7510 case OPS.lineTo:
7511 x = args[j++];
7512 y = args[j++];
7513 ctx.lineTo(x, y);
7514 if (!isScalingMatrix) {
7515 current.updatePathMinMax(currentTransform, x, y);
7516 }
7517 break;
7518 case OPS.curveTo:
7519 startX = x;
7520 startY = y;
7521 x = args[j + 4];
7522 y = args[j + 5];
7523 ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y);
7524 current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], args[j + 2], args[j + 3], x, y, minMaxForBezier);
7525 j += 6;
7526 break;
7527 case OPS.curveTo2:
7528 startX = x;
7529 startY = y;
7530 ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]);
7531 current.updateCurvePathMinMax(currentTransform, startX, startY, x, y, args[j], args[j + 1], args[j + 2], args[j + 3], minMaxForBezier);
7532 x = args[j + 2];
7533 y = args[j + 3];
7534 j += 4;
7535 break;
7536 case OPS.curveTo3:
7537 startX = x;
7538 startY = y;
7539 x = args[j + 2];
7540 y = args[j + 3];
7541 ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
7542 current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], x, y, x, y, minMaxForBezier);
7543 j += 4;
7544 break;
7545 case OPS.closePath:
7546 ctx.closePath();
7547 break;
7548 }
7549 }
7550 if (isScalingMatrix) {
7551 current.updateScalingPathMinMax(currentTransform, minMaxForBezier);
7552 }
7553 current.setCurrentPoint(x, y);
7554 }
7555 closePath() {
7556 this.ctx.closePath();
7557 }
7558 stroke(consumePath = true) {
7559 const ctx = this.ctx;
7560 const strokeColor = this.current.strokeColor;
7561 ctx.globalAlpha = this.current.strokeAlpha;
7562 if (this.contentVisible) {
7563 if (typeof strokeColor === "object" && strokeColor?.getPattern) {
7564 ctx.save();
7565 ctx.strokeStyle = strokeColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.STROKE);
7566 this.rescaleAndStroke(false);
7567 ctx.restore();
7568 } else {
7569 this.rescaleAndStroke(true);
7570 }
7571 }
7572 if (consumePath) {
7573 this.consumePath(this.current.getClippedPathBoundingBox());
7574 }
7575 ctx.globalAlpha = this.current.fillAlpha;
7576 }
7577 closeStroke() {
7578 this.closePath();
7579 this.stroke();
7580 }
7581 fill(consumePath = true) {
7582 const ctx = this.ctx;
7583 const fillColor = this.current.fillColor;
7584 const isPatternFill = this.current.patternFill;
7585 let needRestore = false;
7586 if (isPatternFill) {
7587 ctx.save();
7588 ctx.fillStyle = fillColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.FILL);
7589 needRestore = true;
7590 }
7591 const intersect = this.current.getClippedPathBoundingBox();
7592 if (this.contentVisible && intersect !== null) {
7593 if (this.pendingEOFill) {
7594 ctx.fill("evenodd");
7595 this.pendingEOFill = false;
7596 } else {
7597 ctx.fill();
7598 }
7599 }
7600 if (needRestore) {
7601 ctx.restore();
7602 }
7603 if (consumePath) {
7604 this.consumePath(intersect);
7605 }
7606 }
7607 eoFill() {
7608 this.pendingEOFill = true;
7609 this.fill();
7610 }
7611 fillStroke() {
7612 this.fill(false);
7613 this.stroke(false);
7614 this.consumePath();
7615 }
7616 eoFillStroke() {
7617 this.pendingEOFill = true;
7618 this.fillStroke();
7619 }
7620 closeFillStroke() {
7621 this.closePath();
7622 this.fillStroke();
7623 }
7624 closeEOFillStroke() {
7625 this.pendingEOFill = true;
7626 this.closePath();
7627 this.fillStroke();
7628 }
7629 endPath() {
7630 this.consumePath();
7631 }
7632 clip() {
7633 this.pendingClip = NORMAL_CLIP;
7634 }
7635 eoClip() {
7636 this.pendingClip = EO_CLIP;
7637 }
7638 beginText() {
7639 this.current.textMatrix = IDENTITY_MATRIX;
7640 this.current.textMatrixScale = 1;
7641 this.current.x = this.current.lineX = 0;
7642 this.current.y = this.current.lineY = 0;
7643 }
7644 endText() {
7645 const paths = this.pendingTextPaths;
7646 const ctx = this.ctx;
7647 if (paths === undefined) {
7648 ctx.beginPath();
7649 return;
7650 }
7651 ctx.save();
7652 ctx.beginPath();
7653 for (const path of paths) {
7654 ctx.setTransform(...path.transform);
7655 ctx.translate(path.x, path.y);
7656 path.addToPath(ctx, path.fontSize);
7657 }
7658 ctx.restore();
7659 ctx.clip();
7660 ctx.beginPath();
7661 delete this.pendingTextPaths;
7662 }
7663 setCharSpacing(spacing) {
7664 this.current.charSpacing = spacing;
7665 }
7666 setWordSpacing(spacing) {
7667 this.current.wordSpacing = spacing;
7668 }
7669 setHScale(scale) {
7670 this.current.textHScale = scale / 100;
7671 }
7672 setLeading(leading) {
7673 this.current.leading = -leading;
7674 }
7675 setFont(fontRefName, size) {
7676 const fontObj = this.commonObjs.get(fontRefName);
7677 const current = this.current;
7678 if (!fontObj) {
7679 throw new Error(`Can't find font for ${fontRefName}`);
7680 }
7681 current.fontMatrix = fontObj.fontMatrix || FONT_IDENTITY_MATRIX;
7682 if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
7683 warn("Invalid font matrix for font " + fontRefName);
7684 }
7685 if (size < 0) {
7686 size = -size;
7687 current.fontDirection = -1;
7688 } else {
7689 current.fontDirection = 1;
7690 }
7691 this.current.font = fontObj;
7692 this.current.fontSize = size;
7693 if (fontObj.isType3Font) {
7694 return;
7695 }
7696 const name = fontObj.loadedName || "sans-serif";
7697 const typeface = fontObj.systemFontInfo?.css || `"${name}", ${fontObj.fallbackName}`;
7698 let bold = "normal";
7699 if (fontObj.black) {
7700 bold = "900";
7701 } else if (fontObj.bold) {
7702 bold = "bold";
7703 }
7704 const italic = fontObj.italic ? "italic" : "normal";
7705 let browserFontSize = size;
7706 if (size < MIN_FONT_SIZE) {
7707 browserFontSize = MIN_FONT_SIZE;
7708 } else if (size > MAX_FONT_SIZE) {
7709 browserFontSize = MAX_FONT_SIZE;
7710 }
7711 this.current.fontSizeScale = size / browserFontSize;
7712 this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`;
7713 }
7714 setTextRenderingMode(mode) {
7715 this.current.textRenderingMode = mode;
7716 }
7717 setTextRise(rise) {
7718 this.current.textRise = rise;
7719 }
7720 moveText(x, y) {
7721 this.current.x = this.current.lineX += x;
7722 this.current.y = this.current.lineY += y;
7723 }
7724 setLeadingMoveText(x, y) {
7725 this.setLeading(-y);
7726 this.moveText(x, y);
7727 }
7728 setTextMatrix(a, b, c, d, e, f) {
7729 this.current.textMatrix = [a, b, c, d, e, f];
7730 this.current.textMatrixScale = Math.hypot(a, b);
7731 this.current.x = this.current.lineX = 0;
7732 this.current.y = this.current.lineY = 0;
7733 }
7734 nextLine() {
7735 this.moveText(0, this.current.leading);
7736 }
7737 paintChar(character, x, y, patternTransform) {
7738 const ctx = this.ctx;
7739 const current = this.current;
7740 const font = current.font;
7741 const textRenderingMode = current.textRenderingMode;
7742 const fontSize = current.fontSize / current.fontSizeScale;
7743 const fillStrokeMode = textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;
7744 const isAddToPathSet = !!(textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG);
7745 const patternFill = current.patternFill && !font.missingFile;
7746 let addToPath;
7747 if (font.disableFontFace || isAddToPathSet || patternFill) {
7748 addToPath = font.getPathGenerator(this.commonObjs, character);
7749 }
7750 if (font.disableFontFace || patternFill) {
7751 ctx.save();
7752 ctx.translate(x, y);
7753 ctx.beginPath();
7754 addToPath(ctx, fontSize);
7755 if (patternTransform) {
7756 ctx.setTransform(...patternTransform);
7757 }
7758 if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
7759 ctx.fill();
7760 }
7761 if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
7762 ctx.stroke();
7763 }
7764 ctx.restore();
7765 } else {
7766 if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
7767 ctx.fillText(character, x, y);
7768 }
7769 if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
7770 ctx.strokeText(character, x, y);
7771 }
7772 }
7773 if (isAddToPathSet) {
7774 const paths = this.pendingTextPaths ||= [];
7775 paths.push({
7776 transform: getCurrentTransform(ctx),
7777 x,
7778 y,
7779 fontSize,
7780 addToPath
7781 });
7782 }
7783 }
7784 get isFontSubpixelAAEnabled() {
7785 const {
7786 context: ctx
7787 } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10);
7788 ctx.scale(1.5, 1);
7789 ctx.fillText("I", 0, 10);
7790 const data = ctx.getImageData(0, 0, 10, 10).data;
7791 let enabled = false;
7792 for (let i = 3; i < data.length; i += 4) {
7793 if (data[i] > 0 && data[i] < 255) {
7794 enabled = true;
7795 break;
7796 }
7797 }
7798 return shadow(this, "isFontSubpixelAAEnabled", enabled);
7799 }
7800 showText(glyphs) {
7801 const current = this.current;
7802 const font = current.font;
7803 if (font.isType3Font) {
7804 return this.showType3Text(glyphs);
7805 }
7806 const fontSize = current.fontSize;
7807 if (fontSize === 0) {
7808 return undefined;
7809 }
7810 const ctx = this.ctx;
7811 const fontSizeScale = current.fontSizeScale;
7812 const charSpacing = current.charSpacing;
7813 const wordSpacing = current.wordSpacing;
7814 const fontDirection = current.fontDirection;
7815 const textHScale = current.textHScale * fontDirection;
7816 const glyphsLength = glyphs.length;
7817 const vertical = font.vertical;
7818 const spacingDir = vertical ? 1 : -1;
7819 const defaultVMetrics = font.defaultVMetrics;
7820 const widthAdvanceScale = fontSize * current.fontMatrix[0];
7821 const simpleFillText = current.textRenderingMode === TextRenderingMode.FILL && !font.disableFontFace && !current.patternFill;
7822 ctx.save();
7823 ctx.transform(...current.textMatrix);
7824 ctx.translate(current.x, current.y + current.textRise);
7825 if (fontDirection > 0) {
7826 ctx.scale(textHScale, -1);
7827 } else {
7828 ctx.scale(textHScale, 1);
7829 }
7830 let patternTransform;
7831 if (current.patternFill) {
7832 ctx.save();
7833 const pattern = current.fillColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.FILL);
7834 patternTransform = getCurrentTransform(ctx);
7835 ctx.restore();
7836 ctx.fillStyle = pattern;
7837 }
7838 let lineWidth = current.lineWidth;
7839 const scale = current.textMatrixScale;
7840 if (scale === 0 || lineWidth === 0) {
7841 const fillStrokeMode = current.textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;
7842 if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
7843 lineWidth = this.getSinglePixelWidth();
7844 }
7845 } else {
7846 lineWidth /= scale;
7847 }
7848 if (fontSizeScale !== 1.0) {
7849 ctx.scale(fontSizeScale, fontSizeScale);
7850 lineWidth /= fontSizeScale;
7851 }
7852 ctx.lineWidth = lineWidth;
7853 if (font.isInvalidPDFjsFont) {
7854 const chars = [];
7855 let width = 0;
7856 for (const glyph of glyphs) {
7857 chars.push(glyph.unicode);
7858 width += glyph.width;
7859 }
7860 ctx.fillText(chars.join(""), 0, 0);
7861 current.x += width * widthAdvanceScale * textHScale;
7862 ctx.restore();
7863 this.compose();
7864 return undefined;
7865 }
7866 let x = 0,
7867 i;
7868 for (i = 0; i < glyphsLength; ++i) {
7869 const glyph = glyphs[i];
7870 if (typeof glyph === "number") {
7871 x += spacingDir * glyph * fontSize / 1000;
7872 continue;
7873 }
7874 let restoreNeeded = false;
7875 const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
7876 const character = glyph.fontChar;
7877 const accent = glyph.accent;
7878 let scaledX, scaledY;
7879 let width = glyph.width;
7880 if (vertical) {
7881 const vmetric = glyph.vmetric || defaultVMetrics;
7882 const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale;
7883 const vy = vmetric[2] * widthAdvanceScale;
7884 width = vmetric ? -vmetric[0] : width;
7885 scaledX = vx / fontSizeScale;
7886 scaledY = (x + vy) / fontSizeScale;
7887 } else {
7888 scaledX = x / fontSizeScale;
7889 scaledY = 0;
7890 }
7891 if (font.remeasure && width > 0) {
7892 const measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale;
7893 if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
7894 const characterScaleX = width / measuredWidth;
7895 restoreNeeded = true;
7896 ctx.save();
7897 ctx.scale(characterScaleX, 1);
7898 scaledX /= characterScaleX;
7899 } else if (width !== measuredWidth) {
7900 scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale;
7901 }
7902 }
7903 if (this.contentVisible && (glyph.isInFont || font.missingFile)) {
7904 if (simpleFillText && !accent) {
7905 ctx.fillText(character, scaledX, scaledY);
7906 } else {
7907 this.paintChar(character, scaledX, scaledY, patternTransform);
7908 if (accent) {
7909 const scaledAccentX = scaledX + fontSize * accent.offset.x / fontSizeScale;
7910 const scaledAccentY = scaledY - fontSize * accent.offset.y / fontSizeScale;
7911 this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY, patternTransform);
7912 }
7913 }
7914 }
7915 const charWidth = vertical ? width * widthAdvanceScale - spacing * fontDirection : width * widthAdvanceScale + spacing * fontDirection;
7916 x += charWidth;
7917 if (restoreNeeded) {
7918 ctx.restore();
7919 }
7920 }
7921 if (vertical) {
7922 current.y -= x;
7923 } else {
7924 current.x += x * textHScale;
7925 }
7926 ctx.restore();
7927 this.compose();
7928 return undefined;
7929 }
7930 showType3Text(glyphs) {
7931 const ctx = this.ctx;
7932 const current = this.current;
7933 const font = current.font;
7934 const fontSize = current.fontSize;
7935 const fontDirection = current.fontDirection;
7936 const spacingDir = font.vertical ? 1 : -1;
7937 const charSpacing = current.charSpacing;
7938 const wordSpacing = current.wordSpacing;
7939 const textHScale = current.textHScale * fontDirection;
7940 const fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
7941 const glyphsLength = glyphs.length;
7942 const isTextInvisible = current.textRenderingMode === TextRenderingMode.INVISIBLE;
7943 let i, glyph, width, spacingLength;
7944 if (isTextInvisible || fontSize === 0) {
7945 return;
7946 }
7947 this._cachedScaleForStroking[0] = -1;
7948 this._cachedGetSinglePixelWidth = null;
7949 ctx.save();
7950 ctx.transform(...current.textMatrix);
7951 ctx.translate(current.x, current.y);
7952 ctx.scale(textHScale, fontDirection);
7953 for (i = 0; i < glyphsLength; ++i) {
7954 glyph = glyphs[i];
7955 if (typeof glyph === "number") {
7956 spacingLength = spacingDir * glyph * fontSize / 1000;
7957 this.ctx.translate(spacingLength, 0);
7958 current.x += spacingLength * textHScale;
7959 continue;
7960 }
7961 const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
7962 const operatorList = font.charProcOperatorList[glyph.operatorListId];
7963 if (!operatorList) {
7964 warn(`Type3 character "${glyph.operatorListId}" is not available.`);
7965 continue;
7966 }
7967 if (this.contentVisible) {
7968 this.processingType3 = glyph;
7969 this.save();
7970 ctx.scale(fontSize, fontSize);
7971 ctx.transform(...fontMatrix);
7972 this.executeOperatorList(operatorList);
7973 this.restore();
7974 }
7975 const transformed = Util.applyTransform([glyph.width, 0], fontMatrix);
7976 width = transformed[0] * fontSize + spacing;
7977 ctx.translate(width, 0);
7978 current.x += width * textHScale;
7979 }
7980 ctx.restore();
7981 this.processingType3 = null;
7982 }
7983 setCharWidth(xWidth, yWidth) {}
7984 setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {
7985 this.ctx.rect(llx, lly, urx - llx, ury - lly);
7986 this.ctx.clip();
7987 this.endPath();
7988 }
7989 getColorN_Pattern(IR) {
7990 let pattern;
7991 if (IR[0] === "TilingPattern") {
7992 const color = IR[1];
7993 const baseTransform = this.baseTransform || getCurrentTransform(this.ctx);
7994 const canvasGraphicsFactory = {
7995 createCanvasGraphics: ctx => new CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, {
7996 optionalContentConfig: this.optionalContentConfig,
7997 markedContentStack: this.markedContentStack
7998 })
7999 };
8000 pattern = new TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform);
8001 } else {
8002 pattern = this._getPattern(IR[1], IR[2]);
8003 }
8004 return pattern;
8005 }
8006 setStrokeColorN() {
8007 this.current.strokeColor = this.getColorN_Pattern(arguments);
8008 }
8009 setFillColorN() {
8010 this.current.fillColor = this.getColorN_Pattern(arguments);
8011 this.current.patternFill = true;
8012 }
8013 setStrokeRGBColor(r, g, b) {
8014 this.ctx.strokeStyle = this.current.strokeColor = Util.makeHexColor(r, g, b);
8015 }
8016 setStrokeTransparent() {
8017 this.ctx.strokeStyle = this.current.strokeColor = "transparent";
8018 }
8019 setFillRGBColor(r, g, b) {
8020 this.ctx.fillStyle = this.current.fillColor = Util.makeHexColor(r, g, b);
8021 this.current.patternFill = false;
8022 }
8023 setFillTransparent() {
8024 this.ctx.fillStyle = this.current.fillColor = "transparent";
8025 this.current.patternFill = false;
8026 }
8027 _getPattern(objId, matrix = null) {
8028 let pattern;
8029 if (this.cachedPatterns.has(objId)) {
8030 pattern = this.cachedPatterns.get(objId);
8031 } else {
8032 pattern = getShadingPattern(this.getObject(objId));
8033 this.cachedPatterns.set(objId, pattern);
8034 }
8035 if (matrix) {
8036 pattern.matrix = matrix;
8037 }
8038 return pattern;
8039 }
8040 shadingFill(objId) {
8041 if (!this.contentVisible) {
8042 return;
8043 }
8044 const ctx = this.ctx;
8045 this.save();
8046 const pattern = this._getPattern(objId);
8047 ctx.fillStyle = pattern.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.SHADING);
8048 const inv = getCurrentTransformInverse(ctx);
8049 if (inv) {
8050 const {
8051 width,
8052 height
8053 } = ctx.canvas;
8054 const [x0, y0, x1, y1] = Util.getAxialAlignedBoundingBox([0, 0, width, height], inv);
8055 this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
8056 } else {
8057 this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
8058 }
8059 this.compose(this.current.getClippedPathBoundingBox());
8060 this.restore();
8061 }
8062 beginInlineImage() {
8063 unreachable("Should not call beginInlineImage");
8064 }
8065 beginImageData() {
8066 unreachable("Should not call beginImageData");
8067 }
8068 paintFormXObjectBegin(matrix, bbox) {
8069 if (!this.contentVisible) {
8070 return;
8071 }
8072 this.save();
8073 this.baseTransformStack.push(this.baseTransform);
8074 if (matrix) {
8075 this.transform(...matrix);
8076 }
8077 this.baseTransform = getCurrentTransform(this.ctx);
8078 if (bbox) {
8079 const width = bbox[2] - bbox[0];
8080 const height = bbox[3] - bbox[1];
8081 this.ctx.rect(bbox[0], bbox[1], width, height);
8082 this.current.updateRectMinMax(getCurrentTransform(this.ctx), bbox);
8083 this.clip();
8084 this.endPath();
8085 }
8086 }
8087 paintFormXObjectEnd() {
8088 if (!this.contentVisible) {
8089 return;
8090 }
8091 this.restore();
8092 this.baseTransform = this.baseTransformStack.pop();
8093 }
8094 beginGroup(group) {
8095 if (!this.contentVisible) {
8096 return;
8097 }
8098 this.save();
8099 if (this.inSMaskMode) {
8100 this.endSMaskMode();
8101 this.current.activeSMask = null;
8102 }
8103 const currentCtx = this.ctx;
8104 if (!group.isolated) {
8105 info("TODO: Support non-isolated groups.");
8106 }
8107 if (group.knockout) {
8108 warn("Knockout groups not supported.");
8109 }
8110 const currentTransform = getCurrentTransform(currentCtx);
8111 if (group.matrix) {
8112 currentCtx.transform(...group.matrix);
8113 }
8114 if (!group.bbox) {
8115 throw new Error("Bounding box is required.");
8116 }
8117 let bounds = Util.getAxialAlignedBoundingBox(group.bbox, getCurrentTransform(currentCtx));
8118 const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height];
8119 bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
8120 const offsetX = Math.floor(bounds[0]);
8121 const offsetY = Math.floor(bounds[1]);
8122 const drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
8123 const drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
8124 this.current.startNewPathAndClipBox([0, 0, drawnWidth, drawnHeight]);
8125 let cacheId = "groupAt" + this.groupLevel;
8126 if (group.smask) {
8127 cacheId += "_smask_" + this.smaskCounter++ % 2;
8128 }
8129 const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
8130 const groupCtx = scratchCanvas.context;
8131 groupCtx.translate(-offsetX, -offsetY);
8132 groupCtx.transform(...currentTransform);
8133 if (group.smask) {
8134 this.smaskStack.push({
8135 canvas: scratchCanvas.canvas,
8136 context: groupCtx,
8137 offsetX,
8138 offsetY,
8139 subtype: group.smask.subtype,
8140 backdrop: group.smask.backdrop,
8141 transferMap: group.smask.transferMap || null,
8142 startTransformInverse: null
8143 });
8144 } else {
8145 currentCtx.setTransform(1, 0, 0, 1, 0, 0);
8146 currentCtx.translate(offsetX, offsetY);
8147 currentCtx.save();
8148 }
8149 copyCtxState(currentCtx, groupCtx);
8150 this.ctx = groupCtx;
8151 this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
8152 this.groupStack.push(currentCtx);
8153 this.groupLevel++;
8154 }
8155 endGroup(group) {
8156 if (!this.contentVisible) {
8157 return;
8158 }
8159 this.groupLevel--;
8160 const groupCtx = this.ctx;
8161 const ctx = this.groupStack.pop();
8162 this.ctx = ctx;
8163 this.ctx.imageSmoothingEnabled = false;
8164 if (group.smask) {
8165 this.tempSMask = this.smaskStack.pop();
8166 this.restore();
8167 } else {
8168 this.ctx.restore();
8169 const currentMtx = getCurrentTransform(this.ctx);
8170 this.restore();
8171 this.ctx.save();
8172 this.ctx.setTransform(...currentMtx);
8173 const dirtyBox = Util.getAxialAlignedBoundingBox([0, 0, groupCtx.canvas.width, groupCtx.canvas.height], currentMtx);
8174 this.ctx.drawImage(groupCtx.canvas, 0, 0);
8175 this.ctx.restore();
8176 this.compose(dirtyBox);
8177 }
8178 }
8179 beginAnnotation(id, rect, transform, matrix, hasOwnCanvas) {
8180 this.#restoreInitialState();
8181 resetCtxToDefault(this.ctx);
8182 this.ctx.save();
8183 this.save();
8184 if (this.baseTransform) {
8185 this.ctx.setTransform(...this.baseTransform);
8186 }
8187 if (rect) {
8188 const width = rect[2] - rect[0];
8189 const height = rect[3] - rect[1];
8190 if (hasOwnCanvas && this.annotationCanvasMap) {
8191 transform = transform.slice();
8192 transform[4] -= rect[0];
8193 transform[5] -= rect[1];
8194 rect = rect.slice();
8195 rect[0] = rect[1] = 0;
8196 rect[2] = width;
8197 rect[3] = height;
8198 const [scaleX, scaleY] = Util.singularValueDecompose2dScale(getCurrentTransform(this.ctx));
8199 const {
8200 viewportScale
8201 } = this;
8202 const canvasWidth = Math.ceil(width * this.outputScaleX * viewportScale);
8203 const canvasHeight = Math.ceil(height * this.outputScaleY * viewportScale);
8204 this.annotationCanvas = this.canvasFactory.create(canvasWidth, canvasHeight);
8205 const {
8206 canvas,
8207 context
8208 } = this.annotationCanvas;
8209 this.annotationCanvasMap.set(id, canvas);
8210 this.annotationCanvas.savedCtx = this.ctx;
8211 this.ctx = context;
8212 this.ctx.save();
8213 this.ctx.setTransform(scaleX, 0, 0, -scaleY, 0, height * scaleY);
8214 resetCtxToDefault(this.ctx);
8215 } else {
8216 resetCtxToDefault(this.ctx);
8217 this.endPath();
8218 this.ctx.rect(rect[0], rect[1], width, height);
8219 this.ctx.clip();
8220 this.ctx.beginPath();
8221 }
8222 }
8223 this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
8224 this.transform(...transform);
8225 this.transform(...matrix);
8226 }
8227 endAnnotation() {
8228 if (this.annotationCanvas) {
8229 this.ctx.restore();
8230 this.#drawFilter();
8231 this.ctx = this.annotationCanvas.savedCtx;
8232 delete this.annotationCanvas.savedCtx;
8233 delete this.annotationCanvas;
8234 }
8235 }
8236 paintImageMaskXObject(img) {
8237 if (!this.contentVisible) {
8238 return;
8239 }
8240 const count = img.count;
8241 img = this.getObject(img.data, img);
8242 img.count = count;
8243 const ctx = this.ctx;
8244 const glyph = this.processingType3;
8245 if (glyph) {
8246 if (glyph.compiled === undefined) {
8247 glyph.compiled = compileType3Glyph(img);
8248 }
8249 if (glyph.compiled) {
8250 glyph.compiled(ctx);
8251 return;
8252 }
8253 }
8254 const mask = this._createMaskCanvas(img);
8255 const maskCanvas = mask.canvas;
8256 ctx.save();
8257 ctx.setTransform(1, 0, 0, 1, 0, 0);
8258 ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY);
8259 ctx.restore();
8260 this.compose();
8261 }
8262 paintImageMaskXObjectRepeat(img, scaleX, skewX = 0, skewY = 0, scaleY, positions) {
8263 if (!this.contentVisible) {
8264 return;
8265 }
8266 img = this.getObject(img.data, img);
8267 const ctx = this.ctx;
8268 ctx.save();
8269 const currentTransform = getCurrentTransform(ctx);
8270 ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0);
8271 const mask = this._createMaskCanvas(img);
8272 ctx.setTransform(1, 0, 0, 1, mask.offsetX - currentTransform[4], mask.offsetY - currentTransform[5]);
8273 for (let i = 0, ii = positions.length; i < ii; i += 2) {
8274 const trans = Util.transform(currentTransform, [scaleX, skewX, skewY, scaleY, positions[i], positions[i + 1]]);
8275 const [x, y] = Util.applyTransform([0, 0], trans);
8276 ctx.drawImage(mask.canvas, x, y);
8277 }
8278 ctx.restore();
8279 this.compose();
8280 }
8281 paintImageMaskXObjectGroup(images) {
8282 if (!this.contentVisible) {
8283 return;
8284 }
8285 const ctx = this.ctx;
8286 const fillColor = this.current.fillColor;
8287 const isPatternFill = this.current.patternFill;
8288 for (const image of images) {
8289 const {
8290 data,
8291 width,
8292 height,
8293 transform
8294 } = image;
8295 const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
8296 const maskCtx = maskCanvas.context;
8297 maskCtx.save();
8298 const img = this.getObject(data, image);
8299 putBinaryImageMask(maskCtx, img);
8300 maskCtx.globalCompositeOperation = "source-in";
8301 maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this, getCurrentTransformInverse(ctx), PathType.FILL) : fillColor;
8302 maskCtx.fillRect(0, 0, width, height);
8303 maskCtx.restore();
8304 ctx.save();
8305 ctx.transform(...transform);
8306 ctx.scale(1, -1);
8307 drawImageAtIntegerCoords(ctx, maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
8308 ctx.restore();
8309 }
8310 this.compose();
8311 }
8312 paintImageXObject(objId) {
8313 if (!this.contentVisible) {
8314 return;
8315 }
8316 const imgData = this.getObject(objId);
8317 if (!imgData) {
8318 warn("Dependent image isn't ready yet");
8319 return;
8320 }
8321 this.paintInlineImageXObject(imgData);
8322 }
8323 paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {
8324 if (!this.contentVisible) {
8325 return;
8326 }
8327 const imgData = this.getObject(objId);
8328 if (!imgData) {
8329 warn("Dependent image isn't ready yet");
8330 return;
8331 }
8332 const width = imgData.width;
8333 const height = imgData.height;
8334 const map = [];
8335 for (let i = 0, ii = positions.length; i < ii; i += 2) {
8336 map.push({
8337 transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]],
8338 x: 0,
8339 y: 0,
8340 w: width,
8341 h: height
8342 });
8343 }
8344 this.paintInlineImageXObjectGroup(imgData, map);
8345 }
8346 applyTransferMapsToCanvas(ctx) {
8347 if (this.current.transferMaps !== "none") {
8348 ctx.filter = this.current.transferMaps;
8349 ctx.drawImage(ctx.canvas, 0, 0);
8350 ctx.filter = "none";
8351 }
8352 return ctx.canvas;
8353 }
8354 applyTransferMapsToBitmap(imgData) {
8355 if (this.current.transferMaps === "none") {
8356 return imgData.bitmap;
8357 }
8358 const {
8359 bitmap,
8360 width,
8361 height
8362 } = imgData;
8363 const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
8364 const tmpCtx = tmpCanvas.context;
8365 tmpCtx.filter = this.current.transferMaps;
8366 tmpCtx.drawImage(bitmap, 0, 0);
8367 tmpCtx.filter = "none";
8368 return tmpCanvas.canvas;
8369 }
8370 paintInlineImageXObject(imgData) {
8371 if (!this.contentVisible) {
8372 return;
8373 }
8374 const width = imgData.width;
8375 const height = imgData.height;
8376 const ctx = this.ctx;
8377 this.save();
8378 if (!isNodeJS) {
8379 const {
8380 filter
8381 } = ctx;
8382 if (filter !== "none" && filter !== "") {
8383 ctx.filter = "none";
8384 }
8385 }
8386 ctx.scale(1 / width, -1 / height);
8387 let imgToPaint;
8388 if (imgData.bitmap) {
8389 imgToPaint = this.applyTransferMapsToBitmap(imgData);
8390 } else if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) {
8391 imgToPaint = imgData;
8392 } else {
8393 const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
8394 const tmpCtx = tmpCanvas.context;
8395 putBinaryImageData(tmpCtx, imgData);
8396 imgToPaint = this.applyTransferMapsToCanvas(tmpCtx);
8397 }
8398 const scaled = this._scaleImage(imgToPaint, getCurrentTransformInverse(ctx));
8399 ctx.imageSmoothingEnabled = getImageSmoothingEnabled(getCurrentTransform(ctx), imgData.interpolate);
8400 drawImageAtIntegerCoords(ctx, scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height);
8401 this.compose();
8402 this.restore();
8403 }
8404 paintInlineImageXObjectGroup(imgData, map) {
8405 if (!this.contentVisible) {
8406 return;
8407 }
8408 const ctx = this.ctx;
8409 let imgToPaint;
8410 if (imgData.bitmap) {
8411 imgToPaint = imgData.bitmap;
8412 } else {
8413 const w = imgData.width;
8414 const h = imgData.height;
8415 const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h);
8416 const tmpCtx = tmpCanvas.context;
8417 putBinaryImageData(tmpCtx, imgData);
8418 imgToPaint = this.applyTransferMapsToCanvas(tmpCtx);
8419 }
8420 for (const entry of map) {
8421 ctx.save();
8422 ctx.transform(...entry.transform);
8423 ctx.scale(1, -1);
8424 drawImageAtIntegerCoords(ctx, imgToPaint, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
8425 ctx.restore();
8426 }
8427 this.compose();
8428 }
8429 paintSolidColorImageMask() {
8430 if (!this.contentVisible) {
8431 return;
8432 }
8433 this.ctx.fillRect(0, 0, 1, 1);
8434 this.compose();
8435 }
8436 markPoint(tag) {}
8437 markPointProps(tag, properties) {}
8438 beginMarkedContent(tag) {
8439 this.markedContentStack.push({
8440 visible: true
8441 });
8442 }
8443 beginMarkedContentProps(tag, properties) {
8444 if (tag === "OC") {
8445 this.markedContentStack.push({
8446 visible: this.optionalContentConfig.isVisible(properties)
8447 });
8448 } else {
8449 this.markedContentStack.push({
8450 visible: true
8451 });
8452 }
8453 this.contentVisible = this.isContentVisible();
8454 }
8455 endMarkedContent() {
8456 this.markedContentStack.pop();
8457 this.contentVisible = this.isContentVisible();
8458 }
8459 beginCompat() {}
8460 endCompat() {}
8461 consumePath(clipBox) {
8462 const isEmpty = this.current.isEmptyClip();
8463 if (this.pendingClip) {
8464 this.current.updateClipFromPath();
8465 }
8466 if (!this.pendingClip) {
8467 this.compose(clipBox);
8468 }
8469 const ctx = this.ctx;
8470 if (this.pendingClip) {
8471 if (!isEmpty) {
8472 if (this.pendingClip === EO_CLIP) {
8473 ctx.clip("evenodd");
8474 } else {
8475 ctx.clip();
8476 }
8477 }
8478 this.pendingClip = null;
8479 }
8480 this.current.startNewPathAndClipBox(this.current.clipBox);
8481 ctx.beginPath();
8482 }
8483 getSinglePixelWidth() {
8484 if (!this._cachedGetSinglePixelWidth) {
8485 const m = getCurrentTransform(this.ctx);
8486 if (m[1] === 0 && m[2] === 0) {
8487 this._cachedGetSinglePixelWidth = 1 / Math.min(Math.abs(m[0]), Math.abs(m[3]));
8488 } else {
8489 const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
8490 const normX = Math.hypot(m[0], m[2]);
8491 const normY = Math.hypot(m[1], m[3]);
8492 this._cachedGetSinglePixelWidth = Math.max(normX, normY) / absDet;
8493 }
8494 }
8495 return this._cachedGetSinglePixelWidth;
8496 }
8497 getScaleForStroking() {
8498 if (this._cachedScaleForStroking[0] === -1) {
8499 const {
8500 lineWidth
8501 } = this.current;
8502 const {
8503 a,
8504 b,
8505 c,
8506 d
8507 } = this.ctx.getTransform();
8508 let scaleX, scaleY;
8509 if (b === 0 && c === 0) {
8510 const normX = Math.abs(a);
8511 const normY = Math.abs(d);
8512 if (normX === normY) {
8513 if (lineWidth === 0) {
8514 scaleX = scaleY = 1 / normX;
8515 } else {
8516 const scaledLineWidth = normX * lineWidth;
8517 scaleX = scaleY = scaledLineWidth < 1 ? 1 / scaledLineWidth : 1;
8518 }
8519 } else if (lineWidth === 0) {
8520 scaleX = 1 / normX;
8521 scaleY = 1 / normY;
8522 } else {
8523 const scaledXLineWidth = normX * lineWidth;
8524 const scaledYLineWidth = normY * lineWidth;
8525 scaleX = scaledXLineWidth < 1 ? 1 / scaledXLineWidth : 1;
8526 scaleY = scaledYLineWidth < 1 ? 1 / scaledYLineWidth : 1;
8527 }
8528 } else {
8529 const absDet = Math.abs(a * d - b * c);
8530 const normX = Math.hypot(a, b);
8531 const normY = Math.hypot(c, d);
8532 if (lineWidth === 0) {
8533 scaleX = normY / absDet;
8534 scaleY = normX / absDet;
8535 } else {
8536 const baseArea = lineWidth * absDet;
8537 scaleX = normY > baseArea ? normY / baseArea : 1;
8538 scaleY = normX > baseArea ? normX / baseArea : 1;
8539 }
8540 }
8541 this._cachedScaleForStroking[0] = scaleX;
8542 this._cachedScaleForStroking[1] = scaleY;
8543 }
8544 return this._cachedScaleForStroking;
8545 }
8546 rescaleAndStroke(saveRestore) {
8547 const {
8548 ctx
8549 } = this;
8550 const {
8551 lineWidth
8552 } = this.current;
8553 const [scaleX, scaleY] = this.getScaleForStroking();
8554 ctx.lineWidth = lineWidth || 1;
8555 if (scaleX === 1 && scaleY === 1) {
8556 ctx.stroke();
8557 return;
8558 }
8559 const dashes = ctx.getLineDash();
8560 if (saveRestore) {
8561 ctx.save();
8562 }
8563 ctx.scale(scaleX, scaleY);
8564 if (dashes.length > 0) {
8565 const scale = Math.max(scaleX, scaleY);
8566 ctx.setLineDash(dashes.map(x => x / scale));
8567 ctx.lineDashOffset /= scale;
8568 }
8569 ctx.stroke();
8570 if (saveRestore) {
8571 ctx.restore();
8572 }
8573 }
8574 isContentVisible() {
8575 for (let i = this.markedContentStack.length - 1; i >= 0; i--) {
8576 if (!this.markedContentStack[i].visible) {
8577 return false;
8578 }
8579 }
8580 return true;
8581 }
8582 }
8583 for (const op in OPS) {
8584 if (CanvasGraphics.prototype[op] !== undefined) {
8585 CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
8586 }
8587 }
8588
8589 ;// ./src/display/worker_options.js
8590 class GlobalWorkerOptions {
8591 static #port = null;
8592 static #src = "";
8593 static get workerPort() {
8594 return this.#port;
8595 }
8596 static set workerPort(val) {
8597 if (!(typeof Worker !== "undefined" && val instanceof Worker) && val !== null) {
8598 throw new Error("Invalid `workerPort` type.");
8599 }
8600 this.#port = val;
8601 }
8602 static get workerSrc() {
8603 return this.#src;
8604 }
8605 static set workerSrc(val) {
8606 if (typeof val !== "string") {
8607 throw new Error("Invalid `workerSrc` type.");
8608 }
8609 this.#src = val;
8610 }
8611 }
8612
8613 ;// ./src/shared/message_handler.js
8614
8615 const CallbackKind = {
8616 UNKNOWN: 0,
8617 DATA: 1,
8618 ERROR: 2
8619 };
8620 const StreamKind = {
8621 UNKNOWN: 0,
8622 CANCEL: 1,
8623 CANCEL_COMPLETE: 2,
8624 CLOSE: 3,
8625 ENQUEUE: 4,
8626 ERROR: 5,
8627 PULL: 6,
8628 PULL_COMPLETE: 7,
8629 START_COMPLETE: 8
8630 };
8631 function wrapReason(reason) {
8632 if (!(reason instanceof Error || typeof reason === "object" && reason !== null)) {
8633 unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.');
8634 }
8635 switch (reason.name) {
8636 case "AbortException":
8637 return new AbortException(reason.message);
8638 case "MissingPDFException":
8639 return new MissingPDFException(reason.message);
8640 case "PasswordException":
8641 return new PasswordException(reason.message, reason.code);
8642 case "UnexpectedResponseException":
8643 return new UnexpectedResponseException(reason.message, reason.status);
8644 case "UnknownErrorException":
8645 return new UnknownErrorException(reason.message, reason.details);
8646 default:
8647 return new UnknownErrorException(reason.message, reason.toString());
8648 }
8649 }
8650 class MessageHandler {
8651 constructor(sourceName, targetName, comObj) {
8652 this.sourceName = sourceName;
8653 this.targetName = targetName;
8654 this.comObj = comObj;
8655 this.callbackId = 1;
8656 this.streamId = 1;
8657 this.streamSinks = Object.create(null);
8658 this.streamControllers = Object.create(null);
8659 this.callbackCapabilities = Object.create(null);
8660 this.actionHandler = Object.create(null);
8661 this._onComObjOnMessage = event => {
8662 const data = event.data;
8663 if (data.targetName !== this.sourceName) {
8664 return;
8665 }
8666 if (data.stream) {
8667 this.#processStreamMessage(data);
8668 return;
8669 }
8670 if (data.callback) {
8671 const callbackId = data.callbackId;
8672 const capability = this.callbackCapabilities[callbackId];
8673 if (!capability) {
8674 throw new Error(`Cannot resolve callback ${callbackId}`);
8675 }
8676 delete this.callbackCapabilities[callbackId];
8677 if (data.callback === CallbackKind.DATA) {
8678 capability.resolve(data.data);
8679 } else if (data.callback === CallbackKind.ERROR) {
8680 capability.reject(wrapReason(data.reason));
8681 } else {
8682 throw new Error("Unexpected callback case");
8683 }
8684 return;
8685 }
8686 const action = this.actionHandler[data.action];
8687 if (!action) {
8688 throw new Error(`Unknown action from worker: ${data.action}`);
8689 }
8690 if (data.callbackId) {
8691 const cbSourceName = this.sourceName;
8692 const cbTargetName = data.sourceName;
8693 new Promise(function (resolve) {
8694 resolve(action(data.data));
8695 }).then(function (result) {
8696 comObj.postMessage({
8697 sourceName: cbSourceName,
8698 targetName: cbTargetName,
8699 callback: CallbackKind.DATA,
8700 callbackId: data.callbackId,
8701 data: result
8702 });
8703 }, function (reason) {
8704 comObj.postMessage({
8705 sourceName: cbSourceName,
8706 targetName: cbTargetName,
8707 callback: CallbackKind.ERROR,
8708 callbackId: data.callbackId,
8709 reason: wrapReason(reason)
8710 });
8711 });
8712 return;
8713 }
8714 if (data.streamId) {
8715 this.#createStreamSink(data);
8716 return;
8717 }
8718 action(data.data);
8719 };
8720 comObj.addEventListener("message", this._onComObjOnMessage);
8721 }
8722 on(actionName, handler) {
8723 const ah = this.actionHandler;
8724 if (ah[actionName]) {
8725 throw new Error(`There is already an actionName called "${actionName}"`);
8726 }
8727 ah[actionName] = handler;
8728 }
8729 send(actionName, data, transfers) {
8730 this.comObj.postMessage({
8731 sourceName: this.sourceName,
8732 targetName: this.targetName,
8733 action: actionName,
8734 data
8735 }, transfers);
8736 }
8737 sendWithPromise(actionName, data, transfers) {
8738 const callbackId = this.callbackId++;
8739 const capability = Promise.withResolvers();
8740 this.callbackCapabilities[callbackId] = capability;
8741 try {
8742 this.comObj.postMessage({
8743 sourceName: this.sourceName,
8744 targetName: this.targetName,
8745 action: actionName,
8746 callbackId,
8747 data
8748 }, transfers);
8749 } catch (ex) {
8750 capability.reject(ex);
8751 }
8752 return capability.promise;
8753 }
8754 sendWithStream(actionName, data, queueingStrategy, transfers) {
8755 const streamId = this.streamId++,
8756 sourceName = this.sourceName,
8757 targetName = this.targetName,
8758 comObj = this.comObj;
8759 return new ReadableStream({
8760 start: controller => {
8761 const startCapability = Promise.withResolvers();
8762 this.streamControllers[streamId] = {
8763 controller,
8764 startCall: startCapability,
8765 pullCall: null,
8766 cancelCall: null,
8767 isClosed: false
8768 };
8769 comObj.postMessage({
8770 sourceName,
8771 targetName,
8772 action: actionName,
8773 streamId,
8774 data,
8775 desiredSize: controller.desiredSize
8776 }, transfers);
8777 return startCapability.promise;
8778 },
8779 pull: controller => {
8780 const pullCapability = Promise.withResolvers();
8781 this.streamControllers[streamId].pullCall = pullCapability;
8782 comObj.postMessage({
8783 sourceName,
8784 targetName,
8785 stream: StreamKind.PULL,
8786 streamId,
8787 desiredSize: controller.desiredSize
8788 });
8789 return pullCapability.promise;
8790 },
8791 cancel: reason => {
8792 assert(reason instanceof Error, "cancel must have a valid reason");
8793 const cancelCapability = Promise.withResolvers();
8794 this.streamControllers[streamId].cancelCall = cancelCapability;
8795 this.streamControllers[streamId].isClosed = true;
8796 comObj.postMessage({
8797 sourceName,
8798 targetName,
8799 stream: StreamKind.CANCEL,
8800 streamId,
8801 reason: wrapReason(reason)
8802 });
8803 return cancelCapability.promise;
8804 }
8805 }, queueingStrategy);
8806 }
8807 #createStreamSink(data) {
8808 const streamId = data.streamId,
8809 sourceName = this.sourceName,
8810 targetName = data.sourceName,
8811 comObj = this.comObj;
8812 const self = this,
8813 action = this.actionHandler[data.action];
8814 const streamSink = {
8815 enqueue(chunk, size = 1, transfers) {
8816 if (this.isCancelled) {
8817 return;
8818 }
8819 const lastDesiredSize = this.desiredSize;
8820 this.desiredSize -= size;
8821 if (lastDesiredSize > 0 && this.desiredSize <= 0) {
8822 this.sinkCapability = Promise.withResolvers();
8823 this.ready = this.sinkCapability.promise;
8824 }
8825 comObj.postMessage({
8826 sourceName,
8827 targetName,
8828 stream: StreamKind.ENQUEUE,
8829 streamId,
8830 chunk
8831 }, transfers);
8832 },
8833 close() {
8834 if (this.isCancelled) {
8835 return;
8836 }
8837 this.isCancelled = true;
8838 comObj.postMessage({
8839 sourceName,
8840 targetName,
8841 stream: StreamKind.CLOSE,
8842 streamId
8843 });
8844 delete self.streamSinks[streamId];
8845 },
8846 error(reason) {
8847 assert(reason instanceof Error, "error must have a valid reason");
8848 if (this.isCancelled) {
8849 return;
8850 }
8851 this.isCancelled = true;
8852 comObj.postMessage({
8853 sourceName,
8854 targetName,
8855 stream: StreamKind.ERROR,
8856 streamId,
8857 reason: wrapReason(reason)
8858 });
8859 },
8860 sinkCapability: Promise.withResolvers(),
8861 onPull: null,
8862 onCancel: null,
8863 isCancelled: false,
8864 desiredSize: data.desiredSize,
8865 ready: null
8866 };
8867 streamSink.sinkCapability.resolve();
8868 streamSink.ready = streamSink.sinkCapability.promise;
8869 this.streamSinks[streamId] = streamSink;
8870 new Promise(function (resolve) {
8871 resolve(action(data.data, streamSink));
8872 }).then(function () {
8873 comObj.postMessage({
8874 sourceName,
8875 targetName,
8876 stream: StreamKind.START_COMPLETE,
8877 streamId,
8878 success: true
8879 });
8880 }, function (reason) {
8881 comObj.postMessage({
8882 sourceName,
8883 targetName,
8884 stream: StreamKind.START_COMPLETE,
8885 streamId,
8886 reason: wrapReason(reason)
8887 });
8888 });
8889 }
8890 #processStreamMessage(data) {
8891 const streamId = data.streamId,
8892 sourceName = this.sourceName,
8893 targetName = data.sourceName,
8894 comObj = this.comObj;
8895 const streamController = this.streamControllers[streamId],
8896 streamSink = this.streamSinks[streamId];
8897 switch (data.stream) {
8898 case StreamKind.START_COMPLETE:
8899 if (data.success) {
8900 streamController.startCall.resolve();
8901 } else {
8902 streamController.startCall.reject(wrapReason(data.reason));
8903 }
8904 break;
8905 case StreamKind.PULL_COMPLETE:
8906 if (data.success) {
8907 streamController.pullCall.resolve();
8908 } else {
8909 streamController.pullCall.reject(wrapReason(data.reason));
8910 }
8911 break;
8912 case StreamKind.PULL:
8913 if (!streamSink) {
8914 comObj.postMessage({
8915 sourceName,
8916 targetName,
8917 stream: StreamKind.PULL_COMPLETE,
8918 streamId,
8919 success: true
8920 });
8921 break;
8922 }
8923 if (streamSink.desiredSize <= 0 && data.desiredSize > 0) {
8924 streamSink.sinkCapability.resolve();
8925 }
8926 streamSink.desiredSize = data.desiredSize;
8927 new Promise(function (resolve) {
8928 resolve(streamSink.onPull?.());
8929 }).then(function () {
8930 comObj.postMessage({
8931 sourceName,
8932 targetName,
8933 stream: StreamKind.PULL_COMPLETE,
8934 streamId,
8935 success: true
8936 });
8937 }, function (reason) {
8938 comObj.postMessage({
8939 sourceName,
8940 targetName,
8941 stream: StreamKind.PULL_COMPLETE,
8942 streamId,
8943 reason: wrapReason(reason)
8944 });
8945 });
8946 break;
8947 case StreamKind.ENQUEUE:
8948 assert(streamController, "enqueue should have stream controller");
8949 if (streamController.isClosed) {
8950 break;
8951 }
8952 streamController.controller.enqueue(data.chunk);
8953 break;
8954 case StreamKind.CLOSE:
8955 assert(streamController, "close should have stream controller");
8956 if (streamController.isClosed) {
8957 break;
8958 }
8959 streamController.isClosed = true;
8960 streamController.controller.close();
8961 this.#deleteStreamController(streamController, streamId);
8962 break;
8963 case StreamKind.ERROR:
8964 assert(streamController, "error should have stream controller");
8965 streamController.controller.error(wrapReason(data.reason));
8966 this.#deleteStreamController(streamController, streamId);
8967 break;
8968 case StreamKind.CANCEL_COMPLETE:
8969 if (data.success) {
8970 streamController.cancelCall.resolve();
8971 } else {
8972 streamController.cancelCall.reject(wrapReason(data.reason));
8973 }
8974 this.#deleteStreamController(streamController, streamId);
8975 break;
8976 case StreamKind.CANCEL:
8977 if (!streamSink) {
8978 break;
8979 }
8980 new Promise(function (resolve) {
8981 resolve(streamSink.onCancel?.(wrapReason(data.reason)));
8982 }).then(function () {
8983 comObj.postMessage({
8984 sourceName,
8985 targetName,
8986 stream: StreamKind.CANCEL_COMPLETE,
8987 streamId,
8988 success: true
8989 });
8990 }, function (reason) {
8991 comObj.postMessage({
8992 sourceName,
8993 targetName,
8994 stream: StreamKind.CANCEL_COMPLETE,
8995 streamId,
8996 reason: wrapReason(reason)
8997 });
8998 });
8999 streamSink.sinkCapability.reject(wrapReason(data.reason));
9000 streamSink.isCancelled = true;
9001 delete this.streamSinks[streamId];
9002 break;
9003 default:
9004 throw new Error("Unexpected stream case");
9005 }
9006 }
9007 async #deleteStreamController(streamController, streamId) {
9008 await Promise.allSettled([streamController.startCall?.promise, streamController.pullCall?.promise, streamController.cancelCall?.promise]);
9009 delete this.streamControllers[streamId];
9010 }
9011 destroy() {
9012 this.comObj.removeEventListener("message", this._onComObjOnMessage);
9013 }
9014 }
9015
9016 ;// ./src/display/metadata.js
9017
9018 class Metadata {
9019 #metadataMap;
9020 #data;
9021 constructor({
9022 parsedData,
9023 rawData
9024 }) {
9025 this.#metadataMap = parsedData;
9026 this.#data = rawData;
9027 }
9028 getRaw() {
9029 return this.#data;
9030 }
9031 get(name) {
9032 return this.#metadataMap.get(name) ?? null;
9033 }
9034 getAll() {
9035 return objectFromMap(this.#metadataMap);
9036 }
9037 has(name) {
9038 return this.#metadataMap.has(name);
9039 }
9040 }
9041
9042 ;// ./src/display/optional_content_config.js
9043
9044
9045 const INTERNAL = Symbol("INTERNAL");
9046 class OptionalContentGroup {
9047 #isDisplay = false;
9048 #isPrint = false;
9049 #userSet = false;
9050 #visible = true;
9051 constructor(renderingIntent, {
9052 name,
9053 intent,
9054 usage
9055 }) {
9056 this.#isDisplay = !!(renderingIntent & RenderingIntentFlag.DISPLAY);
9057 this.#isPrint = !!(renderingIntent & RenderingIntentFlag.PRINT);
9058 this.name = name;
9059 this.intent = intent;
9060 this.usage = usage;
9061 }
9062 get visible() {
9063 if (this.#userSet) {
9064 return this.#visible;
9065 }
9066 if (!this.#visible) {
9067 return false;
9068 }
9069 const {
9070 print,
9071 view
9072 } = this.usage;
9073 if (this.#isDisplay) {
9074 return view?.viewState !== "OFF";
9075 } else if (this.#isPrint) {
9076 return print?.printState !== "OFF";
9077 }
9078 return true;
9079 }
9080 _setVisible(internal, visible, userSet = false) {
9081 if (internal !== INTERNAL) {
9082 unreachable("Internal method `_setVisible` called.");
9083 }
9084 this.#userSet = userSet;
9085 this.#visible = visible;
9086 }
9087 }
9088 class OptionalContentConfig {
9089 #cachedGetHash = null;
9090 #groups = new Map();
9091 #initialHash = null;
9092 #order = null;
9093 constructor(data, renderingIntent = RenderingIntentFlag.DISPLAY) {
9094 this.renderingIntent = renderingIntent;
9095 this.name = null;
9096 this.creator = null;
9097 if (data === null) {
9098 return;
9099 }
9100 this.name = data.name;
9101 this.creator = data.creator;
9102 this.#order = data.order;
9103 for (const group of data.groups) {
9104 this.#groups.set(group.id, new OptionalContentGroup(renderingIntent, group));
9105 }
9106 if (data.baseState === "OFF") {
9107 for (const group of this.#groups.values()) {
9108 group._setVisible(INTERNAL, false);
9109 }
9110 }
9111 for (const on of data.on) {
9112 this.#groups.get(on)._setVisible(INTERNAL, true);
9113 }
9114 for (const off of data.off) {
9115 this.#groups.get(off)._setVisible(INTERNAL, false);
9116 }
9117 this.#initialHash = this.getHash();
9118 }
9119 #evaluateVisibilityExpression(array) {
9120 const length = array.length;
9121 if (length < 2) {
9122 return true;
9123 }
9124 const operator = array[0];
9125 for (let i = 1; i < length; i++) {
9126 const element = array[i];
9127 let state;
9128 if (Array.isArray(element)) {
9129 state = this.#evaluateVisibilityExpression(element);
9130 } else if (this.#groups.has(element)) {
9131 state = this.#groups.get(element).visible;
9132 } else {
9133 warn(`Optional content group not found: ${element}`);
9134 return true;
9135 }
9136 switch (operator) {
9137 case "And":
9138 if (!state) {
9139 return false;
9140 }
9141 break;
9142 case "Or":
9143 if (state) {
9144 return true;
9145 }
9146 break;
9147 case "Not":
9148 return !state;
9149 default:
9150 return true;
9151 }
9152 }
9153 return operator === "And";
9154 }
9155 isVisible(group) {
9156 if (this.#groups.size === 0) {
9157 return true;
9158 }
9159 if (!group) {
9160 info("Optional content group not defined.");
9161 return true;
9162 }
9163 if (group.type === "OCG") {
9164 if (!this.#groups.has(group.id)) {
9165 warn(`Optional content group not found: ${group.id}`);
9166 return true;
9167 }
9168 return this.#groups.get(group.id).visible;
9169 } else if (group.type === "OCMD") {
9170 if (group.expression) {
9171 return this.#evaluateVisibilityExpression(group.expression);
9172 }
9173 if (!group.policy || group.policy === "AnyOn") {
9174 for (const id of group.ids) {
9175 if (!this.#groups.has(id)) {
9176 warn(`Optional content group not found: ${id}`);
9177 return true;
9178 }
9179 if (this.#groups.get(id).visible) {
9180 return true;
9181 }
9182 }
9183 return false;
9184 } else if (group.policy === "AllOn") {
9185 for (const id of group.ids) {
9186 if (!this.#groups.has(id)) {
9187 warn(`Optional content group not found: ${id}`);
9188 return true;
9189 }
9190 if (!this.#groups.get(id).visible) {
9191 return false;
9192 }
9193 }
9194 return true;
9195 } else if (group.policy === "AnyOff") {
9196 for (const id of group.ids) {
9197 if (!this.#groups.has(id)) {
9198 warn(`Optional content group not found: ${id}`);
9199 return true;
9200 }
9201 if (!this.#groups.get(id).visible) {
9202 return true;
9203 }
9204 }
9205 return false;
9206 } else if (group.policy === "AllOff") {
9207 for (const id of group.ids) {
9208 if (!this.#groups.has(id)) {
9209 warn(`Optional content group not found: ${id}`);
9210 return true;
9211 }
9212 if (this.#groups.get(id).visible) {
9213 return false;
9214 }
9215 }
9216 return true;
9217 }
9218 warn(`Unknown optional content policy ${group.policy}.`);
9219 return true;
9220 }
9221 warn(`Unknown group type ${group.type}.`);
9222 return true;
9223 }
9224 setVisibility(id, visible = true) {
9225 const group = this.#groups.get(id);
9226 if (!group) {
9227 warn(`Optional content group not found: ${id}`);
9228 return;
9229 }
9230 group._setVisible(INTERNAL, !!visible, true);
9231 this.#cachedGetHash = null;
9232 }
9233 setOCGState({
9234 state,
9235 preserveRB
9236 }) {
9237 let operator;
9238 for (const elem of state) {
9239 switch (elem) {
9240 case "ON":
9241 case "OFF":
9242 case "Toggle":
9243 operator = elem;
9244 continue;
9245 }
9246 const group = this.#groups.get(elem);
9247 if (!group) {
9248 continue;
9249 }
9250 switch (operator) {
9251 case "ON":
9252 group._setVisible(INTERNAL, true);
9253 break;
9254 case "OFF":
9255 group._setVisible(INTERNAL, false);
9256 break;
9257 case "Toggle":
9258 group._setVisible(INTERNAL, !group.visible);
9259 break;
9260 }
9261 }
9262 this.#cachedGetHash = null;
9263 }
9264 get hasInitialVisibility() {
9265 return this.#initialHash === null || this.getHash() === this.#initialHash;
9266 }
9267 getOrder() {
9268 if (!this.#groups.size) {
9269 return null;
9270 }
9271 if (this.#order) {
9272 return this.#order.slice();
9273 }
9274 return [...this.#groups.keys()];
9275 }
9276 getGroups() {
9277 return this.#groups.size > 0 ? objectFromMap(this.#groups) : null;
9278 }
9279 getGroup(id) {
9280 return this.#groups.get(id) || null;
9281 }
9282 getHash() {
9283 if (this.#cachedGetHash !== null) {
9284 return this.#cachedGetHash;
9285 }
9286 const hash = new MurmurHash3_64();
9287 for (const [id, group] of this.#groups) {
9288 hash.update(`${id}:${group.visible}`);
9289 }
9290 return this.#cachedGetHash = hash.hexdigest();
9291 }
9292 }
9293
9294 ;// ./src/display/transport_stream.js
9295
9296
9297 class PDFDataTransportStream {
9298 constructor(pdfDataRangeTransport, {
9299 disableRange = false,
9300 disableStream = false
9301 }) {
9302 assert(pdfDataRangeTransport, 'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');
9303 const {
9304 length,
9305 initialData,
9306 progressiveDone,
9307 contentDispositionFilename
9308 } = pdfDataRangeTransport;
9309 this._queuedChunks = [];
9310 this._progressiveDone = progressiveDone;
9311 this._contentDispositionFilename = contentDispositionFilename;
9312 if (initialData?.length > 0) {
9313 const buffer = initialData instanceof Uint8Array && initialData.byteLength === initialData.buffer.byteLength ? initialData.buffer : new Uint8Array(initialData).buffer;
9314 this._queuedChunks.push(buffer);
9315 }
9316 this._pdfDataRangeTransport = pdfDataRangeTransport;
9317 this._isStreamingSupported = !disableStream;
9318 this._isRangeSupported = !disableRange;
9319 this._contentLength = length;
9320 this._fullRequestReader = null;
9321 this._rangeReaders = [];
9322 pdfDataRangeTransport.addRangeListener((begin, chunk) => {
9323 this._onReceiveData({
9324 begin,
9325 chunk
9326 });
9327 });
9328 pdfDataRangeTransport.addProgressListener((loaded, total) => {
9329 this._onProgress({
9330 loaded,
9331 total
9332 });
9333 });
9334 pdfDataRangeTransport.addProgressiveReadListener(chunk => {
9335 this._onReceiveData({
9336 chunk
9337 });
9338 });
9339 pdfDataRangeTransport.addProgressiveDoneListener(() => {
9340 this._onProgressiveDone();
9341 });
9342 pdfDataRangeTransport.transportReady();
9343 }
9344 _onReceiveData({
9345 begin,
9346 chunk
9347 }) {
9348 const buffer = chunk instanceof Uint8Array && chunk.byteLength === chunk.buffer.byteLength ? chunk.buffer : new Uint8Array(chunk).buffer;
9349 if (begin === undefined) {
9350 if (this._fullRequestReader) {
9351 this._fullRequestReader._enqueue(buffer);
9352 } else {
9353 this._queuedChunks.push(buffer);
9354 }
9355 } else {
9356 const found = this._rangeReaders.some(function (rangeReader) {
9357 if (rangeReader._begin !== begin) {
9358 return false;
9359 }
9360 rangeReader._enqueue(buffer);
9361 return true;
9362 });
9363 assert(found, "_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.");
9364 }
9365 }
9366 get _progressiveDataLength() {
9367 return this._fullRequestReader?._loaded ?? 0;
9368 }
9369 _onProgress(evt) {
9370 if (evt.total === undefined) {
9371 this._rangeReaders[0]?.onProgress?.({
9372 loaded: evt.loaded
9373 });
9374 } else {
9375 this._fullRequestReader?.onProgress?.({
9376 loaded: evt.loaded,
9377 total: evt.total
9378 });
9379 }
9380 }
9381 _onProgressiveDone() {
9382 this._fullRequestReader?.progressiveDone();
9383 this._progressiveDone = true;
9384 }
9385 _removeRangeReader(reader) {
9386 const i = this._rangeReaders.indexOf(reader);
9387 if (i >= 0) {
9388 this._rangeReaders.splice(i, 1);
9389 }
9390 }
9391 getFullReader() {
9392 assert(!this._fullRequestReader, "PDFDataTransportStream.getFullReader can only be called once.");
9393 const queuedChunks = this._queuedChunks;
9394 this._queuedChunks = null;
9395 return new PDFDataTransportStreamReader(this, queuedChunks, this._progressiveDone, this._contentDispositionFilename);
9396 }
9397 getRangeReader(begin, end) {
9398 if (end <= this._progressiveDataLength) {
9399 return null;
9400 }
9401 const reader = new PDFDataTransportStreamRangeReader(this, begin, end);
9402 this._pdfDataRangeTransport.requestDataRange(begin, end);
9403 this._rangeReaders.push(reader);
9404 return reader;
9405 }
9406 cancelAllRequests(reason) {
9407 this._fullRequestReader?.cancel(reason);
9408 for (const reader of this._rangeReaders.slice(0)) {
9409 reader.cancel(reason);
9410 }
9411 this._pdfDataRangeTransport.abort();
9412 }
9413 }
9414 class PDFDataTransportStreamReader {
9415 constructor(stream, queuedChunks, progressiveDone = false, contentDispositionFilename = null) {
9416 this._stream = stream;
9417 this._done = progressiveDone || false;
9418 this._filename = isPdfFile(contentDispositionFilename) ? contentDispositionFilename : null;
9419 this._queuedChunks = queuedChunks || [];
9420 this._loaded = 0;
9421 for (const chunk of this._queuedChunks) {
9422 this._loaded += chunk.byteLength;
9423 }
9424 this._requests = [];
9425 this._headersReady = Promise.resolve();
9426 stream._fullRequestReader = this;
9427 this.onProgress = null;
9428 }
9429 _enqueue(chunk) {
9430 if (this._done) {
9431 return;
9432 }
9433 if (this._requests.length > 0) {
9434 const requestCapability = this._requests.shift();
9435 requestCapability.resolve({
9436 value: chunk,
9437 done: false
9438 });
9439 } else {
9440 this._queuedChunks.push(chunk);
9441 }
9442 this._loaded += chunk.byteLength;
9443 }
9444 get headersReady() {
9445 return this._headersReady;
9446 }
9447 get filename() {
9448 return this._filename;
9449 }
9450 get isRangeSupported() {
9451 return this._stream._isRangeSupported;
9452 }
9453 get isStreamingSupported() {
9454 return this._stream._isStreamingSupported;
9455 }
9456 get contentLength() {
9457 return this._stream._contentLength;
9458 }
9459 async read() {
9460 if (this._queuedChunks.length > 0) {
9461 const chunk = this._queuedChunks.shift();
9462 return {
9463 value: chunk,
9464 done: false
9465 };
9466 }
9467 if (this._done) {
9468 return {
9469 value: undefined,
9470 done: true
9471 };
9472 }
9473 const requestCapability = Promise.withResolvers();
9474 this._requests.push(requestCapability);
9475 return requestCapability.promise;
9476 }
9477 cancel(reason) {
9478 this._done = true;
9479 for (const requestCapability of this._requests) {
9480 requestCapability.resolve({
9481 value: undefined,
9482 done: true
9483 });
9484 }
9485 this._requests.length = 0;
9486 }
9487 progressiveDone() {
9488 if (this._done) {
9489 return;
9490 }
9491 this._done = true;
9492 }
9493 }
9494 class PDFDataTransportStreamRangeReader {
9495 constructor(stream, begin, end) {
9496 this._stream = stream;
9497 this._begin = begin;
9498 this._end = end;
9499 this._queuedChunk = null;
9500 this._requests = [];
9501 this._done = false;
9502 this.onProgress = null;
9503 }
9504 _enqueue(chunk) {
9505 if (this._done) {
9506 return;
9507 }
9508 if (this._requests.length === 0) {
9509 this._queuedChunk = chunk;
9510 } else {
9511 const requestsCapability = this._requests.shift();
9512 requestsCapability.resolve({
9513 value: chunk,
9514 done: false
9515 });
9516 for (const requestCapability of this._requests) {
9517 requestCapability.resolve({
9518 value: undefined,
9519 done: true
9520 });
9521 }
9522 this._requests.length = 0;
9523 }
9524 this._done = true;
9525 this._stream._removeRangeReader(this);
9526 }
9527 get isStreamingSupported() {
9528 return false;
9529 }
9530 async read() {
9531 if (this._queuedChunk) {
9532 const chunk = this._queuedChunk;
9533 this._queuedChunk = null;
9534 return {
9535 value: chunk,
9536 done: false
9537 };
9538 }
9539 if (this._done) {
9540 return {
9541 value: undefined,
9542 done: true
9543 };
9544 }
9545 const requestCapability = Promise.withResolvers();
9546 this._requests.push(requestCapability);
9547 return requestCapability.promise;
9548 }
9549 cancel(reason) {
9550 this._done = true;
9551 for (const requestCapability of this._requests) {
9552 requestCapability.resolve({
9553 value: undefined,
9554 done: true
9555 });
9556 }
9557 this._requests.length = 0;
9558 this._stream._removeRangeReader(this);
9559 }
9560 }
9561
9562 ;// ./src/display/content_disposition.js
9563
9564 function getFilenameFromContentDispositionHeader(contentDisposition) {
9565 let needsEncodingFixup = true;
9566 let tmp = toParamRegExp("filename\\*", "i").exec(contentDisposition);
9567 if (tmp) {
9568 tmp = tmp[1];
9569 let filename = rfc2616unquote(tmp);
9570 filename = unescape(filename);
9571 filename = rfc5987decode(filename);
9572 filename = rfc2047decode(filename);
9573 return fixupEncoding(filename);
9574 }
9575 tmp = rfc2231getparam(contentDisposition);
9576 if (tmp) {
9577 const filename = rfc2047decode(tmp);
9578 return fixupEncoding(filename);
9579 }
9580 tmp = toParamRegExp("filename", "i").exec(contentDisposition);
9581 if (tmp) {
9582 tmp = tmp[1];
9583 let filename = rfc2616unquote(tmp);
9584 filename = rfc2047decode(filename);
9585 return fixupEncoding(filename);
9586 }
9587 function toParamRegExp(attributePattern, flags) {
9588 return new RegExp("(?:^|;)\\s*" + attributePattern + "\\s*=\\s*" + "(" + '[^";\\s][^;\\s]*' + "|" + '"(?:[^"\\\\]|\\\\"?)+"?' + ")", flags);
9589 }
9590 function textdecode(encoding, value) {
9591 if (encoding) {
9592 if (!/^[\x00-\xFF]+$/.test(value)) {
9593 return value;
9594 }
9595 try {
9596 const decoder = new TextDecoder(encoding, {
9597 fatal: true
9598 });
9599 const buffer = stringToBytes(value);
9600 value = decoder.decode(buffer);
9601 needsEncodingFixup = false;
9602 } catch {}
9603 }
9604 return value;
9605 }
9606 function fixupEncoding(value) {
9607 if (needsEncodingFixup && /[\x80-\xff]/.test(value)) {
9608 value = textdecode("utf-8", value);
9609 if (needsEncodingFixup) {
9610 value = textdecode("iso-8859-1", value);
9611 }
9612 }
9613 return value;
9614 }
9615 function rfc2231getparam(contentDispositionStr) {
9616 const matches = [];
9617 let match;
9618 const iter = toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)", "ig");
9619 while ((match = iter.exec(contentDispositionStr)) !== null) {
9620 let [, n, quot, part] = match;
9621 n = parseInt(n, 10);
9622 if (n in matches) {
9623 if (n === 0) {
9624 break;
9625 }
9626 continue;
9627 }
9628 matches[n] = [quot, part];
9629 }
9630 const parts = [];
9631 for (let n = 0; n < matches.length; ++n) {
9632 if (!(n in matches)) {
9633 break;
9634 }
9635 let [quot, part] = matches[n];
9636 part = rfc2616unquote(part);
9637 if (quot) {
9638 part = unescape(part);
9639 if (n === 0) {
9640 part = rfc5987decode(part);
9641 }
9642 }
9643 parts.push(part);
9644 }
9645 return parts.join("");
9646 }
9647 function rfc2616unquote(value) {
9648 if (value.startsWith('"')) {
9649 const parts = value.slice(1).split('\\"');
9650 for (let i = 0; i < parts.length; ++i) {
9651 const quotindex = parts[i].indexOf('"');
9652 if (quotindex !== -1) {
9653 parts[i] = parts[i].slice(0, quotindex);
9654 parts.length = i + 1;
9655 }
9656 parts[i] = parts[i].replaceAll(/\\(.)/g, "$1");
9657 }
9658 value = parts.join('"');
9659 }
9660 return value;
9661 }
9662 function rfc5987decode(extvalue) {
9663 const encodingend = extvalue.indexOf("'");
9664 if (encodingend === -1) {
9665 return extvalue;
9666 }
9667 const encoding = extvalue.slice(0, encodingend);
9668 const langvalue = extvalue.slice(encodingend + 1);
9669 const value = langvalue.replace(/^[^']*'/, "");
9670 return textdecode(encoding, value);
9671 }
9672 function rfc2047decode(value) {
9673 if (!value.startsWith("=?") || /[\x00-\x19\x80-\xff]/.test(value)) {
9674 return value;
9675 }
9676 return value.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g, function (matches, charset, encoding, text) {
9677 if (encoding === "q" || encoding === "Q") {
9678 text = text.replaceAll("_", " ");
9679 text = text.replaceAll(/=([0-9a-fA-F]{2})/g, function (match, hex) {
9680 return String.fromCharCode(parseInt(hex, 16));
9681 });
9682 return textdecode(charset, text);
9683 }
9684 try {
9685 text = atob(text);
9686 } catch {}
9687 return textdecode(charset, text);
9688 });
9689 }
9690 return "";
9691 }
9692
9693 ;// ./src/display/network_utils.js
9694
9695
9696
9697 function createHeaders(isHttp, httpHeaders) {
9698 const headers = new Headers();
9699 if (!isHttp || !httpHeaders || typeof httpHeaders !== "object") {
9700 return headers;
9701 }
9702 for (const key in httpHeaders) {
9703 const val = httpHeaders[key];
9704 if (val !== undefined) {
9705 headers.append(key, val);
9706 }
9707 }
9708 return headers;
9709 }
9710 function validateRangeRequestCapabilities({
9711 responseHeaders,
9712 isHttp,
9713 rangeChunkSize,
9714 disableRange
9715 }) {
9716 const returnValues = {
9717 allowRangeRequests: false,
9718 suggestedLength: undefined
9719 };
9720 const length = parseInt(responseHeaders.get("Content-Length"), 10);
9721 if (!Number.isInteger(length)) {
9722 return returnValues;
9723 }
9724 returnValues.suggestedLength = length;
9725 if (length <= 2 * rangeChunkSize) {
9726 return returnValues;
9727 }
9728 if (disableRange || !isHttp) {
9729 return returnValues;
9730 }
9731 if (responseHeaders.get("Accept-Ranges") !== "bytes") {
9732 return returnValues;
9733 }
9734 const contentEncoding = responseHeaders.get("Content-Encoding") || "identity";
9735 if (contentEncoding !== "identity") {
9736 return returnValues;
9737 }
9738 returnValues.allowRangeRequests = true;
9739 return returnValues;
9740 }
9741 function extractFilenameFromHeader(responseHeaders) {
9742 const contentDisposition = responseHeaders.get("Content-Disposition");
9743 if (contentDisposition) {
9744 let filename = getFilenameFromContentDispositionHeader(contentDisposition);
9745 if (filename.includes("%")) {
9746 try {
9747 filename = decodeURIComponent(filename);
9748 } catch {}
9749 }
9750 if (isPdfFile(filename)) {
9751 return filename;
9752 }
9753 }
9754 return null;
9755 }
9756 function createResponseStatusError(status, url) {
9757 if (status === 404 || status === 0 && url.startsWith("file:")) {
9758 return new MissingPDFException('Missing PDF "' + url + '".');
9759 }
9760 return new UnexpectedResponseException(`Unexpected server response (${status}) while retrieving PDF "${url}".`, status);
9761 }
9762 function validateResponseStatus(status) {
9763 return status === 200 || status === 206;
9764 }
9765
9766 ;// ./src/display/fetch_stream.js
9767
9768
9769 function createFetchOptions(headers, withCredentials, abortController) {
9770 return {
9771 method: "GET",
9772 headers,
9773 signal: abortController.signal,
9774 mode: "cors",
9775 credentials: withCredentials ? "include" : "same-origin",
9776 redirect: "follow"
9777 };
9778 }
9779 function getArrayBuffer(val) {
9780 if (val instanceof Uint8Array) {
9781 return val.buffer;
9782 }
9783 if (val instanceof ArrayBuffer) {
9784 return val;
9785 }
9786 warn(`getArrayBuffer - unexpected data format: ${val}`);
9787 return new Uint8Array(val).buffer;
9788 }
9789 class PDFFetchStream {
9790 constructor(source) {
9791 this.source = source;
9792 this.isHttp = /^https?:/i.test(source.url);
9793 this.headers = createHeaders(this.isHttp, source.httpHeaders);
9794 this._fullRequestReader = null;
9795 this._rangeRequestReaders = [];
9796 }
9797 get _progressiveDataLength() {
9798 return this._fullRequestReader?._loaded ?? 0;
9799 }
9800 getFullReader() {
9801 assert(!this._fullRequestReader, "PDFFetchStream.getFullReader can only be called once.");
9802 this._fullRequestReader = new PDFFetchStreamReader(this);
9803 return this._fullRequestReader;
9804 }
9805 getRangeReader(begin, end) {
9806 if (end <= this._progressiveDataLength) {
9807 return null;
9808 }
9809 const reader = new PDFFetchStreamRangeReader(this, begin, end);
9810 this._rangeRequestReaders.push(reader);
9811 return reader;
9812 }
9813 cancelAllRequests(reason) {
9814 this._fullRequestReader?.cancel(reason);
9815 for (const reader of this._rangeRequestReaders.slice(0)) {
9816 reader.cancel(reason);
9817 }
9818 }
9819 }
9820 class PDFFetchStreamReader {
9821 constructor(stream) {
9822 this._stream = stream;
9823 this._reader = null;
9824 this._loaded = 0;
9825 this._filename = null;
9826 const source = stream.source;
9827 this._withCredentials = source.withCredentials || false;
9828 this._contentLength = source.length;
9829 this._headersCapability = Promise.withResolvers();
9830 this._disableRange = source.disableRange || false;
9831 this._rangeChunkSize = source.rangeChunkSize;
9832 if (!this._rangeChunkSize && !this._disableRange) {
9833 this._disableRange = true;
9834 }
9835 this._abortController = new AbortController();
9836 this._isStreamingSupported = !source.disableStream;
9837 this._isRangeSupported = !source.disableRange;
9838 const headers = new Headers(stream.headers);
9839 const url = source.url;
9840 fetch(url, createFetchOptions(headers, this._withCredentials, this._abortController)).then(response => {
9841 if (!validateResponseStatus(response.status)) {
9842 throw createResponseStatusError(response.status, url);
9843 }
9844 this._reader = response.body.getReader();
9845 this._headersCapability.resolve();
9846 const responseHeaders = response.headers;
9847 const {
9848 allowRangeRequests,
9849 suggestedLength
9850 } = validateRangeRequestCapabilities({
9851 responseHeaders,
9852 isHttp: stream.isHttp,
9853 rangeChunkSize: this._rangeChunkSize,
9854 disableRange: this._disableRange
9855 });
9856 this._isRangeSupported = allowRangeRequests;
9857 this._contentLength = suggestedLength || this._contentLength;
9858 this._filename = extractFilenameFromHeader(responseHeaders);
9859 if (!this._isStreamingSupported && this._isRangeSupported) {
9860 this.cancel(new AbortException("Streaming is disabled."));
9861 }
9862 }).catch(this._headersCapability.reject);
9863 this.onProgress = null;
9864 }
9865 get headersReady() {
9866 return this._headersCapability.promise;
9867 }
9868 get filename() {
9869 return this._filename;
9870 }
9871 get contentLength() {
9872 return this._contentLength;
9873 }
9874 get isRangeSupported() {
9875 return this._isRangeSupported;
9876 }
9877 get isStreamingSupported() {
9878 return this._isStreamingSupported;
9879 }
9880 async read() {
9881 await this._headersCapability.promise;
9882 const {
9883 value,
9884 done
9885 } = await this._reader.read();
9886 if (done) {
9887 return {
9888 value,
9889 done
9890 };
9891 }
9892 this._loaded += value.byteLength;
9893 this.onProgress?.({
9894 loaded: this._loaded,
9895 total: this._contentLength
9896 });
9897 return {
9898 value: getArrayBuffer(value),
9899 done: false
9900 };
9901 }
9902 cancel(reason) {
9903 this._reader?.cancel(reason);
9904 this._abortController.abort();
9905 }
9906 }
9907 class PDFFetchStreamRangeReader {
9908 constructor(stream, begin, end) {
9909 this._stream = stream;
9910 this._reader = null;
9911 this._loaded = 0;
9912 const source = stream.source;
9913 this._withCredentials = source.withCredentials || false;
9914 this._readCapability = Promise.withResolvers();
9915 this._isStreamingSupported = !source.disableStream;
9916 this._abortController = new AbortController();
9917 const headers = new Headers(stream.headers);
9918 headers.append("Range", `bytes=${begin}-${end - 1}`);
9919 const url = source.url;
9920 fetch(url, createFetchOptions(headers, this._withCredentials, this._abortController)).then(response => {
9921 if (!validateResponseStatus(response.status)) {
9922 throw createResponseStatusError(response.status, url);
9923 }
9924 this._readCapability.resolve();
9925 this._reader = response.body.getReader();
9926 }).catch(this._readCapability.reject);
9927 this.onProgress = null;
9928 }
9929 get isStreamingSupported() {
9930 return this._isStreamingSupported;
9931 }
9932 async read() {
9933 await this._readCapability.promise;
9934 const {
9935 value,
9936 done
9937 } = await this._reader.read();
9938 if (done) {
9939 return {
9940 value,
9941 done
9942 };
9943 }
9944 this._loaded += value.byteLength;
9945 this.onProgress?.({
9946 loaded: this._loaded
9947 });
9948 return {
9949 value: getArrayBuffer(value),
9950 done: false
9951 };
9952 }
9953 cancel(reason) {
9954 this._reader?.cancel(reason);
9955 this._abortController.abort();
9956 }
9957 }
9958
9959 ;// ./src/display/network.js
9960
9961
9962 const OK_RESPONSE = 200;
9963 const PARTIAL_CONTENT_RESPONSE = 206;
9964 function network_getArrayBuffer(xhr) {
9965 const data = xhr.response;
9966 if (typeof data !== "string") {
9967 return data;
9968 }
9969 return stringToBytes(data).buffer;
9970 }
9971 class NetworkManager {
9972 constructor({
9973 url,
9974 httpHeaders,
9975 withCredentials
9976 }) {
9977 this.url = url;
9978 this.isHttp = /^https?:/i.test(url);
9979 this.headers = createHeaders(this.isHttp, httpHeaders);
9980 this.withCredentials = withCredentials || false;
9981 this.currXhrId = 0;
9982 this.pendingRequests = Object.create(null);
9983 }
9984 requestRange(begin, end, listeners) {
9985 const args = {
9986 begin,
9987 end
9988 };
9989 for (const prop in listeners) {
9990 args[prop] = listeners[prop];
9991 }
9992 return this.request(args);
9993 }
9994 requestFull(listeners) {
9995 return this.request(listeners);
9996 }
9997 request(args) {
9998 const xhr = new XMLHttpRequest();
9999 const xhrId = this.currXhrId++;
10000 const pendingRequest = this.pendingRequests[xhrId] = {
10001 xhr
10002 };
10003 xhr.open("GET", this.url);
10004 xhr.withCredentials = this.withCredentials;
10005 for (const [key, val] of this.headers) {
10006 xhr.setRequestHeader(key, val);
10007 }
10008 if (this.isHttp && "begin" in args && "end" in args) {
10009 xhr.setRequestHeader("Range", `bytes=${args.begin}-${args.end - 1}`);
10010 pendingRequest.expectedStatus = PARTIAL_CONTENT_RESPONSE;
10011 } else {
10012 pendingRequest.expectedStatus = OK_RESPONSE;
10013 }
10014 xhr.responseType = "arraybuffer";
10015 if (args.onError) {
10016 xhr.onerror = function (evt) {
10017 args.onError(xhr.status);
10018 };
10019 }
10020 xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);
10021 xhr.onprogress = this.onProgress.bind(this, xhrId);
10022 pendingRequest.onHeadersReceived = args.onHeadersReceived;
10023 pendingRequest.onDone = args.onDone;
10024 pendingRequest.onError = args.onError;
10025 pendingRequest.onProgress = args.onProgress;
10026 xhr.send(null);
10027 return xhrId;
10028 }
10029 onProgress(xhrId, evt) {
10030 const pendingRequest = this.pendingRequests[xhrId];
10031 if (!pendingRequest) {
10032 return;
10033 }
10034 pendingRequest.onProgress?.(evt);
10035 }
10036 onStateChange(xhrId, evt) {
10037 const pendingRequest = this.pendingRequests[xhrId];
10038 if (!pendingRequest) {
10039 return;
10040 }
10041 const xhr = pendingRequest.xhr;
10042 if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {
10043 pendingRequest.onHeadersReceived();
10044 delete pendingRequest.onHeadersReceived;
10045 }
10046 if (xhr.readyState !== 4) {
10047 return;
10048 }
10049 if (!(xhrId in this.pendingRequests)) {
10050 return;
10051 }
10052 delete this.pendingRequests[xhrId];
10053 if (xhr.status === 0 && this.isHttp) {
10054 pendingRequest.onError?.(xhr.status);
10055 return;
10056 }
10057 const xhrStatus = xhr.status || OK_RESPONSE;
10058 const ok_response_on_range_request = xhrStatus === OK_RESPONSE && pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;
10059 if (!ok_response_on_range_request && xhrStatus !== pendingRequest.expectedStatus) {
10060 pendingRequest.onError?.(xhr.status);
10061 return;
10062 }
10063 const chunk = network_getArrayBuffer(xhr);
10064 if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {
10065 const rangeHeader = xhr.getResponseHeader("Content-Range");
10066 const matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);
10067 pendingRequest.onDone({
10068 begin: parseInt(matches[1], 10),
10069 chunk
10070 });
10071 } else if (chunk) {
10072 pendingRequest.onDone({
10073 begin: 0,
10074 chunk
10075 });
10076 } else {
10077 pendingRequest.onError?.(xhr.status);
10078 }
10079 }
10080 getRequestXhr(xhrId) {
10081 return this.pendingRequests[xhrId].xhr;
10082 }
10083 isPendingRequest(xhrId) {
10084 return xhrId in this.pendingRequests;
10085 }
10086 abortRequest(xhrId) {
10087 const xhr = this.pendingRequests[xhrId].xhr;
10088 delete this.pendingRequests[xhrId];
10089 xhr.abort();
10090 }
10091 }
10092 class PDFNetworkStream {
10093 constructor(source) {
10094 this._source = source;
10095 this._manager = new NetworkManager(source);
10096 this._rangeChunkSize = source.rangeChunkSize;
10097 this._fullRequestReader = null;
10098 this._rangeRequestReaders = [];
10099 }
10100 _onRangeRequestReaderClosed(reader) {
10101 const i = this._rangeRequestReaders.indexOf(reader);
10102 if (i >= 0) {
10103 this._rangeRequestReaders.splice(i, 1);
10104 }
10105 }
10106 getFullReader() {
10107 assert(!this._fullRequestReader, "PDFNetworkStream.getFullReader can only be called once.");
10108 this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source);
10109 return this._fullRequestReader;
10110 }
10111 getRangeReader(begin, end) {
10112 const reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end);
10113 reader.onClosed = this._onRangeRequestReaderClosed.bind(this);
10114 this._rangeRequestReaders.push(reader);
10115 return reader;
10116 }
10117 cancelAllRequests(reason) {
10118 this._fullRequestReader?.cancel(reason);
10119 for (const reader of this._rangeRequestReaders.slice(0)) {
10120 reader.cancel(reason);
10121 }
10122 }
10123 }
10124 class PDFNetworkStreamFullRequestReader {
10125 constructor(manager, source) {
10126 this._manager = manager;
10127 const args = {
10128 onHeadersReceived: this._onHeadersReceived.bind(this),
10129 onDone: this._onDone.bind(this),
10130 onError: this._onError.bind(this),
10131 onProgress: this._onProgress.bind(this)
10132 };
10133 this._url = source.url;
10134 this._fullRequestId = manager.requestFull(args);
10135 this._headersCapability = Promise.withResolvers();
10136 this._disableRange = source.disableRange || false;
10137 this._contentLength = source.length;
10138 this._rangeChunkSize = source.rangeChunkSize;
10139 if (!this._rangeChunkSize && !this._disableRange) {
10140 this._disableRange = true;
10141 }
10142 this._isStreamingSupported = false;
10143 this._isRangeSupported = false;
10144 this._cachedChunks = [];
10145 this._requests = [];
10146 this._done = false;
10147 this._storedError = undefined;
10148 this._filename = null;
10149 this.onProgress = null;
10150 }
10151 _onHeadersReceived() {
10152 const fullRequestXhrId = this._fullRequestId;
10153 const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId);
10154 const responseHeaders = new Headers(fullRequestXhr.getAllResponseHeaders().trim().split(/[\r\n]+/).map(x => {
10155 const [key, ...val] = x.split(": ");
10156 return [key, val.join(": ")];
10157 }));
10158 const {
10159 allowRangeRequests,
10160 suggestedLength
10161 } = validateRangeRequestCapabilities({
10162 responseHeaders,
10163 isHttp: this._manager.isHttp,
10164 rangeChunkSize: this._rangeChunkSize,
10165 disableRange: this._disableRange
10166 });
10167 if (allowRangeRequests) {
10168 this._isRangeSupported = true;
10169 }
10170 this._contentLength = suggestedLength || this._contentLength;
10171 this._filename = extractFilenameFromHeader(responseHeaders);
10172 if (this._isRangeSupported) {
10173 this._manager.abortRequest(fullRequestXhrId);
10174 }
10175 this._headersCapability.resolve();
10176 }
10177 _onDone(data) {
10178 if (data) {
10179 if (this._requests.length > 0) {
10180 const requestCapability = this._requests.shift();
10181 requestCapability.resolve({
10182 value: data.chunk,
10183 done: false
10184 });
10185 } else {
10186 this._cachedChunks.push(data.chunk);
10187 }
10188 }
10189 this._done = true;
10190 if (this._cachedChunks.length > 0) {
10191 return;
10192 }
10193 for (const requestCapability of this._requests) {
10194 requestCapability.resolve({
10195 value: undefined,
10196 done: true
10197 });
10198 }
10199 this._requests.length = 0;
10200 }
10201 _onError(status) {
10202 this._storedError = createResponseStatusError(status, this._url);
10203 this._headersCapability.reject(this._storedError);
10204 for (const requestCapability of this._requests) {
10205 requestCapability.reject(this._storedError);
10206 }
10207 this._requests.length = 0;
10208 this._cachedChunks.length = 0;
10209 }
10210 _onProgress(evt) {
10211 this.onProgress?.({
10212 loaded: evt.loaded,
10213 total: evt.lengthComputable ? evt.total : this._contentLength
10214 });
10215 }
10216 get filename() {
10217 return this._filename;
10218 }
10219 get isRangeSupported() {
10220 return this._isRangeSupported;
10221 }
10222 get isStreamingSupported() {
10223 return this._isStreamingSupported;
10224 }
10225 get contentLength() {
10226 return this._contentLength;
10227 }
10228 get headersReady() {
10229 return this._headersCapability.promise;
10230 }
10231 async read() {
10232 if (this._storedError) {
10233 throw this._storedError;
10234 }
10235 if (this._cachedChunks.length > 0) {
10236 const chunk = this._cachedChunks.shift();
10237 return {
10238 value: chunk,
10239 done: false
10240 };
10241 }
10242 if (this._done) {
10243 return {
10244 value: undefined,
10245 done: true
10246 };
10247 }
10248 const requestCapability = Promise.withResolvers();
10249 this._requests.push(requestCapability);
10250 return requestCapability.promise;
10251 }
10252 cancel(reason) {
10253 this._done = true;
10254 this._headersCapability.reject(reason);
10255 for (const requestCapability of this._requests) {
10256 requestCapability.resolve({
10257 value: undefined,
10258 done: true
10259 });
10260 }
10261 this._requests.length = 0;
10262 if (this._manager.isPendingRequest(this._fullRequestId)) {
10263 this._manager.abortRequest(this._fullRequestId);
10264 }
10265 this._fullRequestReader = null;
10266 }
10267 }
10268 class PDFNetworkStreamRangeRequestReader {
10269 constructor(manager, begin, end) {
10270 this._manager = manager;
10271 const args = {
10272 onDone: this._onDone.bind(this),
10273 onError: this._onError.bind(this),
10274 onProgress: this._onProgress.bind(this)
10275 };
10276 this._url = manager.url;
10277 this._requestId = manager.requestRange(begin, end, args);
10278 this._requests = [];
10279 this._queuedChunk = null;
10280 this._done = false;
10281 this._storedError = undefined;
10282 this.onProgress = null;
10283 this.onClosed = null;
10284 }
10285 _close() {
10286 this.onClosed?.(this);
10287 }
10288 _onDone(data) {
10289 const chunk = data.chunk;
10290 if (this._requests.length > 0) {
10291 const requestCapability = this._requests.shift();
10292 requestCapability.resolve({
10293 value: chunk,
10294 done: false
10295 });
10296 } else {
10297 this._queuedChunk = chunk;
10298 }
10299 this._done = true;
10300 for (const requestCapability of this._requests) {
10301 requestCapability.resolve({
10302 value: undefined,
10303 done: true
10304 });
10305 }
10306 this._requests.length = 0;
10307 this._close();
10308 }
10309 _onError(status) {
10310 this._storedError = createResponseStatusError(status, this._url);
10311 for (const requestCapability of this._requests) {
10312 requestCapability.reject(this._storedError);
10313 }
10314 this._requests.length = 0;
10315 this._queuedChunk = null;
10316 }
10317 _onProgress(evt) {
10318 if (!this.isStreamingSupported) {
10319 this.onProgress?.({
10320 loaded: evt.loaded
10321 });
10322 }
10323 }
10324 get isStreamingSupported() {
10325 return false;
10326 }
10327 async read() {
10328 if (this._storedError) {
10329 throw this._storedError;
10330 }
10331 if (this._queuedChunk !== null) {
10332 const chunk = this._queuedChunk;
10333 this._queuedChunk = null;
10334 return {
10335 value: chunk,
10336 done: false
10337 };
10338 }
10339 if (this._done) {
10340 return {
10341 value: undefined,
10342 done: true
10343 };
10344 }
10345 const requestCapability = Promise.withResolvers();
10346 this._requests.push(requestCapability);
10347 return requestCapability.promise;
10348 }
10349 cancel(reason) {
10350 this._done = true;
10351 for (const requestCapability of this._requests) {
10352 requestCapability.resolve({
10353 value: undefined,
10354 done: true
10355 });
10356 }
10357 this._requests.length = 0;
10358 if (this._manager.isPendingRequest(this._requestId)) {
10359 this._manager.abortRequest(this._requestId);
10360 }
10361 this._close();
10362 }
10363 }
10364
10365 ;// ./src/display/node_stream.js
10366
10367
10368
10369 const urlRegex = /^[a-z][a-z0-9\-+.]+:/i;
10370 function parseUrlOrPath(sourceUrl) {
10371 if (urlRegex.test(sourceUrl)) {
10372 return new URL(sourceUrl);
10373 }
10374 const url = NodePackages.get("url");
10375 return new URL(url.pathToFileURL(sourceUrl));
10376 }
10377 function createRequest(url, headers, callback) {
10378 if (url.protocol === "http:") {
10379 const http = NodePackages.get("http");
10380 return http.request(url, {
10381 headers
10382 }, callback);
10383 }
10384 const https = NodePackages.get("https");
10385 return https.request(url, {
10386 headers
10387 }, callback);
10388 }
10389 class PDFNodeStream {
10390 constructor(source) {
10391 this.source = source;
10392 this.url = parseUrlOrPath(source.url);
10393 this.isHttp = this.url.protocol === "http:" || this.url.protocol === "https:";
10394 this.isFsUrl = this.url.protocol === "file:";
10395 this.headers = createHeaders(this.isHttp, source.httpHeaders);
10396 this._fullRequestReader = null;
10397 this._rangeRequestReaders = [];
10398 }
10399 get _progressiveDataLength() {
10400 return this._fullRequestReader?._loaded ?? 0;
10401 }
10402 getFullReader() {
10403 assert(!this._fullRequestReader, "PDFNodeStream.getFullReader can only be called once.");
10404 this._fullRequestReader = this.isFsUrl ? new PDFNodeStreamFsFullReader(this) : new PDFNodeStreamFullReader(this);
10405 return this._fullRequestReader;
10406 }
10407 getRangeReader(start, end) {
10408 if (end <= this._progressiveDataLength) {
10409 return null;
10410 }
10411 const rangeReader = this.isFsUrl ? new PDFNodeStreamFsRangeReader(this, start, end) : new PDFNodeStreamRangeReader(this, start, end);
10412 this._rangeRequestReaders.push(rangeReader);
10413 return rangeReader;
10414 }
10415 cancelAllRequests(reason) {
10416 this._fullRequestReader?.cancel(reason);
10417 for (const reader of this._rangeRequestReaders.slice(0)) {
10418 reader.cancel(reason);
10419 }
10420 }
10421 }
10422 class BaseFullReader {
10423 constructor(stream) {
10424 this._url = stream.url;
10425 this._done = false;
10426 this._storedError = null;
10427 this.onProgress = null;
10428 const source = stream.source;
10429 this._contentLength = source.length;
10430 this._loaded = 0;
10431 this._filename = null;
10432 this._disableRange = source.disableRange || false;
10433 this._rangeChunkSize = source.rangeChunkSize;
10434 if (!this._rangeChunkSize && !this._disableRange) {
10435 this._disableRange = true;
10436 }
10437 this._isStreamingSupported = !source.disableStream;
10438 this._isRangeSupported = !source.disableRange;
10439 this._readableStream = null;
10440 this._readCapability = Promise.withResolvers();
10441 this._headersCapability = Promise.withResolvers();
10442 }
10443 get headersReady() {
10444 return this._headersCapability.promise;
10445 }
10446 get filename() {
10447 return this._filename;
10448 }
10449 get contentLength() {
10450 return this._contentLength;
10451 }
10452 get isRangeSupported() {
10453 return this._isRangeSupported;
10454 }
10455 get isStreamingSupported() {
10456 return this._isStreamingSupported;
10457 }
10458 async read() {
10459 await this._readCapability.promise;
10460 if (this._done) {
10461 return {
10462 value: undefined,
10463 done: true
10464 };
10465 }
10466 if (this._storedError) {
10467 throw this._storedError;
10468 }
10469 const chunk = this._readableStream.read();
10470 if (chunk === null) {
10471 this._readCapability = Promise.withResolvers();
10472 return this.read();
10473 }
10474 this._loaded += chunk.length;
10475 this.onProgress?.({
10476 loaded: this._loaded,
10477 total: this._contentLength
10478 });
10479 const buffer = new Uint8Array(chunk).buffer;
10480 return {
10481 value: buffer,
10482 done: false
10483 };
10484 }
10485 cancel(reason) {
10486 if (!this._readableStream) {
10487 this._error(reason);
10488 return;
10489 }
10490 this._readableStream.destroy(reason);
10491 }
10492 _error(reason) {
10493 this._storedError = reason;
10494 this._readCapability.resolve();
10495 }
10496 _setReadableStream(readableStream) {
10497 this._readableStream = readableStream;
10498 readableStream.on("readable", () => {
10499 this._readCapability.resolve();
10500 });
10501 readableStream.on("end", () => {
10502 readableStream.destroy();
10503 this._done = true;
10504 this._readCapability.resolve();
10505 });
10506 readableStream.on("error", reason => {
10507 this._error(reason);
10508 });
10509 if (!this._isStreamingSupported && this._isRangeSupported) {
10510 this._error(new AbortException("streaming is disabled"));
10511 }
10512 if (this._storedError) {
10513 this._readableStream.destroy(this._storedError);
10514 }
10515 }
10516 }
10517 class BaseRangeReader {
10518 constructor(stream) {
10519 this._url = stream.url;
10520 this._done = false;
10521 this._storedError = null;
10522 this.onProgress = null;
10523 this._loaded = 0;
10524 this._readableStream = null;
10525 this._readCapability = Promise.withResolvers();
10526 const source = stream.source;
10527 this._isStreamingSupported = !source.disableStream;
10528 }
10529 get isStreamingSupported() {
10530 return this._isStreamingSupported;
10531 }
10532 async read() {
10533 await this._readCapability.promise;
10534 if (this._done) {
10535 return {
10536 value: undefined,
10537 done: true
10538 };
10539 }
10540 if (this._storedError) {
10541 throw this._storedError;
10542 }
10543 const chunk = this._readableStream.read();
10544 if (chunk === null) {
10545 this._readCapability = Promise.withResolvers();
10546 return this.read();
10547 }
10548 this._loaded += chunk.length;
10549 this.onProgress?.({
10550 loaded: this._loaded
10551 });
10552 const buffer = new Uint8Array(chunk).buffer;
10553 return {
10554 value: buffer,
10555 done: false
10556 };
10557 }
10558 cancel(reason) {
10559 if (!this._readableStream) {
10560 this._error(reason);
10561 return;
10562 }
10563 this._readableStream.destroy(reason);
10564 }
10565 _error(reason) {
10566 this._storedError = reason;
10567 this._readCapability.resolve();
10568 }
10569 _setReadableStream(readableStream) {
10570 this._readableStream = readableStream;
10571 readableStream.on("readable", () => {
10572 this._readCapability.resolve();
10573 });
10574 readableStream.on("end", () => {
10575 readableStream.destroy();
10576 this._done = true;
10577 this._readCapability.resolve();
10578 });
10579 readableStream.on("error", reason => {
10580 this._error(reason);
10581 });
10582 if (this._storedError) {
10583 this._readableStream.destroy(this._storedError);
10584 }
10585 }
10586 }
10587 class PDFNodeStreamFullReader extends BaseFullReader {
10588 constructor(stream) {
10589 super(stream);
10590 const headers = Object.fromEntries(stream.headers);
10591 const handleResponse = response => {
10592 if (response.statusCode === 404) {
10593 const error = new MissingPDFException(`Missing PDF "${this._url}".`);
10594 this._storedError = error;
10595 this._headersCapability.reject(error);
10596 return;
10597 }
10598 this._headersCapability.resolve();
10599 this._setReadableStream(response);
10600 const responseHeaders = new Headers(this._readableStream.headers);
10601 const {
10602 allowRangeRequests,
10603 suggestedLength
10604 } = validateRangeRequestCapabilities({
10605 responseHeaders,
10606 isHttp: stream.isHttp,
10607 rangeChunkSize: this._rangeChunkSize,
10608 disableRange: this._disableRange
10609 });
10610 this._isRangeSupported = allowRangeRequests;
10611 this._contentLength = suggestedLength || this._contentLength;
10612 this._filename = extractFilenameFromHeader(responseHeaders);
10613 };
10614 this._request = createRequest(this._url, headers, handleResponse);
10615 this._request.on("error", reason => {
10616 this._storedError = reason;
10617 this._headersCapability.reject(reason);
10618 });
10619 this._request.end();
10620 }
10621 }
10622 class PDFNodeStreamRangeReader extends BaseRangeReader {
10623 constructor(stream, start, end) {
10624 super(stream);
10625 const headers = Object.fromEntries(stream.headers);
10626 headers.Range = `bytes=${start}-${end - 1}`;
10627 const handleResponse = response => {
10628 if (response.statusCode === 404) {
10629 const error = new MissingPDFException(`Missing PDF "${this._url}".`);
10630 this._storedError = error;
10631 return;
10632 }
10633 this._setReadableStream(response);
10634 };
10635 this._request = createRequest(this._url, headers, handleResponse);
10636 this._request.on("error", reason => {
10637 this._storedError = reason;
10638 });
10639 this._request.end();
10640 }
10641 }
10642 class PDFNodeStreamFsFullReader extends BaseFullReader {
10643 constructor(stream) {
10644 super(stream);
10645 const fs = NodePackages.get("fs");
10646 fs.promises.lstat(this._url).then(stat => {
10647 this._contentLength = stat.size;
10648 this._setReadableStream(fs.createReadStream(this._url));
10649 this._headersCapability.resolve();
10650 }, error => {
10651 if (error.code === "ENOENT") {
10652 error = new MissingPDFException(`Missing PDF "${this._url}".`);
10653 }
10654 this._storedError = error;
10655 this._headersCapability.reject(error);
10656 });
10657 }
10658 }
10659 class PDFNodeStreamFsRangeReader extends BaseRangeReader {
10660 constructor(stream, start, end) {
10661 super(stream);
10662 const fs = NodePackages.get("fs");
10663 this._setReadableStream(fs.createReadStream(this._url, {
10664 start,
10665 end: end - 1
10666 }));
10667 }
10668 }
10669
10670 ;// ./src/display/text_layer.js
10671
10672
10673 const MAX_TEXT_DIVS_TO_RENDER = 100000;
10674 const DEFAULT_FONT_SIZE = 30;
10675 const DEFAULT_FONT_ASCENT = 0.8;
10676 class TextLayer {
10677 #capability = Promise.withResolvers();
10678 #container = null;
10679 #disableProcessItems = false;
10680 #fontInspectorEnabled = !!globalThis.FontInspector?.enabled;
10681 #lang = null;
10682 #layoutTextParams = null;
10683 #pageHeight = 0;
10684 #pageWidth = 0;
10685 #reader = null;
10686 #rootContainer = null;
10687 #rotation = 0;
10688 #scale = 0;
10689 #styleCache = Object.create(null);
10690 #textContentItemsStr = [];
10691 #textContentSource = null;
10692 #textDivs = [];
10693 #textDivProperties = new WeakMap();
10694 #transform = null;
10695 static #ascentCache = new Map();
10696 static #canvasContexts = new Map();
10697 static #canvasCtxFonts = new WeakMap();
10698 static #minFontSize = null;
10699 static #pendingTextLayers = new Set();
10700 constructor({
10701 textContentSource,
10702 container,
10703 viewport
10704 }) {
10705 if (textContentSource instanceof ReadableStream) {
10706 this.#textContentSource = textContentSource;
10707 } else if (typeof textContentSource === "object") {
10708 this.#textContentSource = new ReadableStream({
10709 start(controller) {
10710 controller.enqueue(textContentSource);
10711 controller.close();
10712 }
10713 });
10714 } else {
10715 throw new Error('No "textContentSource" parameter specified.');
10716 }
10717 this.#container = this.#rootContainer = container;
10718 this.#scale = viewport.scale * (globalThis.devicePixelRatio || 1);
10719 this.#rotation = viewport.rotation;
10720 this.#layoutTextParams = {
10721 div: null,
10722 properties: null,
10723 ctx: null
10724 };
10725 const {
10726 pageWidth,
10727 pageHeight,
10728 pageX,
10729 pageY
10730 } = viewport.rawDims;
10731 this.#transform = [1, 0, 0, -1, -pageX, pageY + pageHeight];
10732 this.#pageWidth = pageWidth;
10733 this.#pageHeight = pageHeight;
10734 TextLayer.#ensureMinFontSizeComputed();
10735 setLayerDimensions(container, viewport);
10736 this.#capability.promise.finally(() => {
10737 TextLayer.#pendingTextLayers.delete(this);
10738 this.#layoutTextParams = null;
10739 this.#styleCache = null;
10740 }).catch(() => {});
10741 }
10742 static get fontFamilyMap() {
10743 const {
10744 isWindows,
10745 isFirefox
10746 } = util_FeatureTest.platform;
10747 return shadow(this, "fontFamilyMap", new Map([["sans-serif", `${isWindows && isFirefox ? "Calibri, " : ""}sans-serif`], ["monospace", `${isWindows && isFirefox ? "Lucida Console, " : ""}monospace`]]));
10748 }
10749 render() {
10750 const pump = () => {
10751 this.#reader.read().then(({
10752 value,
10753 done
10754 }) => {
10755 if (done) {
10756 this.#capability.resolve();
10757 return;
10758 }
10759 this.#lang ??= value.lang;
10760 Object.assign(this.#styleCache, value.styles);
10761 this.#processItems(value.items);
10762 pump();
10763 }, this.#capability.reject);
10764 };
10765 this.#reader = this.#textContentSource.getReader();
10766 TextLayer.#pendingTextLayers.add(this);
10767 pump();
10768 return this.#capability.promise;
10769 }
10770 update({
10771 viewport,
10772 onBefore = null
10773 }) {
10774 const scale = viewport.scale * (globalThis.devicePixelRatio || 1);
10775 const rotation = viewport.rotation;
10776 if (rotation !== this.#rotation) {
10777 onBefore?.();
10778 this.#rotation = rotation;
10779 setLayerDimensions(this.#rootContainer, {
10780 rotation
10781 });
10782 }
10783 if (scale !== this.#scale) {
10784 onBefore?.();
10785 this.#scale = scale;
10786 const params = {
10787 div: null,
10788 properties: null,
10789 ctx: TextLayer.#getCtx(this.#lang)
10790 };
10791 for (const div of this.#textDivs) {
10792 params.properties = this.#textDivProperties.get(div);
10793 params.div = div;
10794 this.#layout(params);
10795 }
10796 }
10797 }
10798 cancel() {
10799 const abortEx = new AbortException("TextLayer task cancelled.");
10800 this.#reader?.cancel(abortEx).catch(() => {});
10801 this.#reader = null;
10802 this.#capability.reject(abortEx);
10803 }
10804 get textDivs() {
10805 return this.#textDivs;
10806 }
10807 get textContentItemsStr() {
10808 return this.#textContentItemsStr;
10809 }
10810 #processItems(items) {
10811 if (this.#disableProcessItems) {
10812 return;
10813 }
10814 this.#layoutTextParams.ctx ??= TextLayer.#getCtx(this.#lang);
10815 const textDivs = this.#textDivs,
10816 textContentItemsStr = this.#textContentItemsStr;
10817 for (const item of items) {
10818 if (textDivs.length > MAX_TEXT_DIVS_TO_RENDER) {
10819 warn("Ignoring additional textDivs for performance reasons.");
10820 this.#disableProcessItems = true;
10821 return;
10822 }
10823 if (item.str === undefined) {
10824 if (item.type === "beginMarkedContentProps" || item.type === "beginMarkedContent") {
10825 const parent = this.#container;
10826 this.#container = document.createElement("span");
10827 this.#container.classList.add("markedContent");
10828 if (item.id !== null) {
10829 this.#container.setAttribute("id", `${item.id}`);
10830 }
10831 parent.append(this.#container);
10832 } else if (item.type === "endMarkedContent") {
10833 this.#container = this.#container.parentNode;
10834 }
10835 continue;
10836 }
10837 textContentItemsStr.push(item.str);
10838 this.#appendText(item);
10839 }
10840 }
10841 #appendText(geom) {
10842 const textDiv = document.createElement("span");
10843 const textDivProperties = {
10844 angle: 0,
10845 canvasWidth: 0,
10846 hasText: geom.str !== "",
10847 hasEOL: geom.hasEOL,
10848 fontSize: 0
10849 };
10850 this.#textDivs.push(textDiv);
10851 const tx = Util.transform(this.#transform, geom.transform);
10852 let angle = Math.atan2(tx[1], tx[0]);
10853 const style = this.#styleCache[geom.fontName];
10854 if (style.vertical) {
10855 angle += Math.PI / 2;
10856 }
10857 let fontFamily = this.#fontInspectorEnabled && style.fontSubstitution || style.fontFamily;
10858 fontFamily = TextLayer.fontFamilyMap.get(fontFamily) || fontFamily;
10859 const fontHeight = Math.hypot(tx[2], tx[3]);
10860 const fontAscent = fontHeight * TextLayer.#getAscent(fontFamily, this.#lang);
10861 let left, top;
10862 if (angle === 0) {
10863 left = tx[4];
10864 top = tx[5] - fontAscent;
10865 } else {
10866 left = tx[4] + fontAscent * Math.sin(angle);
10867 top = tx[5] - fontAscent * Math.cos(angle);
10868 }
10869 const scaleFactorStr = "calc(var(--scale-factor)*";
10870 const divStyle = textDiv.style;
10871 if (this.#container === this.#rootContainer) {
10872 divStyle.left = `${(100 * left / this.#pageWidth).toFixed(2)}%`;
10873 divStyle.top = `${(100 * top / this.#pageHeight).toFixed(2)}%`;
10874 } else {
10875 divStyle.left = `${scaleFactorStr}${left.toFixed(2)}px)`;
10876 divStyle.top = `${scaleFactorStr}${top.toFixed(2)}px)`;
10877 }
10878 divStyle.fontSize = `${scaleFactorStr}${(TextLayer.#minFontSize * fontHeight).toFixed(2)}px)`;
10879 divStyle.fontFamily = fontFamily;
10880 textDivProperties.fontSize = fontHeight;
10881 textDiv.setAttribute("role", "presentation");
10882 textDiv.textContent = geom.str;
10883 textDiv.dir = geom.dir;
10884 if (this.#fontInspectorEnabled) {
10885 textDiv.dataset.fontName = style.fontSubstitutionLoadedName || geom.fontName;
10886 }
10887 if (angle !== 0) {
10888 textDivProperties.angle = angle * (180 / Math.PI);
10889 }
10890 let shouldScaleText = false;
10891 if (geom.str.length > 1) {
10892 shouldScaleText = true;
10893 } else if (geom.str !== " " && geom.transform[0] !== geom.transform[3]) {
10894 const absScaleX = Math.abs(geom.transform[0]),
10895 absScaleY = Math.abs(geom.transform[3]);
10896 if (absScaleX !== absScaleY && Math.max(absScaleX, absScaleY) / Math.min(absScaleX, absScaleY) > 1.5) {
10897 shouldScaleText = true;
10898 }
10899 }
10900 if (shouldScaleText) {
10901 textDivProperties.canvasWidth = style.vertical ? geom.height : geom.width;
10902 }
10903 this.#textDivProperties.set(textDiv, textDivProperties);
10904 this.#layoutTextParams.div = textDiv;
10905 this.#layoutTextParams.properties = textDivProperties;
10906 this.#layout(this.#layoutTextParams);
10907 if (textDivProperties.hasText) {
10908 this.#container.append(textDiv);
10909 }
10910 if (textDivProperties.hasEOL) {
10911 const br = document.createElement("br");
10912 br.setAttribute("role", "presentation");
10913 this.#container.append(br);
10914 }
10915 }
10916 #layout(params) {
10917 const {
10918 div,
10919 properties,
10920 ctx
10921 } = params;
10922 const {
10923 style
10924 } = div;
10925 let transform = "";
10926 if (TextLayer.#minFontSize > 1) {
10927 transform = `scale(${1 / TextLayer.#minFontSize})`;
10928 }
10929 if (properties.canvasWidth !== 0 && properties.hasText) {
10930 const {
10931 fontFamily
10932 } = style;
10933 const {
10934 canvasWidth,
10935 fontSize
10936 } = properties;
10937 TextLayer.#ensureCtxFont(ctx, fontSize * this.#scale, fontFamily);
10938 const {
10939 width
10940 } = ctx.measureText(div.textContent);
10941 if (width > 0) {
10942 transform = `scaleX(${canvasWidth * this.#scale / width}) ${transform}`;
10943 }
10944 }
10945 if (properties.angle !== 0) {
10946 transform = `rotate(${properties.angle}deg) ${transform}`;
10947 }
10948 if (transform.length > 0) {
10949 style.transform = transform;
10950 }
10951 }
10952 static cleanup() {
10953 if (this.#pendingTextLayers.size > 0) {
10954 return;
10955 }
10956 this.#ascentCache.clear();
10957 for (const {
10958 canvas
10959 } of this.#canvasContexts.values()) {
10960 canvas.remove();
10961 }
10962 this.#canvasContexts.clear();
10963 }
10964 static #getCtx(lang = null) {
10965 let ctx = this.#canvasContexts.get(lang ||= "");
10966 if (!ctx) {
10967 const canvas = document.createElement("canvas");
10968 canvas.className = "hiddenCanvasElement";
10969 canvas.lang = lang;
10970 document.body.append(canvas);
10971 ctx = canvas.getContext("2d", {
10972 alpha: false,
10973 willReadFrequently: true
10974 });
10975 this.#canvasContexts.set(lang, ctx);
10976 this.#canvasCtxFonts.set(ctx, {
10977 size: 0,
10978 family: ""
10979 });
10980 }
10981 return ctx;
10982 }
10983 static #ensureCtxFont(ctx, size, family) {
10984 const cached = this.#canvasCtxFonts.get(ctx);
10985 if (size === cached.size && family === cached.family) {
10986 return;
10987 }
10988 ctx.font = `${size}px ${family}`;
10989 cached.size = size;
10990 cached.family = family;
10991 }
10992 static #ensureMinFontSizeComputed() {
10993 if (this.#minFontSize !== null) {
10994 return;
10995 }
10996 const div = document.createElement("div");
10997 div.style.opacity = 0;
10998 div.style.lineHeight = 1;
10999 div.style.fontSize = "1px";
11000 div.style.position = "absolute";
11001 div.textContent = "X";
11002 document.body.append(div);
11003 this.#minFontSize = div.getBoundingClientRect().height;
11004 div.remove();
11005 }
11006 static #getAscent(fontFamily, lang) {
11007 const cachedAscent = this.#ascentCache.get(fontFamily);
11008 if (cachedAscent) {
11009 return cachedAscent;
11010 }
11011 const ctx = this.#getCtx(lang);
11012 ctx.canvas.width = ctx.canvas.height = DEFAULT_FONT_SIZE;
11013 this.#ensureCtxFont(ctx, DEFAULT_FONT_SIZE, fontFamily);
11014 const metrics = ctx.measureText("");
11015 let ascent = metrics.fontBoundingBoxAscent;
11016 let descent = Math.abs(metrics.fontBoundingBoxDescent);
11017 if (ascent) {
11018 const ratio = ascent / (ascent + descent);
11019 this.#ascentCache.set(fontFamily, ratio);
11020 ctx.canvas.width = ctx.canvas.height = 0;
11021 return ratio;
11022 }
11023 ctx.strokeStyle = "red";
11024 ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
11025 ctx.strokeText("g", 0, 0);
11026 let pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
11027 descent = 0;
11028 for (let i = pixels.length - 1 - 3; i >= 0; i -= 4) {
11029 if (pixels[i] > 0) {
11030 descent = Math.ceil(i / 4 / DEFAULT_FONT_SIZE);
11031 break;
11032 }
11033 }
11034 ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
11035 ctx.strokeText("A", 0, DEFAULT_FONT_SIZE);
11036 pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
11037 ascent = 0;
11038 for (let i = 0, ii = pixels.length; i < ii; i += 4) {
11039 if (pixels[i] > 0) {
11040 ascent = DEFAULT_FONT_SIZE - Math.floor(i / 4 / DEFAULT_FONT_SIZE);
11041 break;
11042 }
11043 }
11044 ctx.canvas.width = ctx.canvas.height = 0;
11045 const ratio = ascent ? ascent / (ascent + descent) : DEFAULT_FONT_ASCENT;
11046 this.#ascentCache.set(fontFamily, ratio);
11047 return ratio;
11048 }
11049 }
11050
11051 ;// ./src/display/xfa_text.js
11052 class XfaText {
11053 static textContent(xfa) {
11054 const items = [];
11055 const output = {
11056 items,
11057 styles: Object.create(null)
11058 };
11059 function walk(node) {
11060 if (!node) {
11061 return;
11062 }
11063 let str = null;
11064 const name = node.name;
11065 if (name === "#text") {
11066 str = node.value;
11067 } else if (!XfaText.shouldBuildText(name)) {
11068 return;
11069 } else if (node?.attributes?.textContent) {
11070 str = node.attributes.textContent;
11071 } else if (node.value) {
11072 str = node.value;
11073 }
11074 if (str !== null) {
11075 items.push({
11076 str
11077 });
11078 }
11079 if (!node.children) {
11080 return;
11081 }
11082 for (const child of node.children) {
11083 walk(child);
11084 }
11085 }
11086 walk(xfa);
11087 return output;
11088 }
11089 static shouldBuildText(name) {
11090 return !(name === "textarea" || name === "input" || name === "option" || name === "select");
11091 }
11092 }
11093
11094 ;// ./src/display/api.js
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111 const DEFAULT_RANGE_CHUNK_SIZE = 65536;
11112 const RENDERING_CANCELLED_TIMEOUT = 100;
11113 const DELAYED_CLEANUP_TIMEOUT = 5000;
11114 const DefaultCanvasFactory = isNodeJS ? NodeCanvasFactory : DOMCanvasFactory;
11115 const DefaultCMapReaderFactory = isNodeJS ? NodeCMapReaderFactory : DOMCMapReaderFactory;
11116 const DefaultFilterFactory = isNodeJS ? NodeFilterFactory : DOMFilterFactory;
11117 const DefaultStandardFontDataFactory = isNodeJS ? NodeStandardFontDataFactory : DOMStandardFontDataFactory;
11118 function getDocument(src = {}) {
11119 if (typeof src === "string" || src instanceof URL) {
11120 src = {
11121 url: src
11122 };
11123 } else if (src instanceof ArrayBuffer || ArrayBuffer.isView(src)) {
11124 src = {
11125 data: src
11126 };
11127 }
11128 const task = new PDFDocumentLoadingTask();
11129 const {
11130 docId
11131 } = task;
11132 const url = src.url ? getUrlProp(src.url) : null;
11133 const data = src.data ? getDataProp(src.data) : null;
11134 const httpHeaders = src.httpHeaders || null;
11135 const withCredentials = src.withCredentials === true;
11136 const password = src.password ?? null;
11137 const rangeTransport = src.range instanceof PDFDataRangeTransport ? src.range : null;
11138 const rangeChunkSize = Number.isInteger(src.rangeChunkSize) && src.rangeChunkSize > 0 ? src.rangeChunkSize : DEFAULT_RANGE_CHUNK_SIZE;
11139 let worker = src.worker instanceof PDFWorker ? src.worker : null;
11140 const verbosity = src.verbosity;
11141 const docBaseUrl = typeof src.docBaseUrl === "string" && !isDataScheme(src.docBaseUrl) ? src.docBaseUrl : null;
11142 const cMapUrl = typeof src.cMapUrl === "string" ? src.cMapUrl : null;
11143 const cMapPacked = src.cMapPacked !== false;
11144 const CMapReaderFactory = src.CMapReaderFactory || DefaultCMapReaderFactory;
11145 const standardFontDataUrl = typeof src.standardFontDataUrl === "string" ? src.standardFontDataUrl : null;
11146 const StandardFontDataFactory = src.StandardFontDataFactory || DefaultStandardFontDataFactory;
11147 const ignoreErrors = src.stopAtErrors !== true;
11148 const maxImageSize = Number.isInteger(src.maxImageSize) && src.maxImageSize > -1 ? src.maxImageSize : -1;
11149 const isEvalSupported = src.isEvalSupported !== false;
11150 const isOffscreenCanvasSupported = typeof src.isOffscreenCanvasSupported === "boolean" ? src.isOffscreenCanvasSupported : !isNodeJS;
11151 const canvasMaxAreaInBytes = Number.isInteger(src.canvasMaxAreaInBytes) ? src.canvasMaxAreaInBytes : -1;
11152 const disableFontFace = typeof src.disableFontFace === "boolean" ? src.disableFontFace : isNodeJS;
11153 const fontExtraProperties = src.fontExtraProperties === true;
11154 const enableXfa = src.enableXfa === true;
11155 const ownerDocument = src.ownerDocument || globalThis.document;
11156 const disableRange = src.disableRange === true;
11157 const disableStream = src.disableStream === true;
11158 const disableAutoFetch = src.disableAutoFetch === true;
11159 const pdfBug = src.pdfBug === true;
11160 const CanvasFactory = src.CanvasFactory || DefaultCanvasFactory;
11161 const FilterFactory = src.FilterFactory || DefaultFilterFactory;
11162 const enableHWA = src.enableHWA === true;
11163 const length = rangeTransport ? rangeTransport.length : src.length ?? NaN;
11164 const useSystemFonts = typeof src.useSystemFonts === "boolean" ? src.useSystemFonts : !isNodeJS && !disableFontFace;
11165 const useWorkerFetch = typeof src.useWorkerFetch === "boolean" ? src.useWorkerFetch : CMapReaderFactory === DOMCMapReaderFactory && StandardFontDataFactory === DOMStandardFontDataFactory && cMapUrl && standardFontDataUrl && isValidFetchUrl(cMapUrl, document.baseURI) && isValidFetchUrl(standardFontDataUrl, document.baseURI);
11166 if (src.canvasFactory) {
11167 deprecated("`canvasFactory`-instance option, please use `CanvasFactory` instead.");
11168 }
11169 if (src.filterFactory) {
11170 deprecated("`filterFactory`-instance option, please use `FilterFactory` instead.");
11171 }
11172 const styleElement = null;
11173 setVerbosityLevel(verbosity);
11174 const transportFactory = {
11175 canvasFactory: new CanvasFactory({
11176 ownerDocument,
11177 enableHWA
11178 }),
11179 filterFactory: new FilterFactory({
11180 docId,
11181 ownerDocument
11182 }),
11183 cMapReaderFactory: useWorkerFetch ? null : new CMapReaderFactory({
11184 baseUrl: cMapUrl,
11185 isCompressed: cMapPacked
11186 }),
11187 standardFontDataFactory: useWorkerFetch ? null : new StandardFontDataFactory({
11188 baseUrl: standardFontDataUrl
11189 })
11190 };
11191 if (!worker) {
11192 const workerParams = {
11193 verbosity,
11194 port: GlobalWorkerOptions.workerPort
11195 };
11196 worker = workerParams.port ? PDFWorker.fromPort(workerParams) : new PDFWorker(workerParams);
11197 task._worker = worker;
11198 }
11199 const docParams = {
11200 docId,
11201 apiVersion: "4.7.76",
11202 data,
11203 password,
11204 disableAutoFetch,
11205 rangeChunkSize,
11206 length,
11207 docBaseUrl,
11208 enableXfa,
11209 evaluatorOptions: {
11210 maxImageSize,
11211 disableFontFace,
11212 ignoreErrors,
11213 isEvalSupported,
11214 isOffscreenCanvasSupported,
11215 canvasMaxAreaInBytes,
11216 fontExtraProperties,
11217 useSystemFonts,
11218 cMapUrl: useWorkerFetch ? cMapUrl : null,
11219 standardFontDataUrl: useWorkerFetch ? standardFontDataUrl : null
11220 }
11221 };
11222 const transportParams = {
11223 disableFontFace,
11224 fontExtraProperties,
11225 ownerDocument,
11226 pdfBug,
11227 styleElement,
11228 loadingParams: {
11229 disableAutoFetch,
11230 enableXfa
11231 }
11232 };
11233 worker.promise.then(function () {
11234 if (task.destroyed) {
11235 throw new Error("Loading aborted");
11236 }
11237 if (worker.destroyed) {
11238 throw new Error("Worker was destroyed");
11239 }
11240 const workerIdPromise = worker.messageHandler.sendWithPromise("GetDocRequest", docParams, data ? [data.buffer] : null);
11241 let networkStream;
11242 if (rangeTransport) {
11243 networkStream = new PDFDataTransportStream(rangeTransport, {
11244 disableRange,
11245 disableStream
11246 });
11247 } else if (!data) {
11248 if (!url) {
11249 throw new Error("getDocument - no `url` parameter provided.");
11250 }
11251 let NetworkStream;
11252 if (isNodeJS) {
11253 const isFetchSupported = typeof fetch !== "undefined" && typeof Response !== "undefined" && "body" in Response.prototype;
11254 NetworkStream = isFetchSupported && isValidFetchUrl(url) ? PDFFetchStream : PDFNodeStream;
11255 } else {
11256 NetworkStream = isValidFetchUrl(url) ? PDFFetchStream : PDFNetworkStream;
11257 }
11258 networkStream = new NetworkStream({
11259 url,
11260 length,
11261 httpHeaders,
11262 withCredentials,
11263 rangeChunkSize,
11264 disableRange,
11265 disableStream
11266 });
11267 }
11268 return workerIdPromise.then(workerId => {
11269 if (task.destroyed) {
11270 throw new Error("Loading aborted");
11271 }
11272 if (worker.destroyed) {
11273 throw new Error("Worker was destroyed");
11274 }
11275 const messageHandler = new MessageHandler(docId, workerId, worker.port);
11276 const transport = new WorkerTransport(messageHandler, task, networkStream, transportParams, transportFactory);
11277 task._transport = transport;
11278 messageHandler.send("Ready", null);
11279 });
11280 }).catch(task._capability.reject);
11281 return task;
11282 }
11283 function getUrlProp(val) {
11284 if (val instanceof URL) {
11285 return val.href;
11286 }
11287 try {
11288 return new URL(val, window.location).href;
11289 } catch {
11290 if (isNodeJS && typeof val === "string") {
11291 return val;
11292 }
11293 }
11294 throw new Error("Invalid PDF url data: " + "either string or URL-object is expected in the url property.");
11295 }
11296 function getDataProp(val) {
11297 if (isNodeJS && typeof Buffer !== "undefined" && val instanceof Buffer) {
11298 throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");
11299 }
11300 if (val instanceof Uint8Array && val.byteLength === val.buffer.byteLength) {
11301 return val;
11302 }
11303 if (typeof val === "string") {
11304 return stringToBytes(val);
11305 }
11306 if (val instanceof ArrayBuffer || ArrayBuffer.isView(val) || typeof val === "object" && !isNaN(val?.length)) {
11307 return new Uint8Array(val);
11308 }
11309 throw new Error("Invalid PDF binary data: either TypedArray, " + "string, or array-like object is expected in the data property.");
11310 }
11311 function isRefProxy(ref) {
11312 return typeof ref === "object" && Number.isInteger(ref?.num) && ref.num >= 0 && Number.isInteger(ref?.gen) && ref.gen >= 0;
11313 }
11314 class PDFDocumentLoadingTask {
11315 static #docId = 0;
11316 constructor() {
11317 this._capability = Promise.withResolvers();
11318 this._transport = null;
11319 this._worker = null;
11320 this.docId = `d${PDFDocumentLoadingTask.#docId++}`;
11321 this.destroyed = false;
11322 this.onPassword = null;
11323 this.onProgress = null;
11324 }
11325 get promise() {
11326 return this._capability.promise;
11327 }
11328 async destroy() {
11329 this.destroyed = true;
11330 try {
11331 if (this._worker?.port) {
11332 this._worker._pendingDestroy = true;
11333 }
11334 await this._transport?.destroy();
11335 } catch (ex) {
11336 if (this._worker?.port) {
11337 delete this._worker._pendingDestroy;
11338 }
11339 throw ex;
11340 }
11341 this._transport = null;
11342 if (this._worker) {
11343 this._worker.destroy();
11344 this._worker = null;
11345 }
11346 }
11347 }
11348 class PDFDataRangeTransport {
11349 constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) {
11350 this.length = length;
11351 this.initialData = initialData;
11352 this.progressiveDone = progressiveDone;
11353 this.contentDispositionFilename = contentDispositionFilename;
11354 this._rangeListeners = [];
11355 this._progressListeners = [];
11356 this._progressiveReadListeners = [];
11357 this._progressiveDoneListeners = [];
11358 this._readyCapability = Promise.withResolvers();
11359 }
11360 addRangeListener(listener) {
11361 this._rangeListeners.push(listener);
11362 }
11363 addProgressListener(listener) {
11364 this._progressListeners.push(listener);
11365 }
11366 addProgressiveReadListener(listener) {
11367 this._progressiveReadListeners.push(listener);
11368 }
11369 addProgressiveDoneListener(listener) {
11370 this._progressiveDoneListeners.push(listener);
11371 }
11372 onDataRange(begin, chunk) {
11373 for (const listener of this._rangeListeners) {
11374 listener(begin, chunk);
11375 }
11376 }
11377 onDataProgress(loaded, total) {
11378 this._readyCapability.promise.then(() => {
11379 for (const listener of this._progressListeners) {
11380 listener(loaded, total);
11381 }
11382 });
11383 }
11384 onDataProgressiveRead(chunk) {
11385 this._readyCapability.promise.then(() => {
11386 for (const listener of this._progressiveReadListeners) {
11387 listener(chunk);
11388 }
11389 });
11390 }
11391 onDataProgressiveDone() {
11392 this._readyCapability.promise.then(() => {
11393 for (const listener of this._progressiveDoneListeners) {
11394 listener();
11395 }
11396 });
11397 }
11398 transportReady() {
11399 this._readyCapability.resolve();
11400 }
11401 requestDataRange(begin, end) {
11402 unreachable("Abstract method PDFDataRangeTransport.requestDataRange");
11403 }
11404 abort() {}
11405 }
11406 class PDFDocumentProxy {
11407 constructor(pdfInfo, transport) {
11408 this._pdfInfo = pdfInfo;
11409 this._transport = transport;
11410 }
11411 get annotationStorage() {
11412 return this._transport.annotationStorage;
11413 }
11414 get canvasFactory() {
11415 return this._transport.canvasFactory;
11416 }
11417 get filterFactory() {
11418 return this._transport.filterFactory;
11419 }
11420 get numPages() {
11421 return this._pdfInfo.numPages;
11422 }
11423 get fingerprints() {
11424 return this._pdfInfo.fingerprints;
11425 }
11426 get isPureXfa() {
11427 return shadow(this, "isPureXfa", !!this._transport._htmlForXfa);
11428 }
11429 get allXfaHtml() {
11430 return this._transport._htmlForXfa;
11431 }
11432 getPage(pageNumber) {
11433 return this._transport.getPage(pageNumber);
11434 }
11435 getPageIndex(ref) {
11436 return this._transport.getPageIndex(ref);
11437 }
11438 getDestinations() {
11439 return this._transport.getDestinations();
11440 }
11441 getDestination(id) {
11442 return this._transport.getDestination(id);
11443 }
11444 getPageLabels() {
11445 return this._transport.getPageLabels();
11446 }
11447 getPageLayout() {
11448 return this._transport.getPageLayout();
11449 }
11450 getPageMode() {
11451 return this._transport.getPageMode();
11452 }
11453 getViewerPreferences() {
11454 return this._transport.getViewerPreferences();
11455 }
11456 getOpenAction() {
11457 return this._transport.getOpenAction();
11458 }
11459 getAttachments() {
11460 return this._transport.getAttachments();
11461 }
11462 getJSActions() {
11463 return this._transport.getDocJSActions();
11464 }
11465 getOutline() {
11466 return this._transport.getOutline();
11467 }
11468 getOptionalContentConfig({
11469 intent = "display"
11470 } = {}) {
11471 const {
11472 renderingIntent
11473 } = this._transport.getRenderingIntent(intent);
11474 return this._transport.getOptionalContentConfig(renderingIntent);
11475 }
11476 getPermissions() {
11477 return this._transport.getPermissions();
11478 }
11479 getMetadata() {
11480 return this._transport.getMetadata();
11481 }
11482 getMarkInfo() {
11483 return this._transport.getMarkInfo();
11484 }
11485 getData() {
11486 return this._transport.getData();
11487 }
11488 saveDocument() {
11489 return this._transport.saveDocument();
11490 }
11491 getDownloadInfo() {
11492 return this._transport.downloadInfoCapability.promise;
11493 }
11494 cleanup(keepLoadedFonts = false) {
11495 return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa);
11496 }
11497 destroy() {
11498 return this.loadingTask.destroy();
11499 }
11500 cachedPageNumber(ref) {
11501 return this._transport.cachedPageNumber(ref);
11502 }
11503 get loadingParams() {
11504 return this._transport.loadingParams;
11505 }
11506 get loadingTask() {
11507 return this._transport.loadingTask;
11508 }
11509 getFieldObjects() {
11510 return this._transport.getFieldObjects();
11511 }
11512 hasJSActions() {
11513 return this._transport.hasJSActions();
11514 }
11515 getCalculationOrderIds() {
11516 return this._transport.getCalculationOrderIds();
11517 }
11518 }
11519 class PDFPageProxy {
11520 #delayedCleanupTimeout = null;
11521 #pendingCleanup = false;
11522 constructor(pageIndex, pageInfo, transport, pdfBug = false) {
11523 this._pageIndex = pageIndex;
11524 this._pageInfo = pageInfo;
11525 this._transport = transport;
11526 this._stats = pdfBug ? new StatTimer() : null;
11527 this._pdfBug = pdfBug;
11528 this.commonObjs = transport.commonObjs;
11529 this.objs = new PDFObjects();
11530 this._maybeCleanupAfterRender = false;
11531 this._intentStates = new Map();
11532 this.destroyed = false;
11533 }
11534 get pageNumber() {
11535 return this._pageIndex + 1;
11536 }
11537 get rotate() {
11538 return this._pageInfo.rotate;
11539 }
11540 get ref() {
11541 return this._pageInfo.ref;
11542 }
11543 get userUnit() {
11544 return this._pageInfo.userUnit;
11545 }
11546 get view() {
11547 return this._pageInfo.view;
11548 }
11549 getViewport({
11550 scale,
11551 rotation = this.rotate,
11552 offsetX = 0,
11553 offsetY = 0,
11554 dontFlip = false
11555 } = {}) {
11556 return new PageViewport({
11557 viewBox: this.view,
11558 scale,
11559 rotation,
11560 offsetX,
11561 offsetY,
11562 dontFlip
11563 });
11564 }
11565 getAnnotations({
11566 intent = "display"
11567 } = {}) {
11568 const {
11569 renderingIntent
11570 } = this._transport.getRenderingIntent(intent);
11571 return this._transport.getAnnotations(this._pageIndex, renderingIntent);
11572 }
11573 getJSActions() {
11574 return this._transport.getPageJSActions(this._pageIndex);
11575 }
11576 get filterFactory() {
11577 return this._transport.filterFactory;
11578 }
11579 get isPureXfa() {
11580 return shadow(this, "isPureXfa", !!this._transport._htmlForXfa);
11581 }
11582 async getXfa() {
11583 return this._transport._htmlForXfa?.children[this._pageIndex] || null;
11584 }
11585 render({
11586 canvasContext,
11587 viewport,
11588 intent = "display",
11589 annotationMode = AnnotationMode.ENABLE,
11590 transform = null,
11591 background = null,
11592 optionalContentConfigPromise = null,
11593 annotationCanvasMap = null,
11594 pageColors = null,
11595 printAnnotationStorage = null,
11596 isEditing = false
11597 }) {
11598 this._stats?.time("Overall");
11599 const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, isEditing);
11600 const {
11601 renderingIntent,
11602 cacheKey
11603 } = intentArgs;
11604 this.#pendingCleanup = false;
11605 this.#abortDelayedCleanup();
11606 optionalContentConfigPromise ||= this._transport.getOptionalContentConfig(renderingIntent);
11607 let intentState = this._intentStates.get(cacheKey);
11608 if (!intentState) {
11609 intentState = Object.create(null);
11610 this._intentStates.set(cacheKey, intentState);
11611 }
11612 if (intentState.streamReaderCancelTimeout) {
11613 clearTimeout(intentState.streamReaderCancelTimeout);
11614 intentState.streamReaderCancelTimeout = null;
11615 }
11616 const intentPrint = !!(renderingIntent & RenderingIntentFlag.PRINT);
11617 if (!intentState.displayReadyCapability) {
11618 intentState.displayReadyCapability = Promise.withResolvers();
11619 intentState.operatorList = {
11620 fnArray: [],
11621 argsArray: [],
11622 lastChunk: false,
11623 separateAnnots: null
11624 };
11625 this._stats?.time("Page Request");
11626 this._pumpOperatorList(intentArgs);
11627 }
11628 const complete = error => {
11629 intentState.renderTasks.delete(internalRenderTask);
11630 if (this._maybeCleanupAfterRender || intentPrint) {
11631 this.#pendingCleanup = true;
11632 }
11633 this.#tryCleanup(!intentPrint);
11634 if (error) {
11635 internalRenderTask.capability.reject(error);
11636 this._abortOperatorList({
11637 intentState,
11638 reason: error instanceof Error ? error : new Error(error)
11639 });
11640 } else {
11641 internalRenderTask.capability.resolve();
11642 }
11643 if (this._stats) {
11644 this._stats.timeEnd("Rendering");
11645 this._stats.timeEnd("Overall");
11646 if (globalThis.Stats?.enabled) {
11647 globalThis.Stats.add(this.pageNumber, this._stats);
11648 }
11649 }
11650 };
11651 const internalRenderTask = new InternalRenderTask({
11652 callback: complete,
11653 params: {
11654 canvasContext,
11655 viewport,
11656 transform,
11657 background
11658 },
11659 objs: this.objs,
11660 commonObjs: this.commonObjs,
11661 annotationCanvasMap,
11662 operatorList: intentState.operatorList,
11663 pageIndex: this._pageIndex,
11664 canvasFactory: this._transport.canvasFactory,
11665 filterFactory: this._transport.filterFactory,
11666 useRequestAnimationFrame: !intentPrint,
11667 pdfBug: this._pdfBug,
11668 pageColors
11669 });
11670 (intentState.renderTasks ||= new Set()).add(internalRenderTask);
11671 const renderTask = internalRenderTask.task;
11672 Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => {
11673 if (this.destroyed) {
11674 complete();
11675 return;
11676 }
11677 this._stats?.time("Rendering");
11678 if (!(optionalContentConfig.renderingIntent & renderingIntent)) {
11679 throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` " + "and `PDFDocumentProxy.getOptionalContentConfig` methods.");
11680 }
11681 internalRenderTask.initializeGraphics({
11682 transparency,
11683 optionalContentConfig
11684 });
11685 internalRenderTask.operatorListChanged();
11686 }).catch(complete);
11687 return renderTask;
11688 }
11689 getOperatorList({
11690 intent = "display",
11691 annotationMode = AnnotationMode.ENABLE,
11692 printAnnotationStorage = null,
11693 isEditing = false
11694 } = {}) {
11695 function operatorListChanged() {
11696 if (intentState.operatorList.lastChunk) {
11697 intentState.opListReadCapability.resolve(intentState.operatorList);
11698 intentState.renderTasks.delete(opListTask);
11699 }
11700 }
11701 const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, isEditing, true);
11702 let intentState = this._intentStates.get(intentArgs.cacheKey);
11703 if (!intentState) {
11704 intentState = Object.create(null);
11705 this._intentStates.set(intentArgs.cacheKey, intentState);
11706 }
11707 let opListTask;
11708 if (!intentState.opListReadCapability) {
11709 opListTask = Object.create(null);
11710 opListTask.operatorListChanged = operatorListChanged;
11711 intentState.opListReadCapability = Promise.withResolvers();
11712 (intentState.renderTasks ||= new Set()).add(opListTask);
11713 intentState.operatorList = {
11714 fnArray: [],
11715 argsArray: [],
11716 lastChunk: false,
11717 separateAnnots: null
11718 };
11719 this._stats?.time("Page Request");
11720 this._pumpOperatorList(intentArgs);
11721 }
11722 return intentState.opListReadCapability.promise;
11723 }
11724 streamTextContent({
11725 includeMarkedContent = false,
11726 disableNormalization = false
11727 } = {}) {
11728 const TEXT_CONTENT_CHUNK_SIZE = 100;
11729 return this._transport.messageHandler.sendWithStream("GetTextContent", {
11730 pageIndex: this._pageIndex,
11731 includeMarkedContent: includeMarkedContent === true,
11732 disableNormalization: disableNormalization === true
11733 }, {
11734 highWaterMark: TEXT_CONTENT_CHUNK_SIZE,
11735 size(textContent) {
11736 return textContent.items.length;
11737 }
11738 });
11739 }
11740 getTextContent(params = {}) {
11741 if (this._transport._htmlForXfa) {
11742 return this.getXfa().then(xfa => XfaText.textContent(xfa));
11743 }
11744 const readableStream = this.streamTextContent(params);
11745 return new Promise(function (resolve, reject) {
11746 function pump() {
11747 reader.read().then(function ({
11748 value,
11749 done
11750 }) {
11751 if (done) {
11752 resolve(textContent);
11753 return;
11754 }
11755 textContent.lang ??= value.lang;
11756 Object.assign(textContent.styles, value.styles);
11757 textContent.items.push(...value.items);
11758 pump();
11759 }, reject);
11760 }
11761 const reader = readableStream.getReader();
11762 const textContent = {
11763 items: [],
11764 styles: Object.create(null),
11765 lang: null
11766 };
11767 pump();
11768 });
11769 }
11770 getStructTree() {
11771 return this._transport.getStructTree(this._pageIndex);
11772 }
11773 _destroy() {
11774 this.destroyed = true;
11775 const waitOn = [];
11776 for (const intentState of this._intentStates.values()) {
11777 this._abortOperatorList({
11778 intentState,
11779 reason: new Error("Page was destroyed."),
11780 force: true
11781 });
11782 if (intentState.opListReadCapability) {
11783 continue;
11784 }
11785 for (const internalRenderTask of intentState.renderTasks) {
11786 waitOn.push(internalRenderTask.completed);
11787 internalRenderTask.cancel();
11788 }
11789 }
11790 this.objs.clear();
11791 this.#pendingCleanup = false;
11792 this.#abortDelayedCleanup();
11793 return Promise.all(waitOn);
11794 }
11795 cleanup(resetStats = false) {
11796 this.#pendingCleanup = true;
11797 const success = this.#tryCleanup(false);
11798 if (resetStats && success) {
11799 this._stats &&= new StatTimer();
11800 }
11801 return success;
11802 }
11803 #tryCleanup(delayed = false) {
11804 this.#abortDelayedCleanup();
11805 if (!this.#pendingCleanup || this.destroyed) {
11806 return false;
11807 }
11808 if (delayed) {
11809 this.#delayedCleanupTimeout = setTimeout(() => {
11810 this.#delayedCleanupTimeout = null;
11811 this.#tryCleanup(false);
11812 }, DELAYED_CLEANUP_TIMEOUT);
11813 return false;
11814 }
11815 for (const {
11816 renderTasks,
11817 operatorList
11818 } of this._intentStates.values()) {
11819 if (renderTasks.size > 0 || !operatorList.lastChunk) {
11820 return false;
11821 }
11822 }
11823 this._intentStates.clear();
11824 this.objs.clear();
11825 this.#pendingCleanup = false;
11826 return true;
11827 }
11828 #abortDelayedCleanup() {
11829 if (this.#delayedCleanupTimeout) {
11830 clearTimeout(this.#delayedCleanupTimeout);
11831 this.#delayedCleanupTimeout = null;
11832 }
11833 }
11834 _startRenderPage(transparency, cacheKey) {
11835 const intentState = this._intentStates.get(cacheKey);
11836 if (!intentState) {
11837 return;
11838 }
11839 this._stats?.timeEnd("Page Request");
11840 intentState.displayReadyCapability?.resolve(transparency);
11841 }
11842 _renderPageChunk(operatorListChunk, intentState) {
11843 for (let i = 0, ii = operatorListChunk.length; i < ii; i++) {
11844 intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
11845 intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);
11846 }
11847 intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
11848 intentState.operatorList.separateAnnots = operatorListChunk.separateAnnots;
11849 for (const internalRenderTask of intentState.renderTasks) {
11850 internalRenderTask.operatorListChanged();
11851 }
11852 if (operatorListChunk.lastChunk) {
11853 this.#tryCleanup(true);
11854 }
11855 }
11856 _pumpOperatorList({
11857 renderingIntent,
11858 cacheKey,
11859 annotationStorageSerializable,
11860 modifiedIds
11861 }) {
11862 const {
11863 map,
11864 transfer
11865 } = annotationStorageSerializable;
11866 const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", {
11867 pageIndex: this._pageIndex,
11868 intent: renderingIntent,
11869 cacheKey,
11870 annotationStorage: map,
11871 modifiedIds
11872 }, transfer);
11873 const reader = readableStream.getReader();
11874 const intentState = this._intentStates.get(cacheKey);
11875 intentState.streamReader = reader;
11876 const pump = () => {
11877 reader.read().then(({
11878 value,
11879 done
11880 }) => {
11881 if (done) {
11882 intentState.streamReader = null;
11883 return;
11884 }
11885 if (this._transport.destroyed) {
11886 return;
11887 }
11888 this._renderPageChunk(value, intentState);
11889 pump();
11890 }, reason => {
11891 intentState.streamReader = null;
11892 if (this._transport.destroyed) {
11893 return;
11894 }
11895 if (intentState.operatorList) {
11896 intentState.operatorList.lastChunk = true;
11897 for (const internalRenderTask of intentState.renderTasks) {
11898 internalRenderTask.operatorListChanged();
11899 }
11900 this.#tryCleanup(true);
11901 }
11902 if (intentState.displayReadyCapability) {
11903 intentState.displayReadyCapability.reject(reason);
11904 } else if (intentState.opListReadCapability) {
11905 intentState.opListReadCapability.reject(reason);
11906 } else {
11907 throw reason;
11908 }
11909 });
11910 };
11911 pump();
11912 }
11913 _abortOperatorList({
11914 intentState,
11915 reason,
11916 force = false
11917 }) {
11918 if (!intentState.streamReader) {
11919 return;
11920 }
11921 if (intentState.streamReaderCancelTimeout) {
11922 clearTimeout(intentState.streamReaderCancelTimeout);
11923 intentState.streamReaderCancelTimeout = null;
11924 }
11925 if (!force) {
11926 if (intentState.renderTasks.size > 0) {
11927 return;
11928 }
11929 if (reason instanceof RenderingCancelledException) {
11930 let delay = RENDERING_CANCELLED_TIMEOUT;
11931 if (reason.extraDelay > 0 && reason.extraDelay < 1000) {
11932 delay += reason.extraDelay;
11933 }
11934 intentState.streamReaderCancelTimeout = setTimeout(() => {
11935 intentState.streamReaderCancelTimeout = null;
11936 this._abortOperatorList({
11937 intentState,
11938 reason,
11939 force: true
11940 });
11941 }, delay);
11942 return;
11943 }
11944 }
11945 intentState.streamReader.cancel(new AbortException(reason.message)).catch(() => {});
11946 intentState.streamReader = null;
11947 if (this._transport.destroyed) {
11948 return;
11949 }
11950 for (const [curCacheKey, curIntentState] of this._intentStates) {
11951 if (curIntentState === intentState) {
11952 this._intentStates.delete(curCacheKey);
11953 break;
11954 }
11955 }
11956 this.cleanup();
11957 }
11958 get stats() {
11959 return this._stats;
11960 }
11961 }
11962 class LoopbackPort {
11963 #listeners = new Set();
11964 #deferred = Promise.resolve();
11965 postMessage(obj, transfer) {
11966 const event = {
11967 data: structuredClone(obj, transfer ? {
11968 transfer
11969 } : null)
11970 };
11971 this.#deferred.then(() => {
11972 for (const listener of this.#listeners) {
11973 listener.call(this, event);
11974 }
11975 });
11976 }
11977 addEventListener(name, listener) {
11978 this.#listeners.add(listener);
11979 }
11980 removeEventListener(name, listener) {
11981 this.#listeners.delete(listener);
11982 }
11983 terminate() {
11984 this.#listeners.clear();
11985 }
11986 }
11987 class PDFWorker {
11988 static #fakeWorkerId = 0;
11989 static #isWorkerDisabled = false;
11990 static #workerPorts;
11991 static {
11992 if (isNodeJS) {
11993 this.#isWorkerDisabled = true;
11994 GlobalWorkerOptions.workerSrc ||= "./pdf.worker.mjs";
11995 }
11996 this._isSameOrigin = (baseUrl, otherUrl) => {
11997 let base;
11998 try {
11999 base = new URL(baseUrl);
12000 if (!base.origin || base.origin === "null") {
12001 return false;
12002 }
12003 } catch {
12004 return false;
12005 }
12006 const other = new URL(otherUrl, base);
12007 return base.origin === other.origin;
12008 };
12009 this._createCDNWrapper = url => {
12010 const wrapper = `await import("${url}");`;
12011 return URL.createObjectURL(new Blob([wrapper], {
12012 type: "text/javascript"
12013 }));
12014 };
12015 }
12016 constructor({
12017 name = null,
12018 port = null,
12019 verbosity = getVerbosityLevel()
12020 } = {}) {
12021 this.name = name;
12022 this.destroyed = false;
12023 this.verbosity = verbosity;
12024 this._readyCapability = Promise.withResolvers();
12025 this._port = null;
12026 this._webWorker = null;
12027 this._messageHandler = null;
12028 if (port) {
12029 if (PDFWorker.#workerPorts?.has(port)) {
12030 throw new Error("Cannot use more than one PDFWorker per port.");
12031 }
12032 (PDFWorker.#workerPorts ||= new WeakMap()).set(port, this);
12033 this._initializeFromPort(port);
12034 return;
12035 }
12036 this._initialize();
12037 }
12038 get promise() {
12039 if (isNodeJS) {
12040 return Promise.all([NodePackages.promise, this._readyCapability.promise]);
12041 }
12042 return this._readyCapability.promise;
12043 }
12044 #resolve() {
12045 this._readyCapability.resolve();
12046 this._messageHandler.send("configure", {
12047 verbosity: this.verbosity
12048 });
12049 }
12050 get port() {
12051 return this._port;
12052 }
12053 get messageHandler() {
12054 return this._messageHandler;
12055 }
12056 _initializeFromPort(port) {
12057 this._port = port;
12058 this._messageHandler = new MessageHandler("main", "worker", port);
12059 this._messageHandler.on("ready", function () {});
12060 this.#resolve();
12061 }
12062 _initialize() {
12063 if (PDFWorker.#isWorkerDisabled || PDFWorker.#mainThreadWorkerMessageHandler) {
12064 this._setupFakeWorker();
12065 return;
12066 }
12067 let {
12068 workerSrc
12069 } = PDFWorker;
12070 try {
12071 if (!PDFWorker._isSameOrigin(window.location.href, workerSrc)) {
12072 workerSrc = PDFWorker._createCDNWrapper(new URL(workerSrc, window.location).href);
12073 }
12074 const worker = new Worker(workerSrc, {
12075 type: "module"
12076 });
12077 const messageHandler = new MessageHandler("main", "worker", worker);
12078 const terminateEarly = () => {
12079 ac.abort();
12080 messageHandler.destroy();
12081 worker.terminate();
12082 if (this.destroyed) {
12083 this._readyCapability.reject(new Error("Worker was destroyed"));
12084 } else {
12085 this._setupFakeWorker();
12086 }
12087 };
12088 const ac = new AbortController();
12089 worker.addEventListener("error", () => {
12090 if (!this._webWorker) {
12091 terminateEarly();
12092 }
12093 }, {
12094 signal: ac.signal
12095 });
12096 messageHandler.on("test", data => {
12097 ac.abort();
12098 if (this.destroyed || !data) {
12099 terminateEarly();
12100 return;
12101 }
12102 this._messageHandler = messageHandler;
12103 this._port = worker;
12104 this._webWorker = worker;
12105 this.#resolve();
12106 });
12107 messageHandler.on("ready", data => {
12108 ac.abort();
12109 if (this.destroyed) {
12110 terminateEarly();
12111 return;
12112 }
12113 try {
12114 sendTest();
12115 } catch {
12116 this._setupFakeWorker();
12117 }
12118 });
12119 const sendTest = () => {
12120 const testObj = new Uint8Array();
12121 messageHandler.send("test", testObj, [testObj.buffer]);
12122 };
12123 sendTest();
12124 return;
12125 } catch {
12126 info("The worker has been disabled.");
12127 }
12128 this._setupFakeWorker();
12129 }
12130 _setupFakeWorker() {
12131 if (!PDFWorker.#isWorkerDisabled) {
12132 warn("Setting up fake worker.");
12133 PDFWorker.#isWorkerDisabled = true;
12134 }
12135 PDFWorker._setupFakeWorkerGlobal.then(WorkerMessageHandler => {
12136 if (this.destroyed) {
12137 this._readyCapability.reject(new Error("Worker was destroyed"));
12138 return;
12139 }
12140 const port = new LoopbackPort();
12141 this._port = port;
12142 const id = `fake${PDFWorker.#fakeWorkerId++}`;
12143 const workerHandler = new MessageHandler(id + "_worker", id, port);
12144 WorkerMessageHandler.setup(workerHandler, port);
12145 this._messageHandler = new MessageHandler(id, id + "_worker", port);
12146 this.#resolve();
12147 }).catch(reason => {
12148 this._readyCapability.reject(new Error(`Setting up fake worker failed: "${reason.message}".`));
12149 });
12150 }
12151 destroy() {
12152 this.destroyed = true;
12153 if (this._webWorker) {
12154 this._webWorker.terminate();
12155 this._webWorker = null;
12156 }
12157 PDFWorker.#workerPorts?.delete(this._port);
12158 this._port = null;
12159 if (this._messageHandler) {
12160 this._messageHandler.destroy();
12161 this._messageHandler = null;
12162 }
12163 }
12164 static fromPort(params) {
12165 if (!params?.port) {
12166 throw new Error("PDFWorker.fromPort - invalid method signature.");
12167 }
12168 const cachedPort = this.#workerPorts?.get(params.port);
12169 if (cachedPort) {
12170 if (cachedPort._pendingDestroy) {
12171 throw new Error("PDFWorker.fromPort - the worker is being destroyed.\n" + "Please remember to await `PDFDocumentLoadingTask.destroy()`-calls.");
12172 }
12173 return cachedPort;
12174 }
12175 return new PDFWorker(params);
12176 }
12177 static get workerSrc() {
12178 if (GlobalWorkerOptions.workerSrc) {
12179 return GlobalWorkerOptions.workerSrc;
12180 }
12181 throw new Error('No "GlobalWorkerOptions.workerSrc" specified.');
12182 }
12183 static get #mainThreadWorkerMessageHandler() {
12184 try {
12185 return globalThis.pdfjsWorker?.WorkerMessageHandler || null;
12186 } catch {
12187 return null;
12188 }
12189 }
12190 static get _setupFakeWorkerGlobal() {
12191 const loader = async () => {
12192 if (this.#mainThreadWorkerMessageHandler) {
12193 return this.#mainThreadWorkerMessageHandler;
12194 }
12195 const worker = await import(/*webpackIgnore: true*/this.workerSrc);
12196 return worker.WorkerMessageHandler;
12197 };
12198 return shadow(this, "_setupFakeWorkerGlobal", loader());
12199 }
12200 }
12201 class WorkerTransport {
12202 #methodPromises = new Map();
12203 #pageCache = new Map();
12204 #pagePromises = new Map();
12205 #pageRefCache = new Map();
12206 #passwordCapability = null;
12207 constructor(messageHandler, loadingTask, networkStream, params, factory) {
12208 this.messageHandler = messageHandler;
12209 this.loadingTask = loadingTask;
12210 this.commonObjs = new PDFObjects();
12211 this.fontLoader = new FontLoader({
12212 ownerDocument: params.ownerDocument,
12213 styleElement: params.styleElement
12214 });
12215 this.loadingParams = params.loadingParams;
12216 this._params = params;
12217 this.canvasFactory = factory.canvasFactory;
12218 this.filterFactory = factory.filterFactory;
12219 this.cMapReaderFactory = factory.cMapReaderFactory;
12220 this.standardFontDataFactory = factory.standardFontDataFactory;
12221 this.destroyed = false;
12222 this.destroyCapability = null;
12223 this._networkStream = networkStream;
12224 this._fullReader = null;
12225 this._lastProgress = null;
12226 this.downloadInfoCapability = Promise.withResolvers();
12227 this.setupMessageHandler();
12228 }
12229 #cacheSimpleMethod(name, data = null) {
12230 const cachedPromise = this.#methodPromises.get(name);
12231 if (cachedPromise) {
12232 return cachedPromise;
12233 }
12234 const promise = this.messageHandler.sendWithPromise(name, data);
12235 this.#methodPromises.set(name, promise);
12236 return promise;
12237 }
12238 get annotationStorage() {
12239 return shadow(this, "annotationStorage", new AnnotationStorage());
12240 }
12241 getRenderingIntent(intent, annotationMode = AnnotationMode.ENABLE, printAnnotationStorage = null, isEditing = false, isOpList = false) {
12242 let renderingIntent = RenderingIntentFlag.DISPLAY;
12243 let annotationStorageSerializable = SerializableEmpty;
12244 switch (intent) {
12245 case "any":
12246 renderingIntent = RenderingIntentFlag.ANY;
12247 break;
12248 case "display":
12249 break;
12250 case "print":
12251 renderingIntent = RenderingIntentFlag.PRINT;
12252 break;
12253 default:
12254 warn(`getRenderingIntent - invalid intent: ${intent}`);
12255 }
12256 const annotationStorage = renderingIntent & RenderingIntentFlag.PRINT && printAnnotationStorage instanceof PrintAnnotationStorage ? printAnnotationStorage : this.annotationStorage;
12257 switch (annotationMode) {
12258 case AnnotationMode.DISABLE:
12259 renderingIntent += RenderingIntentFlag.ANNOTATIONS_DISABLE;
12260 break;
12261 case AnnotationMode.ENABLE:
12262 break;
12263 case AnnotationMode.ENABLE_FORMS:
12264 renderingIntent += RenderingIntentFlag.ANNOTATIONS_FORMS;
12265 break;
12266 case AnnotationMode.ENABLE_STORAGE:
12267 renderingIntent += RenderingIntentFlag.ANNOTATIONS_STORAGE;
12268 annotationStorageSerializable = annotationStorage.serializable;
12269 break;
12270 default:
12271 warn(`getRenderingIntent - invalid annotationMode: ${annotationMode}`);
12272 }
12273 if (isEditing) {
12274 renderingIntent += RenderingIntentFlag.IS_EDITING;
12275 }
12276 if (isOpList) {
12277 renderingIntent += RenderingIntentFlag.OPLIST;
12278 }
12279 const {
12280 ids: modifiedIds,
12281 hash: modifiedIdsHash
12282 } = annotationStorage.modifiedIds;
12283 const cacheKeyBuf = [renderingIntent, annotationStorageSerializable.hash, modifiedIdsHash];
12284 return {
12285 renderingIntent,
12286 cacheKey: cacheKeyBuf.join("_"),
12287 annotationStorageSerializable,
12288 modifiedIds
12289 };
12290 }
12291 destroy() {
12292 if (this.destroyCapability) {
12293 return this.destroyCapability.promise;
12294 }
12295 this.destroyed = true;
12296 this.destroyCapability = Promise.withResolvers();
12297 this.#passwordCapability?.reject(new Error("Worker was destroyed during onPassword callback"));
12298 const waitOn = [];
12299 for (const page of this.#pageCache.values()) {
12300 waitOn.push(page._destroy());
12301 }
12302 this.#pageCache.clear();
12303 this.#pagePromises.clear();
12304 this.#pageRefCache.clear();
12305 if (this.hasOwnProperty("annotationStorage")) {
12306 this.annotationStorage.resetModified();
12307 }
12308 const terminated = this.messageHandler.sendWithPromise("Terminate", null);
12309 waitOn.push(terminated);
12310 Promise.all(waitOn).then(() => {
12311 this.commonObjs.clear();
12312 this.fontLoader.clear();
12313 this.#methodPromises.clear();
12314 this.filterFactory.destroy();
12315 TextLayer.cleanup();
12316 this._networkStream?.cancelAllRequests(new AbortException("Worker was terminated."));
12317 if (this.messageHandler) {
12318 this.messageHandler.destroy();
12319 this.messageHandler = null;
12320 }
12321 this.destroyCapability.resolve();
12322 }, this.destroyCapability.reject);
12323 return this.destroyCapability.promise;
12324 }
12325 setupMessageHandler() {
12326 const {
12327 messageHandler,
12328 loadingTask
12329 } = this;
12330 messageHandler.on("GetReader", (data, sink) => {
12331 assert(this._networkStream, "GetReader - no `IPDFStream` instance available.");
12332 this._fullReader = this._networkStream.getFullReader();
12333 this._fullReader.onProgress = evt => {
12334 this._lastProgress = {
12335 loaded: evt.loaded,
12336 total: evt.total
12337 };
12338 };
12339 sink.onPull = () => {
12340 this._fullReader.read().then(function ({
12341 value,
12342 done
12343 }) {
12344 if (done) {
12345 sink.close();
12346 return;
12347 }
12348 assert(value instanceof ArrayBuffer, "GetReader - expected an ArrayBuffer.");
12349 sink.enqueue(new Uint8Array(value), 1, [value]);
12350 }).catch(reason => {
12351 sink.error(reason);
12352 });
12353 };
12354 sink.onCancel = reason => {
12355 this._fullReader.cancel(reason);
12356 sink.ready.catch(readyReason => {
12357 if (this.destroyed) {
12358 return;
12359 }
12360 throw readyReason;
12361 });
12362 };
12363 });
12364 messageHandler.on("ReaderHeadersReady", data => {
12365 const headersCapability = Promise.withResolvers();
12366 const fullReader = this._fullReader;
12367 fullReader.headersReady.then(() => {
12368 if (!fullReader.isStreamingSupported || !fullReader.isRangeSupported) {
12369 if (this._lastProgress) {
12370 loadingTask.onProgress?.(this._lastProgress);
12371 }
12372 fullReader.onProgress = evt => {
12373 loadingTask.onProgress?.({
12374 loaded: evt.loaded,
12375 total: evt.total
12376 });
12377 };
12378 }
12379 headersCapability.resolve({
12380 isStreamingSupported: fullReader.isStreamingSupported,
12381 isRangeSupported: fullReader.isRangeSupported,
12382 contentLength: fullReader.contentLength
12383 });
12384 }, headersCapability.reject);
12385 return headersCapability.promise;
12386 });
12387 messageHandler.on("GetRangeReader", (data, sink) => {
12388 assert(this._networkStream, "GetRangeReader - no `IPDFStream` instance available.");
12389 const rangeReader = this._networkStream.getRangeReader(data.begin, data.end);
12390 if (!rangeReader) {
12391 sink.close();
12392 return;
12393 }
12394 sink.onPull = () => {
12395 rangeReader.read().then(function ({
12396 value,
12397 done
12398 }) {
12399 if (done) {
12400 sink.close();
12401 return;
12402 }
12403 assert(value instanceof ArrayBuffer, "GetRangeReader - expected an ArrayBuffer.");
12404 sink.enqueue(new Uint8Array(value), 1, [value]);
12405 }).catch(reason => {
12406 sink.error(reason);
12407 });
12408 };
12409 sink.onCancel = reason => {
12410 rangeReader.cancel(reason);
12411 sink.ready.catch(readyReason => {
12412 if (this.destroyed) {
12413 return;
12414 }
12415 throw readyReason;
12416 });
12417 };
12418 });
12419 messageHandler.on("GetDoc", ({
12420 pdfInfo
12421 }) => {
12422 this._numPages = pdfInfo.numPages;
12423 this._htmlForXfa = pdfInfo.htmlForXfa;
12424 delete pdfInfo.htmlForXfa;
12425 loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this));
12426 });
12427 messageHandler.on("DocException", function (ex) {
12428 let reason;
12429 switch (ex.name) {
12430 case "PasswordException":
12431 reason = new PasswordException(ex.message, ex.code);
12432 break;
12433 case "InvalidPDFException":
12434 reason = new InvalidPDFException(ex.message);
12435 break;
12436 case "MissingPDFException":
12437 reason = new MissingPDFException(ex.message);
12438 break;
12439 case "UnexpectedResponseException":
12440 reason = new UnexpectedResponseException(ex.message, ex.status);
12441 break;
12442 case "UnknownErrorException":
12443 reason = new UnknownErrorException(ex.message, ex.details);
12444 break;
12445 default:
12446 unreachable("DocException - expected a valid Error.");
12447 }
12448 loadingTask._capability.reject(reason);
12449 });
12450 messageHandler.on("PasswordRequest", exception => {
12451 this.#passwordCapability = Promise.withResolvers();
12452 if (loadingTask.onPassword) {
12453 const updatePassword = password => {
12454 if (password instanceof Error) {
12455 this.#passwordCapability.reject(password);
12456 } else {
12457 this.#passwordCapability.resolve({
12458 password
12459 });
12460 }
12461 };
12462 try {
12463 loadingTask.onPassword(updatePassword, exception.code);
12464 } catch (ex) {
12465 this.#passwordCapability.reject(ex);
12466 }
12467 } else {
12468 this.#passwordCapability.reject(new PasswordException(exception.message, exception.code));
12469 }
12470 return this.#passwordCapability.promise;
12471 });
12472 messageHandler.on("DataLoaded", data => {
12473 loadingTask.onProgress?.({
12474 loaded: data.length,
12475 total: data.length
12476 });
12477 this.downloadInfoCapability.resolve(data);
12478 });
12479 messageHandler.on("StartRenderPage", data => {
12480 if (this.destroyed) {
12481 return;
12482 }
12483 const page = this.#pageCache.get(data.pageIndex);
12484 page._startRenderPage(data.transparency, data.cacheKey);
12485 });
12486 messageHandler.on("commonobj", ([id, type, exportedData]) => {
12487 if (this.destroyed) {
12488 return null;
12489 }
12490 if (this.commonObjs.has(id)) {
12491 return null;
12492 }
12493 switch (type) {
12494 case "Font":
12495 const {
12496 disableFontFace,
12497 fontExtraProperties,
12498 pdfBug
12499 } = this._params;
12500 if ("error" in exportedData) {
12501 const exportedError = exportedData.error;
12502 warn(`Error during font loading: ${exportedError}`);
12503 this.commonObjs.resolve(id, exportedError);
12504 break;
12505 }
12506 const inspectFont = pdfBug && globalThis.FontInspector?.enabled ? (font, url) => globalThis.FontInspector.fontAdded(font, url) : null;
12507 const font = new FontFaceObject(exportedData, {
12508 disableFontFace,
12509 inspectFont
12510 });
12511 this.fontLoader.bind(font).catch(() => messageHandler.sendWithPromise("FontFallback", {
12512 id
12513 })).finally(() => {
12514 if (!fontExtraProperties && font.data) {
12515 font.data = null;
12516 }
12517 this.commonObjs.resolve(id, font);
12518 });
12519 break;
12520 case "CopyLocalImage":
12521 const {
12522 imageRef
12523 } = exportedData;
12524 assert(imageRef, "The imageRef must be defined.");
12525 for (const pageProxy of this.#pageCache.values()) {
12526 for (const [, data] of pageProxy.objs) {
12527 if (data?.ref !== imageRef) {
12528 continue;
12529 }
12530 if (!data.dataLen) {
12531 return null;
12532 }
12533 this.commonObjs.resolve(id, structuredClone(data));
12534 return data.dataLen;
12535 }
12536 }
12537 break;
12538 case "FontPath":
12539 case "Image":
12540 case "Pattern":
12541 this.commonObjs.resolve(id, exportedData);
12542 break;
12543 default:
12544 throw new Error(`Got unknown common object type ${type}`);
12545 }
12546 return null;
12547 });
12548 messageHandler.on("obj", ([id, pageIndex, type, imageData]) => {
12549 if (this.destroyed) {
12550 return;
12551 }
12552 const pageProxy = this.#pageCache.get(pageIndex);
12553 if (pageProxy.objs.has(id)) {
12554 return;
12555 }
12556 if (pageProxy._intentStates.size === 0) {
12557 imageData?.bitmap?.close();
12558 return;
12559 }
12560 switch (type) {
12561 case "Image":
12562 pageProxy.objs.resolve(id, imageData);
12563 if (imageData?.dataLen > MAX_IMAGE_SIZE_TO_CACHE) {
12564 pageProxy._maybeCleanupAfterRender = true;
12565 }
12566 break;
12567 case "Pattern":
12568 pageProxy.objs.resolve(id, imageData);
12569 break;
12570 default:
12571 throw new Error(`Got unknown object type ${type}`);
12572 }
12573 });
12574 messageHandler.on("DocProgress", data => {
12575 if (this.destroyed) {
12576 return;
12577 }
12578 loadingTask.onProgress?.({
12579 loaded: data.loaded,
12580 total: data.total
12581 });
12582 });
12583 messageHandler.on("FetchBuiltInCMap", data => {
12584 if (this.destroyed) {
12585 return Promise.reject(new Error("Worker was destroyed."));
12586 }
12587 if (!this.cMapReaderFactory) {
12588 return Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter."));
12589 }
12590 return this.cMapReaderFactory.fetch(data);
12591 });
12592 messageHandler.on("FetchStandardFontData", data => {
12593 if (this.destroyed) {
12594 return Promise.reject(new Error("Worker was destroyed."));
12595 }
12596 if (!this.standardFontDataFactory) {
12597 return Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter."));
12598 }
12599 return this.standardFontDataFactory.fetch(data);
12600 });
12601 }
12602 getData() {
12603 return this.messageHandler.sendWithPromise("GetData", null);
12604 }
12605 saveDocument() {
12606 if (this.annotationStorage.size <= 0) {
12607 warn("saveDocument called while `annotationStorage` is empty, " + "please use the getData-method instead.");
12608 }
12609 const {
12610 map,
12611 transfer
12612 } = this.annotationStorage.serializable;
12613 return this.messageHandler.sendWithPromise("SaveDocument", {
12614 isPureXfa: !!this._htmlForXfa,
12615 numPages: this._numPages,
12616 annotationStorage: map,
12617 filename: this._fullReader?.filename ?? null
12618 }, transfer).finally(() => {
12619 this.annotationStorage.resetModified();
12620 });
12621 }
12622 getPage(pageNumber) {
12623 if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this._numPages) {
12624 return Promise.reject(new Error("Invalid page request."));
12625 }
12626 const pageIndex = pageNumber - 1,
12627 cachedPromise = this.#pagePromises.get(pageIndex);
12628 if (cachedPromise) {
12629 return cachedPromise;
12630 }
12631 const promise = this.messageHandler.sendWithPromise("GetPage", {
12632 pageIndex
12633 }).then(pageInfo => {
12634 if (this.destroyed) {
12635 throw new Error("Transport destroyed");
12636 }
12637 if (pageInfo.refStr) {
12638 this.#pageRefCache.set(pageInfo.refStr, pageNumber);
12639 }
12640 const page = new PDFPageProxy(pageIndex, pageInfo, this, this._params.pdfBug);
12641 this.#pageCache.set(pageIndex, page);
12642 return page;
12643 });
12644 this.#pagePromises.set(pageIndex, promise);
12645 return promise;
12646 }
12647 getPageIndex(ref) {
12648 if (!isRefProxy(ref)) {
12649 return Promise.reject(new Error("Invalid pageIndex request."));
12650 }
12651 return this.messageHandler.sendWithPromise("GetPageIndex", {
12652 num: ref.num,
12653 gen: ref.gen
12654 });
12655 }
12656 getAnnotations(pageIndex, intent) {
12657 return this.messageHandler.sendWithPromise("GetAnnotations", {
12658 pageIndex,
12659 intent
12660 });
12661 }
12662 getFieldObjects() {
12663 return this.#cacheSimpleMethod("GetFieldObjects");
12664 }
12665 hasJSActions() {
12666 return this.#cacheSimpleMethod("HasJSActions");
12667 }
12668 getCalculationOrderIds() {
12669 return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null);
12670 }
12671 getDestinations() {
12672 return this.messageHandler.sendWithPromise("GetDestinations", null);
12673 }
12674 getDestination(id) {
12675 if (typeof id !== "string") {
12676 return Promise.reject(new Error("Invalid destination request."));
12677 }
12678 return this.messageHandler.sendWithPromise("GetDestination", {
12679 id
12680 });
12681 }
12682 getPageLabels() {
12683 return this.messageHandler.sendWithPromise("GetPageLabels", null);
12684 }
12685 getPageLayout() {
12686 return this.messageHandler.sendWithPromise("GetPageLayout", null);
12687 }
12688 getPageMode() {
12689 return this.messageHandler.sendWithPromise("GetPageMode", null);
12690 }
12691 getViewerPreferences() {
12692 return this.messageHandler.sendWithPromise("GetViewerPreferences", null);
12693 }
12694 getOpenAction() {
12695 return this.messageHandler.sendWithPromise("GetOpenAction", null);
12696 }
12697 getAttachments() {
12698 return this.messageHandler.sendWithPromise("GetAttachments", null);
12699 }
12700 getDocJSActions() {
12701 return this.#cacheSimpleMethod("GetDocJSActions");
12702 }
12703 getPageJSActions(pageIndex) {
12704 return this.messageHandler.sendWithPromise("GetPageJSActions", {
12705 pageIndex
12706 });
12707 }
12708 getStructTree(pageIndex) {
12709 return this.messageHandler.sendWithPromise("GetStructTree", {
12710 pageIndex
12711 });
12712 }
12713 getOutline() {
12714 return this.messageHandler.sendWithPromise("GetOutline", null);
12715 }
12716 getOptionalContentConfig(renderingIntent) {
12717 return this.#cacheSimpleMethod("GetOptionalContentConfig").then(data => new OptionalContentConfig(data, renderingIntent));
12718 }
12719 getPermissions() {
12720 return this.messageHandler.sendWithPromise("GetPermissions", null);
12721 }
12722 getMetadata() {
12723 const name = "GetMetadata",
12724 cachedPromise = this.#methodPromises.get(name);
12725 if (cachedPromise) {
12726 return cachedPromise;
12727 }
12728 const promise = this.messageHandler.sendWithPromise(name, null).then(results => ({
12729 info: results[0],
12730 metadata: results[1] ? new Metadata(results[1]) : null,
12731 contentDispositionFilename: this._fullReader?.filename ?? null,
12732 contentLength: this._fullReader?.contentLength ?? null
12733 }));
12734 this.#methodPromises.set(name, promise);
12735 return promise;
12736 }
12737 getMarkInfo() {
12738 return this.messageHandler.sendWithPromise("GetMarkInfo", null);
12739 }
12740 async startCleanup(keepLoadedFonts = false) {
12741 if (this.destroyed) {
12742 return;
12743 }
12744 await this.messageHandler.sendWithPromise("Cleanup", null);
12745 for (const page of this.#pageCache.values()) {
12746 const cleanupSuccessful = page.cleanup();
12747 if (!cleanupSuccessful) {
12748 throw new Error(`startCleanup: Page ${page.pageNumber} is currently rendering.`);
12749 }
12750 }
12751 this.commonObjs.clear();
12752 if (!keepLoadedFonts) {
12753 this.fontLoader.clear();
12754 }
12755 this.#methodPromises.clear();
12756 this.filterFactory.destroy(true);
12757 TextLayer.cleanup();
12758 }
12759 cachedPageNumber(ref) {
12760 if (!isRefProxy(ref)) {
12761 return null;
12762 }
12763 const refStr = ref.gen === 0 ? `${ref.num}R` : `${ref.num}R${ref.gen}`;
12764 return this.#pageRefCache.get(refStr) ?? null;
12765 }
12766 }
12767 const INITIAL_DATA = Symbol("INITIAL_DATA");
12768 class PDFObjects {
12769 #objs = Object.create(null);
12770 #ensureObj(objId) {
12771 return this.#objs[objId] ||= {
12772 ...Promise.withResolvers(),
12773 data: INITIAL_DATA
12774 };
12775 }
12776 get(objId, callback = null) {
12777 if (callback) {
12778 const obj = this.#ensureObj(objId);
12779 obj.promise.then(() => callback(obj.data));
12780 return null;
12781 }
12782 const obj = this.#objs[objId];
12783 if (!obj || obj.data === INITIAL_DATA) {
12784 throw new Error(`Requesting object that isn't resolved yet ${objId}.`);
12785 }
12786 return obj.data;
12787 }
12788 has(objId) {
12789 const obj = this.#objs[objId];
12790 return !!obj && obj.data !== INITIAL_DATA;
12791 }
12792 resolve(objId, data = null) {
12793 const obj = this.#ensureObj(objId);
12794 obj.data = data;
12795 obj.resolve();
12796 }
12797 clear() {
12798 for (const objId in this.#objs) {
12799 const {
12800 data
12801 } = this.#objs[objId];
12802 data?.bitmap?.close();
12803 }
12804 this.#objs = Object.create(null);
12805 }
12806 *[Symbol.iterator]() {
12807 for (const objId in this.#objs) {
12808 const {
12809 data
12810 } = this.#objs[objId];
12811 if (data === INITIAL_DATA) {
12812 continue;
12813 }
12814 yield [objId, data];
12815 }
12816 }
12817 }
12818 class RenderTask {
12819 #internalRenderTask = null;
12820 constructor(internalRenderTask) {
12821 this.#internalRenderTask = internalRenderTask;
12822 this.onContinue = null;
12823 }
12824 get promise() {
12825 return this.#internalRenderTask.capability.promise;
12826 }
12827 cancel(extraDelay = 0) {
12828 this.#internalRenderTask.cancel(null, extraDelay);
12829 }
12830 get separateAnnots() {
12831 const {
12832 separateAnnots
12833 } = this.#internalRenderTask.operatorList;
12834 if (!separateAnnots) {
12835 return false;
12836 }
12837 const {
12838 annotationCanvasMap
12839 } = this.#internalRenderTask;
12840 return separateAnnots.form || separateAnnots.canvas && annotationCanvasMap?.size > 0;
12841 }
12842 }
12843 class InternalRenderTask {
12844 #rAF = null;
12845 static #canvasInUse = new WeakSet();
12846 constructor({
12847 callback,
12848 params,
12849 objs,
12850 commonObjs,
12851 annotationCanvasMap,
12852 operatorList,
12853 pageIndex,
12854 canvasFactory,
12855 filterFactory,
12856 useRequestAnimationFrame = false,
12857 pdfBug = false,
12858 pageColors = null
12859 }) {
12860 this.callback = callback;
12861 this.params = params;
12862 this.objs = objs;
12863 this.commonObjs = commonObjs;
12864 this.annotationCanvasMap = annotationCanvasMap;
12865 this.operatorListIdx = null;
12866 this.operatorList = operatorList;
12867 this._pageIndex = pageIndex;
12868 this.canvasFactory = canvasFactory;
12869 this.filterFactory = filterFactory;
12870 this._pdfBug = pdfBug;
12871 this.pageColors = pageColors;
12872 this.running = false;
12873 this.graphicsReadyCallback = null;
12874 this.graphicsReady = false;
12875 this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== "undefined";
12876 this.cancelled = false;
12877 this.capability = Promise.withResolvers();
12878 this.task = new RenderTask(this);
12879 this._cancelBound = this.cancel.bind(this);
12880 this._continueBound = this._continue.bind(this);
12881 this._scheduleNextBound = this._scheduleNext.bind(this);
12882 this._nextBound = this._next.bind(this);
12883 this._canvas = params.canvasContext.canvas;
12884 }
12885 get completed() {
12886 return this.capability.promise.catch(function () {});
12887 }
12888 initializeGraphics({
12889 transparency = false,
12890 optionalContentConfig
12891 }) {
12892 if (this.cancelled) {
12893 return;
12894 }
12895 if (this._canvas) {
12896 if (InternalRenderTask.#canvasInUse.has(this._canvas)) {
12897 throw new Error("Cannot use the same canvas during multiple render() operations. " + "Use different canvas or ensure previous operations were " + "cancelled or completed.");
12898 }
12899 InternalRenderTask.#canvasInUse.add(this._canvas);
12900 }
12901 if (this._pdfBug && globalThis.StepperManager?.enabled) {
12902 this.stepper = globalThis.StepperManager.create(this._pageIndex);
12903 this.stepper.init(this.operatorList);
12904 this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
12905 }
12906 const {
12907 canvasContext,
12908 viewport,
12909 transform,
12910 background
12911 } = this.params;
12912 this.gfx = new CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, {
12913 optionalContentConfig
12914 }, this.annotationCanvasMap, this.pageColors);
12915 this.gfx.beginDrawing({
12916 transform,
12917 viewport,
12918 transparency,
12919 background
12920 });
12921 this.operatorListIdx = 0;
12922 this.graphicsReady = true;
12923 this.graphicsReadyCallback?.();
12924 }
12925 cancel(error = null, extraDelay = 0) {
12926 this.running = false;
12927 this.cancelled = true;
12928 this.gfx?.endDrawing();
12929 if (this.#rAF) {
12930 window.cancelAnimationFrame(this.#rAF);
12931 this.#rAF = null;
12932 }
12933 InternalRenderTask.#canvasInUse.delete(this._canvas);
12934 this.callback(error || new RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, extraDelay));
12935 }
12936 operatorListChanged() {
12937 if (!this.graphicsReady) {
12938 this.graphicsReadyCallback ||= this._continueBound;
12939 return;
12940 }
12941 this.stepper?.updateOperatorList(this.operatorList);
12942 if (this.running) {
12943 return;
12944 }
12945 this._continue();
12946 }
12947 _continue() {
12948 this.running = true;
12949 if (this.cancelled) {
12950 return;
12951 }
12952 if (this.task.onContinue) {
12953 this.task.onContinue(this._scheduleNextBound);
12954 } else {
12955 this._scheduleNext();
12956 }
12957 }
12958 _scheduleNext() {
12959 if (this._useRequestAnimationFrame) {
12960 this.#rAF = window.requestAnimationFrame(() => {
12961 this.#rAF = null;
12962 this._nextBound().catch(this._cancelBound);
12963 });
12964 } else {
12965 Promise.resolve().then(this._nextBound).catch(this._cancelBound);
12966 }
12967 }
12968 async _next() {
12969 if (this.cancelled) {
12970 return;
12971 }
12972 this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper);
12973 if (this.operatorListIdx === this.operatorList.argsArray.length) {
12974 this.running = false;
12975 if (this.operatorList.lastChunk) {
12976 this.gfx.endDrawing();
12977 InternalRenderTask.#canvasInUse.delete(this._canvas);
12978 this.callback();
12979 }
12980 }
12981 }
12982 }
12983 const version = "4.7.76";
12984 const build = "8b73b828b";
12985
12986 ;// ./src/shared/scripting_utils.js
12987 function makeColorComp(n) {
12988 return Math.floor(Math.max(0, Math.min(1, n)) * 255).toString(16).padStart(2, "0");
12989 }
12990 function scaleAndClamp(x) {
12991 return Math.max(0, Math.min(255, 255 * x));
12992 }
12993 class ColorConverters {
12994 static CMYK_G([c, y, m, k]) {
12995 return ["G", 1 - Math.min(1, 0.3 * c + 0.59 * m + 0.11 * y + k)];
12996 }
12997 static G_CMYK([g]) {
12998 return ["CMYK", 0, 0, 0, 1 - g];
12999 }
13000 static G_RGB([g]) {
13001 return ["RGB", g, g, g];
13002 }
13003 static G_rgb([g]) {
13004 g = scaleAndClamp(g);
13005 return [g, g, g];
13006 }
13007 static G_HTML([g]) {
13008 const G = makeColorComp(g);
13009 return `#${G}${G}${G}`;
13010 }
13011 static RGB_G([r, g, b]) {
13012 return ["G", 0.3 * r + 0.59 * g + 0.11 * b];
13013 }
13014 static RGB_rgb(color) {
13015 return color.map(scaleAndClamp);
13016 }
13017 static RGB_HTML(color) {
13018 return `#${color.map(makeColorComp).join("")}`;
13019 }
13020 static T_HTML() {
13021 return "#00000000";
13022 }
13023 static T_rgb() {
13024 return [null];
13025 }
13026 static CMYK_RGB([c, y, m, k]) {
13027 return ["RGB", 1 - Math.min(1, c + k), 1 - Math.min(1, m + k), 1 - Math.min(1, y + k)];
13028 }
13029 static CMYK_rgb([c, y, m, k]) {
13030 return [scaleAndClamp(1 - Math.min(1, c + k)), scaleAndClamp(1 - Math.min(1, m + k)), scaleAndClamp(1 - Math.min(1, y + k))];
13031 }
13032 static CMYK_HTML(components) {
13033 const rgb = this.CMYK_RGB(components).slice(1);
13034 return this.RGB_HTML(rgb);
13035 }
13036 static RGB_CMYK([r, g, b]) {
13037 const c = 1 - r;
13038 const m = 1 - g;
13039 const y = 1 - b;
13040 const k = Math.min(c, m, y);
13041 return ["CMYK", c, m, y, k];
13042 }
13043 }
13044
13045 ;// ./src/display/xfa_layer.js
13046
13047 class XfaLayer {
13048 static setupStorage(html, id, element, storage, intent) {
13049 const storedData = storage.getValue(id, {
13050 value: null
13051 });
13052 switch (element.name) {
13053 case "textarea":
13054 if (storedData.value !== null) {
13055 html.textContent = storedData.value;
13056 }
13057 if (intent === "print") {
13058 break;
13059 }
13060 html.addEventListener("input", event => {
13061 storage.setValue(id, {
13062 value: event.target.value
13063 });
13064 });
13065 break;
13066 case "input":
13067 if (element.attributes.type === "radio" || element.attributes.type === "checkbox") {
13068 if (storedData.value === element.attributes.xfaOn) {
13069 html.setAttribute("checked", true);
13070 } else if (storedData.value === element.attributes.xfaOff) {
13071 html.removeAttribute("checked");
13072 }
13073 if (intent === "print") {
13074 break;
13075 }
13076 html.addEventListener("change", event => {
13077 storage.setValue(id, {
13078 value: event.target.checked ? event.target.getAttribute("xfaOn") : event.target.getAttribute("xfaOff")
13079 });
13080 });
13081 } else {
13082 if (storedData.value !== null) {
13083 html.setAttribute("value", storedData.value);
13084 }
13085 if (intent === "print") {
13086 break;
13087 }
13088 html.addEventListener("input", event => {
13089 storage.setValue(id, {
13090 value: event.target.value
13091 });
13092 });
13093 }
13094 break;
13095 case "select":
13096 if (storedData.value !== null) {
13097 html.setAttribute("value", storedData.value);
13098 for (const option of element.children) {
13099 if (option.attributes.value === storedData.value) {
13100 option.attributes.selected = true;
13101 } else if (option.attributes.hasOwnProperty("selected")) {
13102 delete option.attributes.selected;
13103 }
13104 }
13105 }
13106 html.addEventListener("input", event => {
13107 const options = event.target.options;
13108 const value = options.selectedIndex === -1 ? "" : options[options.selectedIndex].value;
13109 storage.setValue(id, {
13110 value
13111 });
13112 });
13113 break;
13114 }
13115 }
13116 static setAttributes({
13117 html,
13118 element,
13119 storage = null,
13120 intent,
13121 linkService
13122 }) {
13123 const {
13124 attributes
13125 } = element;
13126 const isHTMLAnchorElement = html instanceof HTMLAnchorElement;
13127 if (attributes.type === "radio") {
13128 attributes.name = `${attributes.name}-${intent}`;
13129 }
13130 for (const [key, value] of Object.entries(attributes)) {
13131 if (value === null || value === undefined) {
13132 continue;
13133 }
13134 switch (key) {
13135 case "class":
13136 if (value.length) {
13137 html.setAttribute(key, value.join(" "));
13138 }
13139 break;
13140 case "dataId":
13141 break;
13142 case "id":
13143 html.setAttribute("data-element-id", value);
13144 break;
13145 case "style":
13146 Object.assign(html.style, value);
13147 break;
13148 case "textContent":
13149 html.textContent = value;
13150 break;
13151 default:
13152 if (!isHTMLAnchorElement || key !== "href" && key !== "newWindow") {
13153 html.setAttribute(key, value);
13154 }
13155 }
13156 }
13157 if (isHTMLAnchorElement) {
13158 linkService.addLinkAttributes(html, attributes.href, attributes.newWindow);
13159 }
13160 if (storage && attributes.dataId) {
13161 this.setupStorage(html, attributes.dataId, element, storage);
13162 }
13163 }
13164 static render(parameters) {
13165 const storage = parameters.annotationStorage;
13166 const linkService = parameters.linkService;
13167 const root = parameters.xfaHtml;
13168 const intent = parameters.intent || "display";
13169 const rootHtml = document.createElement(root.name);
13170 if (root.attributes) {
13171 this.setAttributes({
13172 html: rootHtml,
13173 element: root,
13174 intent,
13175 linkService
13176 });
13177 }
13178 const isNotForRichText = intent !== "richText";
13179 const rootDiv = parameters.div;
13180 rootDiv.append(rootHtml);
13181 if (parameters.viewport) {
13182 const transform = `matrix(${parameters.viewport.transform.join(",")})`;
13183 rootDiv.style.transform = transform;
13184 }
13185 if (isNotForRichText) {
13186 rootDiv.setAttribute("class", "xfaLayer xfaFont");
13187 }
13188 const textDivs = [];
13189 if (root.children.length === 0) {
13190 if (root.value) {
13191 const node = document.createTextNode(root.value);
13192 rootHtml.append(node);
13193 if (isNotForRichText && XfaText.shouldBuildText(root.name)) {
13194 textDivs.push(node);
13195 }
13196 }
13197 return {
13198 textDivs
13199 };
13200 }
13201 const stack = [[root, -1, rootHtml]];
13202 while (stack.length > 0) {
13203 const [parent, i, html] = stack.at(-1);
13204 if (i + 1 === parent.children.length) {
13205 stack.pop();
13206 continue;
13207 }
13208 const child = parent.children[++stack.at(-1)[1]];
13209 if (child === null) {
13210 continue;
13211 }
13212 const {
13213 name
13214 } = child;
13215 if (name === "#text") {
13216 const node = document.createTextNode(child.value);
13217 textDivs.push(node);
13218 html.append(node);
13219 continue;
13220 }
13221 const childHtml = child?.attributes?.xmlns ? document.createElementNS(child.attributes.xmlns, name) : document.createElement(name);
13222 html.append(childHtml);
13223 if (child.attributes) {
13224 this.setAttributes({
13225 html: childHtml,
13226 element: child,
13227 storage,
13228 intent,
13229 linkService
13230 });
13231 }
13232 if (child.children?.length > 0) {
13233 stack.push([child, -1, childHtml]);
13234 } else if (child.value) {
13235 const node = document.createTextNode(child.value);
13236 if (isNotForRichText && XfaText.shouldBuildText(name)) {
13237 textDivs.push(node);
13238 }
13239 childHtml.append(node);
13240 }
13241 }
13242 for (const el of rootDiv.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea")) {
13243 el.setAttribute("readOnly", true);
13244 }
13245 return {
13246 textDivs
13247 };
13248 }
13249 static update(parameters) {
13250 const transform = `matrix(${parameters.viewport.transform.join(",")})`;
13251 parameters.div.style.transform = transform;
13252 parameters.div.hidden = false;
13253 }
13254 }
13255
13256 ;// ./src/display/annotation_layer.js
13257
13258
13259
13260
13261
13262 const DEFAULT_TAB_INDEX = 1000;
13263 const annotation_layer_DEFAULT_FONT_SIZE = 9;
13264 const GetElementsByNameSet = new WeakSet();
13265 function getRectDims(rect) {
13266 return {
13267 width: rect[2] - rect[0],
13268 height: rect[3] - rect[1]
13269 };
13270 }
13271 class AnnotationElementFactory {
13272 static create(parameters) {
13273 const subtype = parameters.data.annotationType;
13274 switch (subtype) {
13275 case AnnotationType.LINK:
13276 return new LinkAnnotationElement(parameters);
13277 case AnnotationType.TEXT:
13278 return new TextAnnotationElement(parameters);
13279 case AnnotationType.WIDGET:
13280 const fieldType = parameters.data.fieldType;
13281 switch (fieldType) {
13282 case "Tx":
13283 return new TextWidgetAnnotationElement(parameters);
13284 case "Btn":
13285 if (parameters.data.radioButton) {
13286 return new RadioButtonWidgetAnnotationElement(parameters);
13287 } else if (parameters.data.checkBox) {
13288 return new CheckboxWidgetAnnotationElement(parameters);
13289 }
13290 return new PushButtonWidgetAnnotationElement(parameters);
13291 case "Ch":
13292 return new ChoiceWidgetAnnotationElement(parameters);
13293 case "Sig":
13294 return new SignatureWidgetAnnotationElement(parameters);
13295 }
13296 return new WidgetAnnotationElement(parameters);
13297 case AnnotationType.POPUP:
13298 return new PopupAnnotationElement(parameters);
13299 case AnnotationType.FREETEXT:
13300 return new FreeTextAnnotationElement(parameters);
13301 case AnnotationType.LINE:
13302 return new LineAnnotationElement(parameters);
13303 case AnnotationType.SQUARE:
13304 return new SquareAnnotationElement(parameters);
13305 case AnnotationType.CIRCLE:
13306 return new CircleAnnotationElement(parameters);
13307 case AnnotationType.POLYLINE:
13308 return new PolylineAnnotationElement(parameters);
13309 case AnnotationType.CARET:
13310 return new CaretAnnotationElement(parameters);
13311 case AnnotationType.INK:
13312 return new InkAnnotationElement(parameters);
13313 case AnnotationType.POLYGON:
13314 return new PolygonAnnotationElement(parameters);
13315 case AnnotationType.HIGHLIGHT:
13316 return new HighlightAnnotationElement(parameters);
13317 case AnnotationType.UNDERLINE:
13318 return new UnderlineAnnotationElement(parameters);
13319 case AnnotationType.SQUIGGLY:
13320 return new SquigglyAnnotationElement(parameters);
13321 case AnnotationType.STRIKEOUT:
13322 return new StrikeOutAnnotationElement(parameters);
13323 case AnnotationType.STAMP:
13324 return new StampAnnotationElement(parameters);
13325 case AnnotationType.FILEATTACHMENT:
13326 return new FileAttachmentAnnotationElement(parameters);
13327 default:
13328 return new AnnotationElement(parameters);
13329 }
13330 }
13331 }
13332 class AnnotationElement {
13333 #updates = null;
13334 #hasBorder = false;
13335 #popupElement = null;
13336 constructor(parameters, {
13337 isRenderable = false,
13338 ignoreBorder = false,
13339 createQuadrilaterals = false
13340 } = {}) {
13341 this.isRenderable = isRenderable;
13342 this.data = parameters.data;
13343 this.layer = parameters.layer;
13344 this.linkService = parameters.linkService;
13345 this.downloadManager = parameters.downloadManager;
13346 this.imageResourcesPath = parameters.imageResourcesPath;
13347 this.renderForms = parameters.renderForms;
13348 this.svgFactory = parameters.svgFactory;
13349 this.annotationStorage = parameters.annotationStorage;
13350 this.enableScripting = parameters.enableScripting;
13351 this.hasJSActions = parameters.hasJSActions;
13352 this._fieldObjects = parameters.fieldObjects;
13353 this.parent = parameters.parent;
13354 if (isRenderable) {
13355 this.container = this._createContainer(ignoreBorder);
13356 }
13357 if (createQuadrilaterals) {
13358 this._createQuadrilaterals();
13359 }
13360 }
13361 static _hasPopupData({
13362 titleObj,
13363 contentsObj,
13364 richText
13365 }) {
13366 return !!(titleObj?.str || contentsObj?.str || richText?.str);
13367 }
13368 get _isEditable() {
13369 return this.data.isEditable;
13370 }
13371 get hasPopupData() {
13372 return AnnotationElement._hasPopupData(this.data);
13373 }
13374 updateEdited(params) {
13375 if (!this.container) {
13376 return;
13377 }
13378 this.#updates ||= {
13379 rect: this.data.rect.slice(0)
13380 };
13381 const {
13382 rect
13383 } = params;
13384 if (rect) {
13385 this.#setRectEdited(rect);
13386 }
13387 this.#popupElement?.popup.updateEdited(params);
13388 }
13389 resetEdited() {
13390 if (!this.#updates) {
13391 return;
13392 }
13393 this.#setRectEdited(this.#updates.rect);
13394 this.#popupElement?.popup.resetEdited();
13395 this.#updates = null;
13396 }
13397 #setRectEdited(rect) {
13398 const {
13399 container: {
13400 style
13401 },
13402 data: {
13403 rect: currentRect,
13404 rotation
13405 },
13406 parent: {
13407 viewport: {
13408 rawDims: {
13409 pageWidth,
13410 pageHeight,
13411 pageX,
13412 pageY
13413 }
13414 }
13415 }
13416 } = this;
13417 currentRect?.splice(0, 4, ...rect);
13418 const {
13419 width,
13420 height
13421 } = getRectDims(rect);
13422 style.left = `${100 * (rect[0] - pageX) / pageWidth}%`;
13423 style.top = `${100 * (pageHeight - rect[3] + pageY) / pageHeight}%`;
13424 if (rotation === 0) {
13425 style.width = `${100 * width / pageWidth}%`;
13426 style.height = `${100 * height / pageHeight}%`;
13427 } else {
13428 this.setRotation(rotation);
13429 }
13430 }
13431 _createContainer(ignoreBorder) {
13432 const {
13433 data,
13434 parent: {
13435 page,
13436 viewport
13437 }
13438 } = this;
13439 const container = document.createElement("section");
13440 container.setAttribute("data-annotation-id", data.id);
13441 if (!(this instanceof WidgetAnnotationElement)) {
13442 container.tabIndex = DEFAULT_TAB_INDEX;
13443 }
13444 const {
13445 style
13446 } = container;
13447 style.zIndex = this.parent.zIndex++;
13448 if (data.popupRef) {
13449 container.setAttribute("aria-haspopup", "dialog");
13450 }
13451 if (data.alternativeText) {
13452 container.title = data.alternativeText;
13453 }
13454 if (data.noRotate) {
13455 container.classList.add("norotate");
13456 }
13457 if (!data.rect || this instanceof PopupAnnotationElement) {
13458 const {
13459 rotation
13460 } = data;
13461 if (!data.hasOwnCanvas && rotation !== 0) {
13462 this.setRotation(rotation, container);
13463 }
13464 return container;
13465 }
13466 const {
13467 width,
13468 height
13469 } = getRectDims(data.rect);
13470 if (!ignoreBorder && data.borderStyle.width > 0) {
13471 style.borderWidth = `${data.borderStyle.width}px`;
13472 const horizontalRadius = data.borderStyle.horizontalCornerRadius;
13473 const verticalRadius = data.borderStyle.verticalCornerRadius;
13474 if (horizontalRadius > 0 || verticalRadius > 0) {
13475 const radius = `calc(${horizontalRadius}px * var(--scale-factor)) / calc(${verticalRadius}px * var(--scale-factor))`;
13476 style.borderRadius = radius;
13477 } else if (this instanceof RadioButtonWidgetAnnotationElement) {
13478 const radius = `calc(${width}px * var(--scale-factor)) / calc(${height}px * var(--scale-factor))`;
13479 style.borderRadius = radius;
13480 }
13481 switch (data.borderStyle.style) {
13482 case AnnotationBorderStyleType.SOLID:
13483 style.borderStyle = "solid";
13484 break;
13485 case AnnotationBorderStyleType.DASHED:
13486 style.borderStyle = "dashed";
13487 break;
13488 case AnnotationBorderStyleType.BEVELED:
13489 warn("Unimplemented border style: beveled");
13490 break;
13491 case AnnotationBorderStyleType.INSET:
13492 warn("Unimplemented border style: inset");
13493 break;
13494 case AnnotationBorderStyleType.UNDERLINE:
13495 style.borderBottomStyle = "solid";
13496 break;
13497 default:
13498 break;
13499 }
13500 const borderColor = data.borderColor || null;
13501 if (borderColor) {
13502 this.#hasBorder = true;
13503 style.borderColor = Util.makeHexColor(borderColor[0] | 0, borderColor[1] | 0, borderColor[2] | 0);
13504 } else {
13505 style.borderWidth = 0;
13506 }
13507 }
13508 const rect = Util.normalizeRect([data.rect[0], page.view[3] - data.rect[1] + page.view[1], data.rect[2], page.view[3] - data.rect[3] + page.view[1]]);
13509 const {
13510 pageWidth,
13511 pageHeight,
13512 pageX,
13513 pageY
13514 } = viewport.rawDims;
13515 style.left = `${100 * (rect[0] - pageX) / pageWidth}%`;
13516 style.top = `${100 * (rect[1] - pageY) / pageHeight}%`;
13517 const {
13518 rotation
13519 } = data;
13520 if (data.hasOwnCanvas || rotation === 0) {
13521 style.width = `${100 * width / pageWidth}%`;
13522 style.height = `${100 * height / pageHeight}%`;
13523 } else {
13524 this.setRotation(rotation, container);
13525 }
13526 return container;
13527 }
13528 setRotation(angle, container = this.container) {
13529 if (!this.data.rect) {
13530 return;
13531 }
13532 const {
13533 pageWidth,
13534 pageHeight
13535 } = this.parent.viewport.rawDims;
13536 const {
13537 width,
13538 height
13539 } = getRectDims(this.data.rect);
13540 let elementWidth, elementHeight;
13541 if (angle % 180 === 0) {
13542 elementWidth = 100 * width / pageWidth;
13543 elementHeight = 100 * height / pageHeight;
13544 } else {
13545 elementWidth = 100 * height / pageWidth;
13546 elementHeight = 100 * width / pageHeight;
13547 }
13548 container.style.width = `${elementWidth}%`;
13549 container.style.height = `${elementHeight}%`;
13550 container.setAttribute("data-main-rotation", (360 - angle) % 360);
13551 }
13552 get _commonActions() {
13553 const setColor = (jsName, styleName, event) => {
13554 const color = event.detail[jsName];
13555 const colorType = color[0];
13556 const colorArray = color.slice(1);
13557 event.target.style[styleName] = ColorConverters[`${colorType}_HTML`](colorArray);
13558 this.annotationStorage.setValue(this.data.id, {
13559 [styleName]: ColorConverters[`${colorType}_rgb`](colorArray)
13560 });
13561 };
13562 return shadow(this, "_commonActions", {
13563 display: event => {
13564 const {
13565 display
13566 } = event.detail;
13567 const hidden = display % 2 === 1;
13568 this.container.style.visibility = hidden ? "hidden" : "visible";
13569 this.annotationStorage.setValue(this.data.id, {
13570 noView: hidden,
13571 noPrint: display === 1 || display === 2
13572 });
13573 },
13574 print: event => {
13575 this.annotationStorage.setValue(this.data.id, {
13576 noPrint: !event.detail.print
13577 });
13578 },
13579 hidden: event => {
13580 const {
13581 hidden
13582 } = event.detail;
13583 this.container.style.visibility = hidden ? "hidden" : "visible";
13584 this.annotationStorage.setValue(this.data.id, {
13585 noPrint: hidden,
13586 noView: hidden
13587 });
13588 },
13589 focus: event => {
13590 setTimeout(() => event.target.focus({
13591 preventScroll: false
13592 }), 0);
13593 },
13594 userName: event => {
13595 event.target.title = event.detail.userName;
13596 },
13597 readonly: event => {
13598 event.target.disabled = event.detail.readonly;
13599 },
13600 required: event => {
13601 this._setRequired(event.target, event.detail.required);
13602 },
13603 bgColor: event => {
13604 setColor("bgColor", "backgroundColor", event);
13605 },
13606 fillColor: event => {
13607 setColor("fillColor", "backgroundColor", event);
13608 },
13609 fgColor: event => {
13610 setColor("fgColor", "color", event);
13611 },
13612 textColor: event => {
13613 setColor("textColor", "color", event);
13614 },
13615 borderColor: event => {
13616 setColor("borderColor", "borderColor", event);
13617 },
13618 strokeColor: event => {
13619 setColor("strokeColor", "borderColor", event);
13620 },
13621 rotation: event => {
13622 const angle = event.detail.rotation;
13623 this.setRotation(angle);
13624 this.annotationStorage.setValue(this.data.id, {
13625 rotation: angle
13626 });
13627 }
13628 });
13629 }
13630 _dispatchEventFromSandbox(actions, jsEvent) {
13631 const commonActions = this._commonActions;
13632 for (const name of Object.keys(jsEvent.detail)) {
13633 const action = actions[name] || commonActions[name];
13634 action?.(jsEvent);
13635 }
13636 }
13637 _setDefaultPropertiesFromJS(element) {
13638 if (!this.enableScripting) {
13639 return;
13640 }
13641 const storedData = this.annotationStorage.getRawValue(this.data.id);
13642 if (!storedData) {
13643 return;
13644 }
13645 const commonActions = this._commonActions;
13646 for (const [actionName, detail] of Object.entries(storedData)) {
13647 const action = commonActions[actionName];
13648 if (action) {
13649 const eventProxy = {
13650 detail: {
13651 [actionName]: detail
13652 },
13653 target: element
13654 };
13655 action(eventProxy);
13656 delete storedData[actionName];
13657 }
13658 }
13659 }
13660 _createQuadrilaterals() {
13661 if (!this.container) {
13662 return;
13663 }
13664 const {
13665 quadPoints
13666 } = this.data;
13667 if (!quadPoints) {
13668 return;
13669 }
13670 const [rectBlX, rectBlY, rectTrX, rectTrY] = this.data.rect.map(x => Math.fround(x));
13671 if (quadPoints.length === 8) {
13672 const [trX, trY, blX, blY] = quadPoints.subarray(2, 6);
13673 if (rectTrX === trX && rectTrY === trY && rectBlX === blX && rectBlY === blY) {
13674 return;
13675 }
13676 }
13677 const {
13678 style
13679 } = this.container;
13680 let svgBuffer;
13681 if (this.#hasBorder) {
13682 const {
13683 borderColor,
13684 borderWidth
13685 } = style;
13686 style.borderWidth = 0;
13687 svgBuffer = ["url('data:image/svg+xml;utf8,", `<svg xmlns="http://www.w3.org/2000/svg"`, ` preserveAspectRatio="none" viewBox="0 0 1 1">`, `<g fill="transparent" stroke="${borderColor}" stroke-width="${borderWidth}">`];
13688 this.container.classList.add("hasBorder");
13689 }
13690 const width = rectTrX - rectBlX;
13691 const height = rectTrY - rectBlY;
13692 const {
13693 svgFactory
13694 } = this;
13695 const svg = svgFactory.createElement("svg");
13696 svg.classList.add("quadrilateralsContainer");
13697 svg.setAttribute("width", 0);
13698 svg.setAttribute("height", 0);
13699 const defs = svgFactory.createElement("defs");
13700 svg.append(defs);
13701 const clipPath = svgFactory.createElement("clipPath");
13702 const id = `clippath_${this.data.id}`;
13703 clipPath.setAttribute("id", id);
13704 clipPath.setAttribute("clipPathUnits", "objectBoundingBox");
13705 defs.append(clipPath);
13706 for (let i = 2, ii = quadPoints.length; i < ii; i += 8) {
13707 const trX = quadPoints[i];
13708 const trY = quadPoints[i + 1];
13709 const blX = quadPoints[i + 2];
13710 const blY = quadPoints[i + 3];
13711 const rect = svgFactory.createElement("rect");
13712 const x = (blX - rectBlX) / width;
13713 const y = (rectTrY - trY) / height;
13714 const rectWidth = (trX - blX) / width;
13715 const rectHeight = (trY - blY) / height;
13716 rect.setAttribute("x", x);
13717 rect.setAttribute("y", y);
13718 rect.setAttribute("width", rectWidth);
13719 rect.setAttribute("height", rectHeight);
13720 clipPath.append(rect);
13721 svgBuffer?.push(`<rect vector-effect="non-scaling-stroke" x="${x}" y="${y}" width="${rectWidth}" height="${rectHeight}"/>`);
13722 }
13723 if (this.#hasBorder) {
13724 svgBuffer.push(`</g></svg>')`);
13725 style.backgroundImage = svgBuffer.join("");
13726 }
13727 this.container.append(svg);
13728 this.container.style.clipPath = `url(#${id})`;
13729 }
13730 _createPopup() {
13731 const {
13732 container,
13733 data
13734 } = this;
13735 container.setAttribute("aria-haspopup", "dialog");
13736 const popup = this.#popupElement = new PopupAnnotationElement({
13737 data: {
13738 color: data.color,
13739 titleObj: data.titleObj,
13740 modificationDate: data.modificationDate,
13741 contentsObj: data.contentsObj,
13742 richText: data.richText,
13743 parentRect: data.rect,
13744 borderStyle: 0,
13745 id: `popup_${data.id}`,
13746 rotation: data.rotation
13747 },
13748 parent: this.parent,
13749 elements: [this]
13750 });
13751 this.parent.div.append(popup.render());
13752 }
13753 render() {
13754 unreachable("Abstract method `AnnotationElement.render` called");
13755 }
13756 _getElementsByName(name, skipId = null) {
13757 const fields = [];
13758 if (this._fieldObjects) {
13759 const fieldObj = this._fieldObjects[name];
13760 if (fieldObj) {
13761 for (const {
13762 page,
13763 id,
13764 exportValues
13765 } of fieldObj) {
13766 if (page === -1) {
13767 continue;
13768 }
13769 if (id === skipId) {
13770 continue;
13771 }
13772 const exportValue = typeof exportValues === "string" ? exportValues : null;
13773 const domElement = document.querySelector(`[data-element-id="${id}"]`);
13774 if (domElement && !GetElementsByNameSet.has(domElement)) {
13775 warn(`_getElementsByName - element not allowed: ${id}`);
13776 continue;
13777 }
13778 fields.push({
13779 id,
13780 exportValue,
13781 domElement
13782 });
13783 }
13784 }
13785 return fields;
13786 }
13787 for (const domElement of document.getElementsByName(name)) {
13788 const {
13789 exportValue
13790 } = domElement;
13791 const id = domElement.getAttribute("data-element-id");
13792 if (id === skipId) {
13793 continue;
13794 }
13795 if (!GetElementsByNameSet.has(domElement)) {
13796 continue;
13797 }
13798 fields.push({
13799 id,
13800 exportValue,
13801 domElement
13802 });
13803 }
13804 return fields;
13805 }
13806 show() {
13807 if (this.container) {
13808 this.container.hidden = false;
13809 }
13810 this.popup?.maybeShow();
13811 }
13812 hide() {
13813 if (this.container) {
13814 this.container.hidden = true;
13815 }
13816 this.popup?.forceHide();
13817 }
13818 getElementsToTriggerPopup() {
13819 return this.container;
13820 }
13821 addHighlightArea() {
13822 const triggers = this.getElementsToTriggerPopup();
13823 if (Array.isArray(triggers)) {
13824 for (const element of triggers) {
13825 element.classList.add("highlightArea");
13826 }
13827 } else {
13828 triggers.classList.add("highlightArea");
13829 }
13830 }
13831 _editOnDoubleClick() {
13832 if (!this._isEditable) {
13833 return;
13834 }
13835 const {
13836 annotationEditorType: mode,
13837 data: {
13838 id: editId
13839 }
13840 } = this;
13841 this.container.addEventListener("dblclick", () => {
13842 this.linkService.eventBus?.dispatch("switchannotationeditormode", {
13843 source: this,
13844 mode,
13845 editId
13846 });
13847 });
13848 }
13849 }
13850 class LinkAnnotationElement extends AnnotationElement {
13851 constructor(parameters, options = null) {
13852 super(parameters, {
13853 isRenderable: true,
13854 ignoreBorder: !!options?.ignoreBorder,
13855 createQuadrilaterals: true
13856 });
13857 this.isTooltipOnly = parameters.data.isTooltipOnly;
13858 }
13859 render() {
13860 const {
13861 data,
13862 linkService
13863 } = this;
13864 const link = document.createElement("a");
13865 link.setAttribute("data-element-id", data.id);
13866 let isBound = false;
13867 if (data.url) {
13868 linkService.addLinkAttributes(link, data.url, data.newWindow);
13869 isBound = true;
13870 } else if (data.action) {
13871 this._bindNamedAction(link, data.action);
13872 isBound = true;
13873 } else if (data.attachment) {
13874 this.#bindAttachment(link, data.attachment, data.attachmentDest);
13875 isBound = true;
13876 } else if (data.setOCGState) {
13877 this.#bindSetOCGState(link, data.setOCGState);
13878 isBound = true;
13879 } else if (data.dest) {
13880 this._bindLink(link, data.dest);
13881 isBound = true;
13882 } else {
13883 if (data.actions && (data.actions.Action || data.actions["Mouse Up"] || data.actions["Mouse Down"]) && this.enableScripting && this.hasJSActions) {
13884 this._bindJSAction(link, data);
13885 isBound = true;
13886 }
13887 if (data.resetForm) {
13888 this._bindResetFormAction(link, data.resetForm);
13889 isBound = true;
13890 } else if (this.isTooltipOnly && !isBound) {
13891 this._bindLink(link, "");
13892 isBound = true;
13893 }
13894 }
13895 this.container.classList.add("linkAnnotation");
13896 if (isBound) {
13897 this.container.append(link);
13898 }
13899 return this.container;
13900 }
13901 #setInternalLink() {
13902 this.container.setAttribute("data-internal-link", "");
13903 }
13904 _bindLink(link, destination) {
13905 link.href = this.linkService.getDestinationHash(destination);
13906 link.onclick = () => {
13907 if (destination) {
13908 this.linkService.goToDestination(destination);
13909 }
13910 return false;
13911 };
13912 if (destination || destination === "") {
13913 this.#setInternalLink();
13914 }
13915 }
13916 _bindNamedAction(link, action) {
13917 link.href = this.linkService.getAnchorUrl("");
13918 link.onclick = () => {
13919 this.linkService.executeNamedAction(action);
13920 return false;
13921 };
13922 this.#setInternalLink();
13923 }
13924 #bindAttachment(link, attachment, dest = null) {
13925 link.href = this.linkService.getAnchorUrl("");
13926 if (attachment.description) {
13927 link.title = attachment.description;
13928 }
13929 link.onclick = () => {
13930 this.downloadManager?.openOrDownloadData(attachment.content, attachment.filename, dest);
13931 return false;
13932 };
13933 this.#setInternalLink();
13934 }
13935 #bindSetOCGState(link, action) {
13936 link.href = this.linkService.getAnchorUrl("");
13937 link.onclick = () => {
13938 this.linkService.executeSetOCGState(action);
13939 return false;
13940 };
13941 this.#setInternalLink();
13942 }
13943 _bindJSAction(link, data) {
13944 link.href = this.linkService.getAnchorUrl("");
13945 const map = new Map([["Action", "onclick"], ["Mouse Up", "onmouseup"], ["Mouse Down", "onmousedown"]]);
13946 for (const name of Object.keys(data.actions)) {
13947 const jsName = map.get(name);
13948 if (!jsName) {
13949 continue;
13950 }
13951 link[jsName] = () => {
13952 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
13953 source: this,
13954 detail: {
13955 id: data.id,
13956 name
13957 }
13958 });
13959 return false;
13960 };
13961 }
13962 if (!link.onclick) {
13963 link.onclick = () => false;
13964 }
13965 this.#setInternalLink();
13966 }
13967 _bindResetFormAction(link, resetForm) {
13968 const otherClickAction = link.onclick;
13969 if (!otherClickAction) {
13970 link.href = this.linkService.getAnchorUrl("");
13971 }
13972 this.#setInternalLink();
13973 if (!this._fieldObjects) {
13974 warn(`_bindResetFormAction - "resetForm" action not supported, ` + "ensure that the `fieldObjects` parameter is provided.");
13975 if (!otherClickAction) {
13976 link.onclick = () => false;
13977 }
13978 return;
13979 }
13980 link.onclick = () => {
13981 otherClickAction?.();
13982 const {
13983 fields: resetFormFields,
13984 refs: resetFormRefs,
13985 include
13986 } = resetForm;
13987 const allFields = [];
13988 if (resetFormFields.length !== 0 || resetFormRefs.length !== 0) {
13989 const fieldIds = new Set(resetFormRefs);
13990 for (const fieldName of resetFormFields) {
13991 const fields = this._fieldObjects[fieldName] || [];
13992 for (const {
13993 id
13994 } of fields) {
13995 fieldIds.add(id);
13996 }
13997 }
13998 for (const fields of Object.values(this._fieldObjects)) {
13999 for (const field of fields) {
14000 if (fieldIds.has(field.id) === include) {
14001 allFields.push(field);
14002 }
14003 }
14004 }
14005 } else {
14006 for (const fields of Object.values(this._fieldObjects)) {
14007 allFields.push(...fields);
14008 }
14009 }
14010 const storage = this.annotationStorage;
14011 const allIds = [];
14012 for (const field of allFields) {
14013 const {
14014 id
14015 } = field;
14016 allIds.push(id);
14017 switch (field.type) {
14018 case "text":
14019 {
14020 const value = field.defaultValue || "";
14021 storage.setValue(id, {
14022 value
14023 });
14024 break;
14025 }
14026 case "checkbox":
14027 case "radiobutton":
14028 {
14029 const value = field.defaultValue === field.exportValues;
14030 storage.setValue(id, {
14031 value
14032 });
14033 break;
14034 }
14035 case "combobox":
14036 case "listbox":
14037 {
14038 const value = field.defaultValue || "";
14039 storage.setValue(id, {
14040 value
14041 });
14042 break;
14043 }
14044 default:
14045 continue;
14046 }
14047 const domElement = document.querySelector(`[data-element-id="${id}"]`);
14048 if (!domElement) {
14049 continue;
14050 } else if (!GetElementsByNameSet.has(domElement)) {
14051 warn(`_bindResetFormAction - element not allowed: ${id}`);
14052 continue;
14053 }
14054 domElement.dispatchEvent(new Event("resetform"));
14055 }
14056 if (this.enableScripting) {
14057 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
14058 source: this,
14059 detail: {
14060 id: "app",
14061 ids: allIds,
14062 name: "ResetForm"
14063 }
14064 });
14065 }
14066 return false;
14067 };
14068 }
14069 }
14070 class TextAnnotationElement extends AnnotationElement {
14071 constructor(parameters) {
14072 super(parameters, {
14073 isRenderable: true
14074 });
14075 }
14076 render() {
14077 this.container.classList.add("textAnnotation");
14078 const image = document.createElement("img");
14079 image.src = this.imageResourcesPath + "annotation-" + this.data.name.toLowerCase() + ".svg";
14080 image.setAttribute("data-l10n-id", "pdfjs-text-annotation-type");
14081 image.setAttribute("data-l10n-args", JSON.stringify({
14082 type: this.data.name
14083 }));
14084 if (!this.data.popupRef && this.hasPopupData) {
14085 this._createPopup();
14086 }
14087 this.container.append(image);
14088 return this.container;
14089 }
14090 }
14091 class WidgetAnnotationElement extends AnnotationElement {
14092 render() {
14093 return this.container;
14094 }
14095 showElementAndHideCanvas(element) {
14096 if (this.data.hasOwnCanvas) {
14097 if (element.previousSibling?.nodeName === "CANVAS") {
14098 element.previousSibling.hidden = true;
14099 }
14100 element.hidden = false;
14101 }
14102 }
14103 _getKeyModifier(event) {
14104 return util_FeatureTest.platform.isMac ? event.metaKey : event.ctrlKey;
14105 }
14106 _setEventListener(element, elementData, baseName, eventName, valueGetter) {
14107 if (baseName.includes("mouse")) {
14108 element.addEventListener(baseName, event => {
14109 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
14110 source: this,
14111 detail: {
14112 id: this.data.id,
14113 name: eventName,
14114 value: valueGetter(event),
14115 shift: event.shiftKey,
14116 modifier: this._getKeyModifier(event)
14117 }
14118 });
14119 });
14120 } else {
14121 element.addEventListener(baseName, event => {
14122 if (baseName === "blur") {
14123 if (!elementData.focused || !event.relatedTarget) {
14124 return;
14125 }
14126 elementData.focused = false;
14127 } else if (baseName === "focus") {
14128 if (elementData.focused) {
14129 return;
14130 }
14131 elementData.focused = true;
14132 }
14133 if (!valueGetter) {
14134 return;
14135 }
14136 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
14137 source: this,
14138 detail: {
14139 id: this.data.id,
14140 name: eventName,
14141 value: valueGetter(event)
14142 }
14143 });
14144 });
14145 }
14146 }
14147 _setEventListeners(element, elementData, names, getter) {
14148 for (const [baseName, eventName] of names) {
14149 if (eventName === "Action" || this.data.actions?.[eventName]) {
14150 if (eventName === "Focus" || eventName === "Blur") {
14151 elementData ||= {
14152 focused: false
14153 };
14154 }
14155 this._setEventListener(element, elementData, baseName, eventName, getter);
14156 if (eventName === "Focus" && !this.data.actions?.Blur) {
14157 this._setEventListener(element, elementData, "blur", "Blur", null);
14158 } else if (eventName === "Blur" && !this.data.actions?.Focus) {
14159 this._setEventListener(element, elementData, "focus", "Focus", null);
14160 }
14161 }
14162 }
14163 }
14164 _setBackgroundColor(element) {
14165 const color = this.data.backgroundColor || null;
14166 element.style.backgroundColor = color === null ? "transparent" : Util.makeHexColor(color[0], color[1], color[2]);
14167 }
14168 _setTextStyle(element) {
14169 const TEXT_ALIGNMENT = ["left", "center", "right"];
14170 const {
14171 fontColor
14172 } = this.data.defaultAppearanceData;
14173 const fontSize = this.data.defaultAppearanceData.fontSize || annotation_layer_DEFAULT_FONT_SIZE;
14174 const style = element.style;
14175 let computedFontSize;
14176 const BORDER_SIZE = 2;
14177 const roundToOneDecimal = x => Math.round(10 * x) / 10;
14178 if (this.data.multiLine) {
14179 const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);
14180 const numberOfLines = Math.round(height / (LINE_FACTOR * fontSize)) || 1;
14181 const lineHeight = height / numberOfLines;
14182 computedFontSize = Math.min(fontSize, roundToOneDecimal(lineHeight / LINE_FACTOR));
14183 } else {
14184 const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);
14185 computedFontSize = Math.min(fontSize, roundToOneDecimal(height / LINE_FACTOR));
14186 }
14187 style.fontSize = `calc(${computedFontSize}px * var(--scale-factor))`;
14188 style.color = Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]);
14189 if (this.data.textAlignment !== null) {
14190 style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
14191 }
14192 }
14193 _setRequired(element, isRequired) {
14194 if (isRequired) {
14195 element.setAttribute("required", true);
14196 } else {
14197 element.removeAttribute("required");
14198 }
14199 element.setAttribute("aria-required", isRequired);
14200 }
14201 }
14202 class TextWidgetAnnotationElement extends WidgetAnnotationElement {
14203 constructor(parameters) {
14204 const isRenderable = parameters.renderForms || parameters.data.hasOwnCanvas || !parameters.data.hasAppearance && !!parameters.data.fieldValue;
14205 super(parameters, {
14206 isRenderable
14207 });
14208 }
14209 setPropertyOnSiblings(base, key, value, keyInStorage) {
14210 const storage = this.annotationStorage;
14211 for (const element of this._getElementsByName(base.name, base.id)) {
14212 if (element.domElement) {
14213 element.domElement[key] = value;
14214 }
14215 storage.setValue(element.id, {
14216 [keyInStorage]: value
14217 });
14218 }
14219 }
14220 render() {
14221 const storage = this.annotationStorage;
14222 const id = this.data.id;
14223 this.container.classList.add("textWidgetAnnotation");
14224 let element = null;
14225 if (this.renderForms) {
14226 const storedData = storage.getValue(id, {
14227 value: this.data.fieldValue
14228 });
14229 let textContent = storedData.value || "";
14230 const maxLen = storage.getValue(id, {
14231 charLimit: this.data.maxLen
14232 }).charLimit;
14233 if (maxLen && textContent.length > maxLen) {
14234 textContent = textContent.slice(0, maxLen);
14235 }
14236 let fieldFormattedValues = storedData.formattedValue || this.data.textContent?.join("\n") || null;
14237 if (fieldFormattedValues && this.data.comb) {
14238 fieldFormattedValues = fieldFormattedValues.replaceAll(/\s+/g, "");
14239 }
14240 const elementData = {
14241 userValue: textContent,
14242 formattedValue: fieldFormattedValues,
14243 lastCommittedValue: null,
14244 commitKey: 1,
14245 focused: false
14246 };
14247 if (this.data.multiLine) {
14248 element = document.createElement("textarea");
14249 element.textContent = fieldFormattedValues ?? textContent;
14250 if (this.data.doNotScroll) {
14251 element.style.overflowY = "hidden";
14252 }
14253 } else {
14254 element = document.createElement("input");
14255 element.type = "text";
14256 element.setAttribute("value", fieldFormattedValues ?? textContent);
14257 if (this.data.doNotScroll) {
14258 element.style.overflowX = "hidden";
14259 }
14260 }
14261 if (this.data.hasOwnCanvas) {
14262 element.hidden = true;
14263 }
14264 GetElementsByNameSet.add(element);
14265 element.setAttribute("data-element-id", id);
14266 element.disabled = this.data.readOnly;
14267 element.name = this.data.fieldName;
14268 element.tabIndex = DEFAULT_TAB_INDEX;
14269 this._setRequired(element, this.data.required);
14270 if (maxLen) {
14271 element.maxLength = maxLen;
14272 }
14273 element.addEventListener("input", event => {
14274 storage.setValue(id, {
14275 value: event.target.value
14276 });
14277 this.setPropertyOnSiblings(element, "value", event.target.value, "value");
14278 elementData.formattedValue = null;
14279 });
14280 element.addEventListener("resetform", event => {
14281 const defaultValue = this.data.defaultFieldValue ?? "";
14282 element.value = elementData.userValue = defaultValue;
14283 elementData.formattedValue = null;
14284 });
14285 let blurListener = event => {
14286 const {
14287 formattedValue
14288 } = elementData;
14289 if (formattedValue !== null && formattedValue !== undefined) {
14290 event.target.value = formattedValue;
14291 }
14292 event.target.scrollLeft = 0;
14293 };
14294 if (this.enableScripting && this.hasJSActions) {
14295 element.addEventListener("focus", event => {
14296 if (elementData.focused) {
14297 return;
14298 }
14299 const {
14300 target
14301 } = event;
14302 if (elementData.userValue) {
14303 target.value = elementData.userValue;
14304 }
14305 elementData.lastCommittedValue = target.value;
14306 elementData.commitKey = 1;
14307 if (!this.data.actions?.Focus) {
14308 elementData.focused = true;
14309 }
14310 });
14311 element.addEventListener("updatefromsandbox", jsEvent => {
14312 this.showElementAndHideCanvas(jsEvent.target);
14313 const actions = {
14314 value(event) {
14315 elementData.userValue = event.detail.value ?? "";
14316 storage.setValue(id, {
14317 value: elementData.userValue.toString()
14318 });
14319 event.target.value = elementData.userValue;
14320 },
14321 formattedValue(event) {
14322 const {
14323 formattedValue
14324 } = event.detail;
14325 elementData.formattedValue = formattedValue;
14326 if (formattedValue !== null && formattedValue !== undefined && event.target !== document.activeElement) {
14327 event.target.value = formattedValue;
14328 }
14329 storage.setValue(id, {
14330 formattedValue
14331 });
14332 },
14333 selRange(event) {
14334 event.target.setSelectionRange(...event.detail.selRange);
14335 },
14336 charLimit: event => {
14337 const {
14338 charLimit
14339 } = event.detail;
14340 const {
14341 target
14342 } = event;
14343 if (charLimit === 0) {
14344 target.removeAttribute("maxLength");
14345 return;
14346 }
14347 target.setAttribute("maxLength", charLimit);
14348 let value = elementData.userValue;
14349 if (!value || value.length <= charLimit) {
14350 return;
14351 }
14352 value = value.slice(0, charLimit);
14353 target.value = elementData.userValue = value;
14354 storage.setValue(id, {
14355 value
14356 });
14357 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
14358 source: this,
14359 detail: {
14360 id,
14361 name: "Keystroke",
14362 value,
14363 willCommit: true,
14364 commitKey: 1,
14365 selStart: target.selectionStart,
14366 selEnd: target.selectionEnd
14367 }
14368 });
14369 }
14370 };
14371 this._dispatchEventFromSandbox(actions, jsEvent);
14372 });
14373 element.addEventListener("keydown", event => {
14374 elementData.commitKey = 1;
14375 let commitKey = -1;
14376 if (event.key === "Escape") {
14377 commitKey = 0;
14378 } else if (event.key === "Enter" && !this.data.multiLine) {
14379 commitKey = 2;
14380 } else if (event.key === "Tab") {
14381 elementData.commitKey = 3;
14382 }
14383 if (commitKey === -1) {
14384 return;
14385 }
14386 const {
14387 value
14388 } = event.target;
14389 if (elementData.lastCommittedValue === value) {
14390 return;
14391 }
14392 elementData.lastCommittedValue = value;
14393 elementData.userValue = value;
14394 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
14395 source: this,
14396 detail: {
14397 id,
14398 name: "Keystroke",
14399 value,
14400 willCommit: true,
14401 commitKey,
14402 selStart: event.target.selectionStart,
14403 selEnd: event.target.selectionEnd
14404 }
14405 });
14406 });
14407 const _blurListener = blurListener;
14408 blurListener = null;
14409 element.addEventListener("blur", event => {
14410 if (!elementData.focused || !event.relatedTarget) {
14411 return;
14412 }
14413 if (!this.data.actions?.Blur) {
14414 elementData.focused = false;
14415 }
14416 const {
14417 value
14418 } = event.target;
14419 elementData.userValue = value;
14420 if (elementData.lastCommittedValue !== value) {
14421 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
14422 source: this,
14423 detail: {
14424 id,
14425 name: "Keystroke",
14426 value,
14427 willCommit: true,
14428 commitKey: elementData.commitKey,
14429 selStart: event.target.selectionStart,
14430 selEnd: event.target.selectionEnd
14431 }
14432 });
14433 }
14434 _blurListener(event);
14435 });
14436 if (this.data.actions?.Keystroke) {
14437 element.addEventListener("beforeinput", event => {
14438 elementData.lastCommittedValue = null;
14439 const {
14440 data,
14441 target
14442 } = event;
14443 const {
14444 value,
14445 selectionStart,
14446 selectionEnd
14447 } = target;
14448 let selStart = selectionStart,
14449 selEnd = selectionEnd;
14450 switch (event.inputType) {
14451 case "deleteWordBackward":
14452 {
14453 const match = value.substring(0, selectionStart).match(/\w*[^\w]*$/);
14454 if (match) {
14455 selStart -= match[0].length;
14456 }
14457 break;
14458 }
14459 case "deleteWordForward":
14460 {
14461 const match = value.substring(selectionStart).match(/^[^\w]*\w*/);
14462 if (match) {
14463 selEnd += match[0].length;
14464 }
14465 break;
14466 }
14467 case "deleteContentBackward":
14468 if (selectionStart === selectionEnd) {
14469 selStart -= 1;
14470 }
14471 break;
14472 case "deleteContentForward":
14473 if (selectionStart === selectionEnd) {
14474 selEnd += 1;
14475 }
14476 break;
14477 }
14478 event.preventDefault();
14479 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
14480 source: this,
14481 detail: {
14482 id,
14483 name: "Keystroke",
14484 value,
14485 change: data || "",
14486 willCommit: false,
14487 selStart,
14488 selEnd
14489 }
14490 });
14491 });
14492 }
14493 this._setEventListeners(element, elementData, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.value);
14494 }
14495 if (blurListener) {
14496 element.addEventListener("blur", blurListener);
14497 }
14498 if (this.data.comb) {
14499 const fieldWidth = this.data.rect[2] - this.data.rect[0];
14500 const combWidth = fieldWidth / maxLen;
14501 element.classList.add("comb");
14502 element.style.letterSpacing = `calc(${combWidth}px * var(--scale-factor) - 1ch)`;
14503 }
14504 } else {
14505 element = document.createElement("div");
14506 element.textContent = this.data.fieldValue;
14507 element.style.verticalAlign = "middle";
14508 element.style.display = "table-cell";
14509 if (this.data.hasOwnCanvas) {
14510 element.hidden = true;
14511 }
14512 }
14513 this._setTextStyle(element);
14514 this._setBackgroundColor(element);
14515 this._setDefaultPropertiesFromJS(element);
14516 this.container.append(element);
14517 return this.container;
14518 }
14519 }
14520 class SignatureWidgetAnnotationElement extends WidgetAnnotationElement {
14521 constructor(parameters) {
14522 super(parameters, {
14523 isRenderable: !!parameters.data.hasOwnCanvas
14524 });
14525 }
14526 }
14527 class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement {
14528 constructor(parameters) {
14529 super(parameters, {
14530 isRenderable: parameters.renderForms
14531 });
14532 }
14533 render() {
14534 const storage = this.annotationStorage;
14535 const data = this.data;
14536 const id = data.id;
14537 let value = storage.getValue(id, {
14538 value: data.exportValue === data.fieldValue
14539 }).value;
14540 if (typeof value === "string") {
14541 value = value !== "Off";
14542 storage.setValue(id, {
14543 value
14544 });
14545 }
14546 this.container.classList.add("buttonWidgetAnnotation", "checkBox");
14547 const element = document.createElement("input");
14548 GetElementsByNameSet.add(element);
14549 element.setAttribute("data-element-id", id);
14550 element.disabled = data.readOnly;
14551 this._setRequired(element, this.data.required);
14552 element.type = "checkbox";
14553 element.name = data.fieldName;
14554 if (value) {
14555 element.setAttribute("checked", true);
14556 }
14557 element.setAttribute("exportValue", data.exportValue);
14558 element.tabIndex = DEFAULT_TAB_INDEX;
14559 element.addEventListener("change", event => {
14560 const {
14561 name,
14562 checked
14563 } = event.target;
14564 for (const checkbox of this._getElementsByName(name, id)) {
14565 const curChecked = checked && checkbox.exportValue === data.exportValue;
14566 if (checkbox.domElement) {
14567 checkbox.domElement.checked = curChecked;
14568 }
14569 storage.setValue(checkbox.id, {
14570 value: curChecked
14571 });
14572 }
14573 storage.setValue(id, {
14574 value: checked
14575 });
14576 });
14577 element.addEventListener("resetform", event => {
14578 const defaultValue = data.defaultFieldValue || "Off";
14579 event.target.checked = defaultValue === data.exportValue;
14580 });
14581 if (this.enableScripting && this.hasJSActions) {
14582 element.addEventListener("updatefromsandbox", jsEvent => {
14583 const actions = {
14584 value(event) {
14585 event.target.checked = event.detail.value !== "Off";
14586 storage.setValue(id, {
14587 value: event.target.checked
14588 });
14589 }
14590 };
14591 this._dispatchEventFromSandbox(actions, jsEvent);
14592 });
14593 this._setEventListeners(element, null, [["change", "Validate"], ["change", "Action"], ["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.checked);
14594 }
14595 this._setBackgroundColor(element);
14596 this._setDefaultPropertiesFromJS(element);
14597 this.container.append(element);
14598 return this.container;
14599 }
14600 }
14601 class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement {
14602 constructor(parameters) {
14603 super(parameters, {
14604 isRenderable: parameters.renderForms
14605 });
14606 }
14607 render() {
14608 this.container.classList.add("buttonWidgetAnnotation", "radioButton");
14609 const storage = this.annotationStorage;
14610 const data = this.data;
14611 const id = data.id;
14612 let value = storage.getValue(id, {
14613 value: data.fieldValue === data.buttonValue
14614 }).value;
14615 if (typeof value === "string") {
14616 value = value !== data.buttonValue;
14617 storage.setValue(id, {
14618 value
14619 });
14620 }
14621 if (value) {
14622 for (const radio of this._getElementsByName(data.fieldName, id)) {
14623 storage.setValue(radio.id, {
14624 value: false
14625 });
14626 }
14627 }
14628 const element = document.createElement("input");
14629 GetElementsByNameSet.add(element);
14630 element.setAttribute("data-element-id", id);
14631 element.disabled = data.readOnly;
14632 this._setRequired(element, this.data.required);
14633 element.type = "radio";
14634 element.name = data.fieldName;
14635 if (value) {
14636 element.setAttribute("checked", true);
14637 }
14638 element.tabIndex = DEFAULT_TAB_INDEX;
14639 element.addEventListener("change", event => {
14640 const {
14641 name,
14642 checked
14643 } = event.target;
14644 for (const radio of this._getElementsByName(name, id)) {
14645 storage.setValue(radio.id, {
14646 value: false
14647 });
14648 }
14649 storage.setValue(id, {
14650 value: checked
14651 });
14652 });
14653 element.addEventListener("resetform", event => {
14654 const defaultValue = data.defaultFieldValue;
14655 event.target.checked = defaultValue !== null && defaultValue !== undefined && defaultValue === data.buttonValue;
14656 });
14657 if (this.enableScripting && this.hasJSActions) {
14658 const pdfButtonValue = data.buttonValue;
14659 element.addEventListener("updatefromsandbox", jsEvent => {
14660 const actions = {
14661 value: event => {
14662 const checked = pdfButtonValue === event.detail.value;
14663 for (const radio of this._getElementsByName(event.target.name)) {
14664 const curChecked = checked && radio.id === id;
14665 if (radio.domElement) {
14666 radio.domElement.checked = curChecked;
14667 }
14668 storage.setValue(radio.id, {
14669 value: curChecked
14670 });
14671 }
14672 }
14673 };
14674 this._dispatchEventFromSandbox(actions, jsEvent);
14675 });
14676 this._setEventListeners(element, null, [["change", "Validate"], ["change", "Action"], ["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.checked);
14677 }
14678 this._setBackgroundColor(element);
14679 this._setDefaultPropertiesFromJS(element);
14680 this.container.append(element);
14681 return this.container;
14682 }
14683 }
14684 class PushButtonWidgetAnnotationElement extends LinkAnnotationElement {
14685 constructor(parameters) {
14686 super(parameters, {
14687 ignoreBorder: parameters.data.hasAppearance
14688 });
14689 }
14690 render() {
14691 const container = super.render();
14692 container.classList.add("buttonWidgetAnnotation", "pushButton");
14693 const linkElement = container.lastChild;
14694 if (this.enableScripting && this.hasJSActions && linkElement) {
14695 this._setDefaultPropertiesFromJS(linkElement);
14696 linkElement.addEventListener("updatefromsandbox", jsEvent => {
14697 this._dispatchEventFromSandbox({}, jsEvent);
14698 });
14699 }
14700 return container;
14701 }
14702 }
14703 class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement {
14704 constructor(parameters) {
14705 super(parameters, {
14706 isRenderable: parameters.renderForms
14707 });
14708 }
14709 render() {
14710 this.container.classList.add("choiceWidgetAnnotation");
14711 const storage = this.annotationStorage;
14712 const id = this.data.id;
14713 const storedData = storage.getValue(id, {
14714 value: this.data.fieldValue
14715 });
14716 const selectElement = document.createElement("select");
14717 GetElementsByNameSet.add(selectElement);
14718 selectElement.setAttribute("data-element-id", id);
14719 selectElement.disabled = this.data.readOnly;
14720 this._setRequired(selectElement, this.data.required);
14721 selectElement.name = this.data.fieldName;
14722 selectElement.tabIndex = DEFAULT_TAB_INDEX;
14723 let addAnEmptyEntry = this.data.combo && this.data.options.length > 0;
14724 if (!this.data.combo) {
14725 selectElement.size = this.data.options.length;
14726 if (this.data.multiSelect) {
14727 selectElement.multiple = true;
14728 }
14729 }
14730 selectElement.addEventListener("resetform", event => {
14731 const defaultValue = this.data.defaultFieldValue;
14732 for (const option of selectElement.options) {
14733 option.selected = option.value === defaultValue;
14734 }
14735 });
14736 for (const option of this.data.options) {
14737 const optionElement = document.createElement("option");
14738 optionElement.textContent = option.displayValue;
14739 optionElement.value = option.exportValue;
14740 if (storedData.value.includes(option.exportValue)) {
14741 optionElement.setAttribute("selected", true);
14742 addAnEmptyEntry = false;
14743 }
14744 selectElement.append(optionElement);
14745 }
14746 let removeEmptyEntry = null;
14747 if (addAnEmptyEntry) {
14748 const noneOptionElement = document.createElement("option");
14749 noneOptionElement.value = " ";
14750 noneOptionElement.setAttribute("hidden", true);
14751 noneOptionElement.setAttribute("selected", true);
14752 selectElement.prepend(noneOptionElement);
14753 removeEmptyEntry = () => {
14754 noneOptionElement.remove();
14755 selectElement.removeEventListener("input", removeEmptyEntry);
14756 removeEmptyEntry = null;
14757 };
14758 selectElement.addEventListener("input", removeEmptyEntry);
14759 }
14760 const getValue = isExport => {
14761 const name = isExport ? "value" : "textContent";
14762 const {
14763 options,
14764 multiple
14765 } = selectElement;
14766 if (!multiple) {
14767 return options.selectedIndex === -1 ? null : options[options.selectedIndex][name];
14768 }
14769 return Array.prototype.filter.call(options, option => option.selected).map(option => option[name]);
14770 };
14771 let selectedValues = getValue(false);
14772 const getItems = event => {
14773 const options = event.target.options;
14774 return Array.prototype.map.call(options, option => ({
14775 displayValue: option.textContent,
14776 exportValue: option.value
14777 }));
14778 };
14779 if (this.enableScripting && this.hasJSActions) {
14780 selectElement.addEventListener("updatefromsandbox", jsEvent => {
14781 const actions = {
14782 value(event) {
14783 removeEmptyEntry?.();
14784 const value = event.detail.value;
14785 const values = new Set(Array.isArray(value) ? value : [value]);
14786 for (const option of selectElement.options) {
14787 option.selected = values.has(option.value);
14788 }
14789 storage.setValue(id, {
14790 value: getValue(true)
14791 });
14792 selectedValues = getValue(false);
14793 },
14794 multipleSelection(event) {
14795 selectElement.multiple = true;
14796 },
14797 remove(event) {
14798 const options = selectElement.options;
14799 const index = event.detail.remove;
14800 options[index].selected = false;
14801 selectElement.remove(index);
14802 if (options.length > 0) {
14803 const i = Array.prototype.findIndex.call(options, option => option.selected);
14804 if (i === -1) {
14805 options[0].selected = true;
14806 }
14807 }
14808 storage.setValue(id, {
14809 value: getValue(true),
14810 items: getItems(event)
14811 });
14812 selectedValues = getValue(false);
14813 },
14814 clear(event) {
14815 while (selectElement.length !== 0) {
14816 selectElement.remove(0);
14817 }
14818 storage.setValue(id, {
14819 value: null,
14820 items: []
14821 });
14822 selectedValues = getValue(false);
14823 },
14824 insert(event) {
14825 const {
14826 index,
14827 displayValue,
14828 exportValue
14829 } = event.detail.insert;
14830 const selectChild = selectElement.children[index];
14831 const optionElement = document.createElement("option");
14832 optionElement.textContent = displayValue;
14833 optionElement.value = exportValue;
14834 if (selectChild) {
14835 selectChild.before(optionElement);
14836 } else {
14837 selectElement.append(optionElement);
14838 }
14839 storage.setValue(id, {
14840 value: getValue(true),
14841 items: getItems(event)
14842 });
14843 selectedValues = getValue(false);
14844 },
14845 items(event) {
14846 const {
14847 items
14848 } = event.detail;
14849 while (selectElement.length !== 0) {
14850 selectElement.remove(0);
14851 }
14852 for (const item of items) {
14853 const {
14854 displayValue,
14855 exportValue
14856 } = item;
14857 const optionElement = document.createElement("option");
14858 optionElement.textContent = displayValue;
14859 optionElement.value = exportValue;
14860 selectElement.append(optionElement);
14861 }
14862 if (selectElement.options.length > 0) {
14863 selectElement.options[0].selected = true;
14864 }
14865 storage.setValue(id, {
14866 value: getValue(true),
14867 items: getItems(event)
14868 });
14869 selectedValues = getValue(false);
14870 },
14871 indices(event) {
14872 const indices = new Set(event.detail.indices);
14873 for (const option of event.target.options) {
14874 option.selected = indices.has(option.index);
14875 }
14876 storage.setValue(id, {
14877 value: getValue(true)
14878 });
14879 selectedValues = getValue(false);
14880 },
14881 editable(event) {
14882 event.target.disabled = !event.detail.editable;
14883 }
14884 };
14885 this._dispatchEventFromSandbox(actions, jsEvent);
14886 });
14887 selectElement.addEventListener("input", event => {
14888 const exportValue = getValue(true);
14889 const change = getValue(false);
14890 storage.setValue(id, {
14891 value: exportValue
14892 });
14893 event.preventDefault();
14894 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
14895 source: this,
14896 detail: {
14897 id,
14898 name: "Keystroke",
14899 value: selectedValues,
14900 change,
14901 changeEx: exportValue,
14902 willCommit: false,
14903 commitKey: 1,
14904 keyDown: false
14905 }
14906 });
14907 });
14908 this._setEventListeners(selectElement, null, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"], ["input", "Action"], ["input", "Validate"]], event => event.target.value);
14909 } else {
14910 selectElement.addEventListener("input", function (event) {
14911 storage.setValue(id, {
14912 value: getValue(true)
14913 });
14914 });
14915 }
14916 if (this.data.combo) {
14917 this._setTextStyle(selectElement);
14918 } else {}
14919 this._setBackgroundColor(selectElement);
14920 this._setDefaultPropertiesFromJS(selectElement);
14921 this.container.append(selectElement);
14922 return this.container;
14923 }
14924 }
14925 class PopupAnnotationElement extends AnnotationElement {
14926 constructor(parameters) {
14927 const {
14928 data,
14929 elements
14930 } = parameters;
14931 super(parameters, {
14932 isRenderable: AnnotationElement._hasPopupData(data)
14933 });
14934 this.elements = elements;
14935 this.popup = null;
14936 }
14937 render() {
14938 this.container.classList.add("popupAnnotation");
14939 const popup = this.popup = new PopupElement({
14940 container: this.container,
14941 color: this.data.color,
14942 titleObj: this.data.titleObj,
14943 modificationDate: this.data.modificationDate,
14944 contentsObj: this.data.contentsObj,
14945 richText: this.data.richText,
14946 rect: this.data.rect,
14947 parentRect: this.data.parentRect || null,
14948 parent: this.parent,
14949 elements: this.elements,
14950 open: this.data.open
14951 });
14952 const elementIds = [];
14953 for (const element of this.elements) {
14954 element.popup = popup;
14955 elementIds.push(element.data.id);
14956 element.addHighlightArea();
14957 }
14958 this.container.setAttribute("aria-controls", elementIds.map(id => `${AnnotationPrefix}${id}`).join(","));
14959 return this.container;
14960 }
14961 }
14962 class PopupElement {
14963 #boundKeyDown = this.#keyDown.bind(this);
14964 #boundHide = this.#hide.bind(this);
14965 #boundShow = this.#show.bind(this);
14966 #boundToggle = this.#toggle.bind(this);
14967 #color = null;
14968 #container = null;
14969 #contentsObj = null;
14970 #dateObj = null;
14971 #elements = null;
14972 #parent = null;
14973 #parentRect = null;
14974 #pinned = false;
14975 #popup = null;
14976 #position = null;
14977 #rect = null;
14978 #richText = null;
14979 #titleObj = null;
14980 #updates = null;
14981 #wasVisible = false;
14982 constructor({
14983 container,
14984 color,
14985 elements,
14986 titleObj,
14987 modificationDate,
14988 contentsObj,
14989 richText,
14990 parent,
14991 rect,
14992 parentRect,
14993 open
14994 }) {
14995 this.#container = container;
14996 this.#titleObj = titleObj;
14997 this.#contentsObj = contentsObj;
14998 this.#richText = richText;
14999 this.#parent = parent;
15000 this.#color = color;
15001 this.#rect = rect;
15002 this.#parentRect = parentRect;
15003 this.#elements = elements;
15004 this.#dateObj = PDFDateString.toDateObject(modificationDate);
15005 this.trigger = elements.flatMap(e => e.getElementsToTriggerPopup());
15006 for (const element of this.trigger) {
15007 element.addEventListener("click", this.#boundToggle);
15008 element.addEventListener("mouseenter", this.#boundShow);
15009 element.addEventListener("mouseleave", this.#boundHide);
15010 element.classList.add("popupTriggerArea");
15011 }
15012 for (const element of elements) {
15013 element.container?.addEventListener("keydown", this.#boundKeyDown);
15014 }
15015 this.#container.hidden = true;
15016 if (open) {
15017 this.#toggle();
15018 }
15019 }
15020 render() {
15021 if (this.#popup) {
15022 return;
15023 }
15024 const popup = this.#popup = document.createElement("div");
15025 popup.className = "popup";
15026 if (this.#color) {
15027 const baseColor = popup.style.outlineColor = Util.makeHexColor(...this.#color);
15028 if (CSS.supports("background-color", "color-mix(in srgb, red 30%, white)")) {
15029 popup.style.backgroundColor = `color-mix(in srgb, ${baseColor} 30%, white)`;
15030 } else {
15031 const BACKGROUND_ENLIGHT = 0.7;
15032 popup.style.backgroundColor = Util.makeHexColor(...this.#color.map(c => Math.floor(BACKGROUND_ENLIGHT * (255 - c) + c)));
15033 }
15034 }
15035 const header = document.createElement("span");
15036 header.className = "header";
15037 const title = document.createElement("h1");
15038 header.append(title);
15039 ({
15040 dir: title.dir,
15041 str: title.textContent
15042 } = this.#titleObj);
15043 popup.append(header);
15044 if (this.#dateObj) {
15045 const modificationDate = document.createElement("span");
15046 modificationDate.classList.add("popupDate");
15047 modificationDate.setAttribute("data-l10n-id", "pdfjs-annotation-date-time-string");
15048 modificationDate.setAttribute("data-l10n-args", JSON.stringify({
15049 dateObj: this.#dateObj.valueOf()
15050 }));
15051 header.append(modificationDate);
15052 }
15053 const html = this.#html;
15054 if (html) {
15055 XfaLayer.render({
15056 xfaHtml: html,
15057 intent: "richText",
15058 div: popup
15059 });
15060 popup.lastChild.classList.add("richText", "popupContent");
15061 } else {
15062 const contents = this._formatContents(this.#contentsObj);
15063 popup.append(contents);
15064 }
15065 this.#container.append(popup);
15066 }
15067 get #html() {
15068 const richText = this.#richText;
15069 const contentsObj = this.#contentsObj;
15070 if (richText?.str && (!contentsObj?.str || contentsObj.str === richText.str)) {
15071 return this.#richText.html || null;
15072 }
15073 return null;
15074 }
15075 get #fontSize() {
15076 return this.#html?.attributes?.style?.fontSize || 0;
15077 }
15078 get #fontColor() {
15079 return this.#html?.attributes?.style?.color || null;
15080 }
15081 #makePopupContent(text) {
15082 const popupLines = [];
15083 const popupContent = {
15084 str: text,
15085 html: {
15086 name: "div",
15087 attributes: {
15088 dir: "auto"
15089 },
15090 children: [{
15091 name: "p",
15092 children: popupLines
15093 }]
15094 }
15095 };
15096 const lineAttributes = {
15097 style: {
15098 color: this.#fontColor,
15099 fontSize: this.#fontSize ? `calc(${this.#fontSize}px * var(--scale-factor))` : ""
15100 }
15101 };
15102 for (const line of text.split("\n")) {
15103 popupLines.push({
15104 name: "span",
15105 value: line,
15106 attributes: lineAttributes
15107 });
15108 }
15109 return popupContent;
15110 }
15111 _formatContents({
15112 str,
15113 dir
15114 }) {
15115 const p = document.createElement("p");
15116 p.classList.add("popupContent");
15117 p.dir = dir;
15118 const lines = str.split(/(?:\r\n?|\n)/);
15119 for (let i = 0, ii = lines.length; i < ii; ++i) {
15120 const line = lines[i];
15121 p.append(document.createTextNode(line));
15122 if (i < ii - 1) {
15123 p.append(document.createElement("br"));
15124 }
15125 }
15126 return p;
15127 }
15128 #keyDown(event) {
15129 if (event.altKey || event.shiftKey || event.ctrlKey || event.metaKey) {
15130 return;
15131 }
15132 if (event.key === "Enter" || event.key === "Escape" && this.#pinned) {
15133 this.#toggle();
15134 }
15135 }
15136 updateEdited({
15137 rect,
15138 popupContent
15139 }) {
15140 this.#updates ||= {
15141 contentsObj: this.#contentsObj,
15142 richText: this.#richText
15143 };
15144 if (rect) {
15145 this.#position = null;
15146 }
15147 if (popupContent) {
15148 this.#richText = this.#makePopupContent(popupContent);
15149 this.#contentsObj = null;
15150 }
15151 this.#popup?.remove();
15152 this.#popup = null;
15153 }
15154 resetEdited() {
15155 if (!this.#updates) {
15156 return;
15157 }
15158 ({
15159 contentsObj: this.#contentsObj,
15160 richText: this.#richText
15161 } = this.#updates);
15162 this.#updates = null;
15163 this.#popup?.remove();
15164 this.#popup = null;
15165 this.#position = null;
15166 }
15167 #setPosition() {
15168 if (this.#position !== null) {
15169 return;
15170 }
15171 const {
15172 page: {
15173 view
15174 },
15175 viewport: {
15176 rawDims: {
15177 pageWidth,
15178 pageHeight,
15179 pageX,
15180 pageY
15181 }
15182 }
15183 } = this.#parent;
15184 let useParentRect = !!this.#parentRect;
15185 let rect = useParentRect ? this.#parentRect : this.#rect;
15186 for (const element of this.#elements) {
15187 if (!rect || Util.intersect(element.data.rect, rect) !== null) {
15188 rect = element.data.rect;
15189 useParentRect = true;
15190 break;
15191 }
15192 }
15193 const normalizedRect = Util.normalizeRect([rect[0], view[3] - rect[1] + view[1], rect[2], view[3] - rect[3] + view[1]]);
15194 const HORIZONTAL_SPACE_AFTER_ANNOTATION = 5;
15195 const parentWidth = useParentRect ? rect[2] - rect[0] + HORIZONTAL_SPACE_AFTER_ANNOTATION : 0;
15196 const popupLeft = normalizedRect[0] + parentWidth;
15197 const popupTop = normalizedRect[1];
15198 this.#position = [100 * (popupLeft - pageX) / pageWidth, 100 * (popupTop - pageY) / pageHeight];
15199 const {
15200 style
15201 } = this.#container;
15202 style.left = `${this.#position[0]}%`;
15203 style.top = `${this.#position[1]}%`;
15204 }
15205 #toggle() {
15206 this.#pinned = !this.#pinned;
15207 if (this.#pinned) {
15208 this.#show();
15209 this.#container.addEventListener("click", this.#boundToggle);
15210 this.#container.addEventListener("keydown", this.#boundKeyDown);
15211 } else {
15212 this.#hide();
15213 this.#container.removeEventListener("click", this.#boundToggle);
15214 this.#container.removeEventListener("keydown", this.#boundKeyDown);
15215 }
15216 }
15217 #show() {
15218 if (!this.#popup) {
15219 this.render();
15220 }
15221 if (!this.isVisible) {
15222 this.#setPosition();
15223 this.#container.hidden = false;
15224 this.#container.style.zIndex = parseInt(this.#container.style.zIndex) + 1000;
15225 } else if (this.#pinned) {
15226 this.#container.classList.add("focused");
15227 }
15228 }
15229 #hide() {
15230 this.#container.classList.remove("focused");
15231 if (this.#pinned || !this.isVisible) {
15232 return;
15233 }
15234 this.#container.hidden = true;
15235 this.#container.style.zIndex = parseInt(this.#container.style.zIndex) - 1000;
15236 }
15237 forceHide() {
15238 this.#wasVisible = this.isVisible;
15239 if (!this.#wasVisible) {
15240 return;
15241 }
15242 this.#container.hidden = true;
15243 }
15244 maybeShow() {
15245 if (!this.#wasVisible) {
15246 return;
15247 }
15248 if (!this.#popup) {
15249 this.#show();
15250 }
15251 this.#wasVisible = false;
15252 this.#container.hidden = false;
15253 }
15254 get isVisible() {
15255 return this.#container.hidden === false;
15256 }
15257 }
15258 class FreeTextAnnotationElement extends AnnotationElement {
15259 constructor(parameters) {
15260 super(parameters, {
15261 isRenderable: true,
15262 ignoreBorder: true
15263 });
15264 this.textContent = parameters.data.textContent;
15265 this.textPosition = parameters.data.textPosition;
15266 this.annotationEditorType = AnnotationEditorType.FREETEXT;
15267 }
15268 render() {
15269 this.container.classList.add("freeTextAnnotation");
15270 if (this.textContent) {
15271 const content = document.createElement("div");
15272 content.classList.add("annotationTextContent");
15273 content.setAttribute("role", "comment");
15274 for (const line of this.textContent) {
15275 const lineSpan = document.createElement("span");
15276 lineSpan.textContent = line;
15277 content.append(lineSpan);
15278 }
15279 this.container.append(content);
15280 }
15281 if (!this.data.popupRef && this.hasPopupData) {
15282 this._createPopup();
15283 }
15284 this._editOnDoubleClick();
15285 return this.container;
15286 }
15287 }
15288 class LineAnnotationElement extends AnnotationElement {
15289 #line = null;
15290 constructor(parameters) {
15291 super(parameters, {
15292 isRenderable: true,
15293 ignoreBorder: true
15294 });
15295 }
15296 render() {
15297 this.container.classList.add("lineAnnotation");
15298 const data = this.data;
15299 const {
15300 width,
15301 height
15302 } = getRectDims(data.rect);
15303 const svg = this.svgFactory.create(width, height, true);
15304 const line = this.#line = this.svgFactory.createElement("svg:line");
15305 line.setAttribute("x1", data.rect[2] - data.lineCoordinates[0]);
15306 line.setAttribute("y1", data.rect[3] - data.lineCoordinates[1]);
15307 line.setAttribute("x2", data.rect[2] - data.lineCoordinates[2]);
15308 line.setAttribute("y2", data.rect[3] - data.lineCoordinates[3]);
15309 line.setAttribute("stroke-width", data.borderStyle.width || 1);
15310 line.setAttribute("stroke", "transparent");
15311 line.setAttribute("fill", "transparent");
15312 svg.append(line);
15313 this.container.append(svg);
15314 if (!data.popupRef && this.hasPopupData) {
15315 this._createPopup();
15316 }
15317 return this.container;
15318 }
15319 getElementsToTriggerPopup() {
15320 return this.#line;
15321 }
15322 addHighlightArea() {
15323 this.container.classList.add("highlightArea");
15324 }
15325 }
15326 class SquareAnnotationElement extends AnnotationElement {
15327 #square = null;
15328 constructor(parameters) {
15329 super(parameters, {
15330 isRenderable: true,
15331 ignoreBorder: true
15332 });
15333 }
15334 render() {
15335 this.container.classList.add("squareAnnotation");
15336 const data = this.data;
15337 const {
15338 width,
15339 height
15340 } = getRectDims(data.rect);
15341 const svg = this.svgFactory.create(width, height, true);
15342 const borderWidth = data.borderStyle.width;
15343 const square = this.#square = this.svgFactory.createElement("svg:rect");
15344 square.setAttribute("x", borderWidth / 2);
15345 square.setAttribute("y", borderWidth / 2);
15346 square.setAttribute("width", width - borderWidth);
15347 square.setAttribute("height", height - borderWidth);
15348 square.setAttribute("stroke-width", borderWidth || 1);
15349 square.setAttribute("stroke", "transparent");
15350 square.setAttribute("fill", "transparent");
15351 svg.append(square);
15352 this.container.append(svg);
15353 if (!data.popupRef && this.hasPopupData) {
15354 this._createPopup();
15355 }
15356 return this.container;
15357 }
15358 getElementsToTriggerPopup() {
15359 return this.#square;
15360 }
15361 addHighlightArea() {
15362 this.container.classList.add("highlightArea");
15363 }
15364 }
15365 class CircleAnnotationElement extends AnnotationElement {
15366 #circle = null;
15367 constructor(parameters) {
15368 super(parameters, {
15369 isRenderable: true,
15370 ignoreBorder: true
15371 });
15372 }
15373 render() {
15374 this.container.classList.add("circleAnnotation");
15375 const data = this.data;
15376 const {
15377 width,
15378 height
15379 } = getRectDims(data.rect);
15380 const svg = this.svgFactory.create(width, height, true);
15381 const borderWidth = data.borderStyle.width;
15382 const circle = this.#circle = this.svgFactory.createElement("svg:ellipse");
15383 circle.setAttribute("cx", width / 2);
15384 circle.setAttribute("cy", height / 2);
15385 circle.setAttribute("rx", width / 2 - borderWidth / 2);
15386 circle.setAttribute("ry", height / 2 - borderWidth / 2);
15387 circle.setAttribute("stroke-width", borderWidth || 1);
15388 circle.setAttribute("stroke", "transparent");
15389 circle.setAttribute("fill", "transparent");
15390 svg.append(circle);
15391 this.container.append(svg);
15392 if (!data.popupRef && this.hasPopupData) {
15393 this._createPopup();
15394 }
15395 return this.container;
15396 }
15397 getElementsToTriggerPopup() {
15398 return this.#circle;
15399 }
15400 addHighlightArea() {
15401 this.container.classList.add("highlightArea");
15402 }
15403 }
15404 class PolylineAnnotationElement extends AnnotationElement {
15405 #polyline = null;
15406 constructor(parameters) {
15407 super(parameters, {
15408 isRenderable: true,
15409 ignoreBorder: true
15410 });
15411 this.containerClassName = "polylineAnnotation";
15412 this.svgElementName = "svg:polyline";
15413 }
15414 render() {
15415 this.container.classList.add(this.containerClassName);
15416 const {
15417 data: {
15418 rect,
15419 vertices,
15420 borderStyle,
15421 popupRef
15422 }
15423 } = this;
15424 if (!vertices) {
15425 return this.container;
15426 }
15427 const {
15428 width,
15429 height
15430 } = getRectDims(rect);
15431 const svg = this.svgFactory.create(width, height, true);
15432 let points = [];
15433 for (let i = 0, ii = vertices.length; i < ii; i += 2) {
15434 const x = vertices[i] - rect[0];
15435 const y = rect[3] - vertices[i + 1];
15436 points.push(`${x},${y}`);
15437 }
15438 points = points.join(" ");
15439 const polyline = this.#polyline = this.svgFactory.createElement(this.svgElementName);
15440 polyline.setAttribute("points", points);
15441 polyline.setAttribute("stroke-width", borderStyle.width || 1);
15442 polyline.setAttribute("stroke", "transparent");
15443 polyline.setAttribute("fill", "transparent");
15444 svg.append(polyline);
15445 this.container.append(svg);
15446 if (!popupRef && this.hasPopupData) {
15447 this._createPopup();
15448 }
15449 return this.container;
15450 }
15451 getElementsToTriggerPopup() {
15452 return this.#polyline;
15453 }
15454 addHighlightArea() {
15455 this.container.classList.add("highlightArea");
15456 }
15457 }
15458 class PolygonAnnotationElement extends PolylineAnnotationElement {
15459 constructor(parameters) {
15460 super(parameters);
15461 this.containerClassName = "polygonAnnotation";
15462 this.svgElementName = "svg:polygon";
15463 }
15464 }
15465 class CaretAnnotationElement extends AnnotationElement {
15466 constructor(parameters) {
15467 super(parameters, {
15468 isRenderable: true,
15469 ignoreBorder: true
15470 });
15471 }
15472 render() {
15473 this.container.classList.add("caretAnnotation");
15474 if (!this.data.popupRef && this.hasPopupData) {
15475 this._createPopup();
15476 }
15477 return this.container;
15478 }
15479 }
15480 class InkAnnotationElement extends AnnotationElement {
15481 #polylines = [];
15482 constructor(parameters) {
15483 super(parameters, {
15484 isRenderable: true,
15485 ignoreBorder: true
15486 });
15487 this.containerClassName = "inkAnnotation";
15488 this.svgElementName = "svg:polyline";
15489 this.annotationEditorType = this.data.it === "InkHighlight" ? AnnotationEditorType.HIGHLIGHT : AnnotationEditorType.INK;
15490 }
15491 render() {
15492 this.container.classList.add(this.containerClassName);
15493 const {
15494 data: {
15495 rect,
15496 inkLists,
15497 borderStyle,
15498 popupRef
15499 }
15500 } = this;
15501 const {
15502 width,
15503 height
15504 } = getRectDims(rect);
15505 const svg = this.svgFactory.create(width, height, true);
15506 for (const inkList of inkLists) {
15507 let points = [];
15508 for (let i = 0, ii = inkList.length; i < ii; i += 2) {
15509 const x = inkList[i] - rect[0];
15510 const y = rect[3] - inkList[i + 1];
15511 points.push(`${x},${y}`);
15512 }
15513 points = points.join(" ");
15514 const polyline = this.svgFactory.createElement(this.svgElementName);
15515 this.#polylines.push(polyline);
15516 polyline.setAttribute("points", points);
15517 polyline.setAttribute("stroke-width", borderStyle.width || 1);
15518 polyline.setAttribute("stroke", "transparent");
15519 polyline.setAttribute("fill", "transparent");
15520 if (!popupRef && this.hasPopupData) {
15521 this._createPopup();
15522 }
15523 svg.append(polyline);
15524 }
15525 this.container.append(svg);
15526 this._editOnDoubleClick();
15527 return this.container;
15528 }
15529 getElementsToTriggerPopup() {
15530 return this.#polylines;
15531 }
15532 addHighlightArea() {
15533 this.container.classList.add("highlightArea");
15534 }
15535 }
15536 class HighlightAnnotationElement extends AnnotationElement {
15537 constructor(parameters) {
15538 super(parameters, {
15539 isRenderable: true,
15540 ignoreBorder: true,
15541 createQuadrilaterals: true
15542 });
15543 this.annotationEditorType = AnnotationEditorType.HIGHLIGHT;
15544 }
15545 render() {
15546 if (!this.data.popupRef && this.hasPopupData) {
15547 this._createPopup();
15548 }
15549 this.container.classList.add("highlightAnnotation");
15550 this._editOnDoubleClick();
15551 return this.container;
15552 }
15553 }
15554 class UnderlineAnnotationElement extends AnnotationElement {
15555 constructor(parameters) {
15556 super(parameters, {
15557 isRenderable: true,
15558 ignoreBorder: true,
15559 createQuadrilaterals: true
15560 });
15561 }
15562 render() {
15563 if (!this.data.popupRef && this.hasPopupData) {
15564 this._createPopup();
15565 }
15566 this.container.classList.add("underlineAnnotation");
15567 return this.container;
15568 }
15569 }
15570 class SquigglyAnnotationElement extends AnnotationElement {
15571 constructor(parameters) {
15572 super(parameters, {
15573 isRenderable: true,
15574 ignoreBorder: true,
15575 createQuadrilaterals: true
15576 });
15577 }
15578 render() {
15579 if (!this.data.popupRef && this.hasPopupData) {
15580 this._createPopup();
15581 }
15582 this.container.classList.add("squigglyAnnotation");
15583 return this.container;
15584 }
15585 }
15586 class StrikeOutAnnotationElement extends AnnotationElement {
15587 constructor(parameters) {
15588 super(parameters, {
15589 isRenderable: true,
15590 ignoreBorder: true,
15591 createQuadrilaterals: true
15592 });
15593 }
15594 render() {
15595 if (!this.data.popupRef && this.hasPopupData) {
15596 this._createPopup();
15597 }
15598 this.container.classList.add("strikeoutAnnotation");
15599 return this.container;
15600 }
15601 }
15602 class StampAnnotationElement extends AnnotationElement {
15603 constructor(parameters) {
15604 super(parameters, {
15605 isRenderable: true,
15606 ignoreBorder: true
15607 });
15608 this.annotationEditorType = AnnotationEditorType.STAMP;
15609 }
15610 render() {
15611 this.container.classList.add("stampAnnotation");
15612 this.container.setAttribute("role", "img");
15613 if (!this.data.popupRef && this.hasPopupData) {
15614 this._createPopup();
15615 }
15616 this._editOnDoubleClick();
15617 return this.container;
15618 }
15619 }
15620 class FileAttachmentAnnotationElement extends AnnotationElement {
15621 #trigger = null;
15622 constructor(parameters) {
15623 super(parameters, {
15624 isRenderable: true
15625 });
15626 const {
15627 file
15628 } = this.data;
15629 this.filename = file.filename;
15630 this.content = file.content;
15631 this.linkService.eventBus?.dispatch("fileattachmentannotation", {
15632 source: this,
15633 ...file
15634 });
15635 }
15636 render() {
15637 this.container.classList.add("fileAttachmentAnnotation");
15638 const {
15639 container,
15640 data
15641 } = this;
15642 let trigger;
15643 if (data.hasAppearance || data.fillAlpha === 0) {
15644 trigger = document.createElement("div");
15645 } else {
15646 trigger = document.createElement("img");
15647 trigger.src = `${this.imageResourcesPath}annotation-${/paperclip/i.test(data.name) ? "paperclip" : "pushpin"}.svg`;
15648 if (data.fillAlpha && data.fillAlpha < 1) {
15649 trigger.style = `filter: opacity(${Math.round(data.fillAlpha * 100)}%);`;
15650 }
15651 }
15652 trigger.addEventListener("dblclick", this.#download.bind(this));
15653 this.#trigger = trigger;
15654 const {
15655 isMac
15656 } = util_FeatureTest.platform;
15657 container.addEventListener("keydown", evt => {
15658 if (evt.key === "Enter" && (isMac ? evt.metaKey : evt.ctrlKey)) {
15659 this.#download();
15660 }
15661 });
15662 if (!data.popupRef && this.hasPopupData) {
15663 this._createPopup();
15664 } else {
15665 trigger.classList.add("popupTriggerArea");
15666 }
15667 container.append(trigger);
15668 return container;
15669 }
15670 getElementsToTriggerPopup() {
15671 return this.#trigger;
15672 }
15673 addHighlightArea() {
15674 this.container.classList.add("highlightArea");
15675 }
15676 #download() {
15677 this.downloadManager?.openOrDownloadData(this.content, this.filename);
15678 }
15679 }
15680 class AnnotationLayer {
15681 #accessibilityManager = null;
15682 #annotationCanvasMap = null;
15683 #editableAnnotations = new Map();
15684 #structTreeLayer = null;
15685 constructor({
15686 div,
15687 accessibilityManager,
15688 annotationCanvasMap,
15689 annotationEditorUIManager,
15690 page,
15691 viewport,
15692 structTreeLayer
15693 }) {
15694 this.div = div;
15695 this.#accessibilityManager = accessibilityManager;
15696 this.#annotationCanvasMap = annotationCanvasMap;
15697 this.#structTreeLayer = structTreeLayer || null;
15698 this.page = page;
15699 this.viewport = viewport;
15700 this.zIndex = 0;
15701 this._annotationEditorUIManager = annotationEditorUIManager;
15702 }
15703 hasEditableAnnotations() {
15704 return this.#editableAnnotations.size > 0;
15705 }
15706 async #appendElement(element, id) {
15707 const contentElement = element.firstChild || element;
15708 const annotationId = contentElement.id = `${AnnotationPrefix}${id}`;
15709 const ariaAttributes = await this.#structTreeLayer?.getAriaAttributes(annotationId);
15710 if (ariaAttributes) {
15711 for (const [key, value] of ariaAttributes) {
15712 contentElement.setAttribute(key, value);
15713 }
15714 }
15715 this.div.append(element);
15716 this.#accessibilityManager?.moveElementInDOM(this.div, element, contentElement, false);
15717 }
15718 async render(params) {
15719 const {
15720 annotations
15721 } = params;
15722 const layer = this.div;
15723 setLayerDimensions(layer, this.viewport);
15724 const popupToElements = new Map();
15725 const elementParams = {
15726 data: null,
15727 layer,
15728 linkService: params.linkService,
15729 downloadManager: params.downloadManager,
15730 imageResourcesPath: params.imageResourcesPath || "",
15731 renderForms: params.renderForms !== false,
15732 svgFactory: new DOMSVGFactory(),
15733 annotationStorage: params.annotationStorage || new AnnotationStorage(),
15734 enableScripting: params.enableScripting === true,
15735 hasJSActions: params.hasJSActions,
15736 fieldObjects: params.fieldObjects,
15737 parent: this,
15738 elements: null
15739 };
15740 for (const data of annotations) {
15741 if (data.noHTML) {
15742 continue;
15743 }
15744 const isPopupAnnotation = data.annotationType === AnnotationType.POPUP;
15745 if (!isPopupAnnotation) {
15746 const {
15747 width,
15748 height
15749 } = getRectDims(data.rect);
15750 if (width <= 0 || height <= 0) {
15751 continue;
15752 }
15753 } else {
15754 const elements = popupToElements.get(data.id);
15755 if (!elements) {
15756 continue;
15757 }
15758 elementParams.elements = elements;
15759 }
15760 elementParams.data = data;
15761 const element = AnnotationElementFactory.create(elementParams);
15762 if (!element.isRenderable) {
15763 continue;
15764 }
15765 if (!isPopupAnnotation && data.popupRef) {
15766 const elements = popupToElements.get(data.popupRef);
15767 if (!elements) {
15768 popupToElements.set(data.popupRef, [element]);
15769 } else {
15770 elements.push(element);
15771 }
15772 }
15773 const rendered = element.render();
15774 if (data.hidden) {
15775 rendered.style.visibility = "hidden";
15776 }
15777 await this.#appendElement(rendered, data.id);
15778 if (element._isEditable) {
15779 this.#editableAnnotations.set(element.data.id, element);
15780 this._annotationEditorUIManager?.renderAnnotationElement(element);
15781 }
15782 }
15783 this.#setAnnotationCanvasMap();
15784 }
15785 update({
15786 viewport
15787 }) {
15788 const layer = this.div;
15789 this.viewport = viewport;
15790 setLayerDimensions(layer, {
15791 rotation: viewport.rotation
15792 });
15793 this.#setAnnotationCanvasMap();
15794 layer.hidden = false;
15795 }
15796 #setAnnotationCanvasMap() {
15797 if (!this.#annotationCanvasMap) {
15798 return;
15799 }
15800 const layer = this.div;
15801 for (const [id, canvas] of this.#annotationCanvasMap) {
15802 const element = layer.querySelector(`[data-annotation-id="${id}"]`);
15803 if (!element) {
15804 continue;
15805 }
15806 canvas.className = "annotationContent";
15807 const {
15808 firstChild
15809 } = element;
15810 if (!firstChild) {
15811 element.append(canvas);
15812 } else if (firstChild.nodeName === "CANVAS") {
15813 firstChild.replaceWith(canvas);
15814 } else if (!firstChild.classList.contains("annotationContent")) {
15815 firstChild.before(canvas);
15816 } else {
15817 firstChild.after(canvas);
15818 }
15819 }
15820 this.#annotationCanvasMap.clear();
15821 }
15822 getEditableAnnotations() {
15823 return Array.from(this.#editableAnnotations.values());
15824 }
15825 getEditableAnnotation(id) {
15826 return this.#editableAnnotations.get(id);
15827 }
15828 }
15829
15830 ;// ./src/display/editor/freetext.js
15831
15832
15833
15834
15835 const EOL_PATTERN = /\r\n?|\n/g;
15836 class FreeTextEditor extends AnnotationEditor {
15837 #color;
15838 #content = "";
15839 #editorDivId = `${this.id}-editor`;
15840 #editModeAC = null;
15841 #fontSize;
15842 static _freeTextDefaultContent = "";
15843 static _internalPadding = 0;
15844 static _defaultColor = null;
15845 static _defaultFontSize = 10;
15846 static get _keyboardManager() {
15847 const proto = FreeTextEditor.prototype;
15848 const arrowChecker = self => self.isEmpty();
15849 const small = AnnotationEditorUIManager.TRANSLATE_SMALL;
15850 const big = AnnotationEditorUIManager.TRANSLATE_BIG;
15851 return shadow(this, "_keyboardManager", new KeyboardManager([[["ctrl+s", "mac+meta+s", "ctrl+p", "mac+meta+p"], proto.commitOrRemove, {
15852 bubbles: true
15853 }], [["ctrl+Enter", "mac+meta+Enter", "Escape", "mac+Escape"], proto.commitOrRemove], [["ArrowLeft", "mac+ArrowLeft"], proto._translateEmpty, {
15854 args: [-small, 0],
15855 checker: arrowChecker
15856 }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], proto._translateEmpty, {
15857 args: [-big, 0],
15858 checker: arrowChecker
15859 }], [["ArrowRight", "mac+ArrowRight"], proto._translateEmpty, {
15860 args: [small, 0],
15861 checker: arrowChecker
15862 }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], proto._translateEmpty, {
15863 args: [big, 0],
15864 checker: arrowChecker
15865 }], [["ArrowUp", "mac+ArrowUp"], proto._translateEmpty, {
15866 args: [0, -small],
15867 checker: arrowChecker
15868 }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], proto._translateEmpty, {
15869 args: [0, -big],
15870 checker: arrowChecker
15871 }], [["ArrowDown", "mac+ArrowDown"], proto._translateEmpty, {
15872 args: [0, small],
15873 checker: arrowChecker
15874 }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], proto._translateEmpty, {
15875 args: [0, big],
15876 checker: arrowChecker
15877 }]]));
15878 }
15879 static _type = "freetext";
15880 static _editorType = AnnotationEditorType.FREETEXT;
15881 constructor(params) {
15882 super({
15883 ...params,
15884 name: "freeTextEditor"
15885 });
15886 this.#color = params.color || FreeTextEditor._defaultColor || AnnotationEditor._defaultLineColor;
15887 this.#fontSize = params.fontSize || FreeTextEditor._defaultFontSize;
15888 }
15889 static initialize(l10n, uiManager) {
15890 AnnotationEditor.initialize(l10n, uiManager, {
15891 strings: ["pdfjs-free-text-default-content"]
15892 });
15893 const style = getComputedStyle(document.documentElement);
15894 this._internalPadding = parseFloat(style.getPropertyValue("--freetext-padding"));
15895 }
15896 static updateDefaultParams(type, value) {
15897 switch (type) {
15898 case AnnotationEditorParamsType.FREETEXT_SIZE:
15899 FreeTextEditor._defaultFontSize = value;
15900 break;
15901 case AnnotationEditorParamsType.FREETEXT_COLOR:
15902 FreeTextEditor._defaultColor = value;
15903 break;
15904 }
15905 }
15906 updateParams(type, value) {
15907 switch (type) {
15908 case AnnotationEditorParamsType.FREETEXT_SIZE:
15909 this.#updateFontSize(value);
15910 break;
15911 case AnnotationEditorParamsType.FREETEXT_COLOR:
15912 this.#updateColor(value);
15913 break;
15914 }
15915 }
15916 static get defaultPropertiesToUpdate() {
15917 return [[AnnotationEditorParamsType.FREETEXT_SIZE, FreeTextEditor._defaultFontSize], [AnnotationEditorParamsType.FREETEXT_COLOR, FreeTextEditor._defaultColor || AnnotationEditor._defaultLineColor]];
15918 }
15919 get propertiesToUpdate() {
15920 return [[AnnotationEditorParamsType.FREETEXT_SIZE, this.#fontSize], [AnnotationEditorParamsType.FREETEXT_COLOR, this.#color]];
15921 }
15922 #updateFontSize(fontSize) {
15923 const setFontsize = size => {
15924 this.editorDiv.style.fontSize = `calc(${size}px * var(--scale-factor))`;
15925 this.translate(0, -(size - this.#fontSize) * this.parentScale);
15926 this.#fontSize = size;
15927 this.#setEditorDimensions();
15928 };
15929 const savedFontsize = this.#fontSize;
15930 this.addCommands({
15931 cmd: setFontsize.bind(this, fontSize),
15932 undo: setFontsize.bind(this, savedFontsize),
15933 post: this._uiManager.updateUI.bind(this._uiManager, this),
15934 mustExec: true,
15935 type: AnnotationEditorParamsType.FREETEXT_SIZE,
15936 overwriteIfSameType: true,
15937 keepUndo: true
15938 });
15939 }
15940 #updateColor(color) {
15941 const setColor = col => {
15942 this.#color = this.editorDiv.style.color = col;
15943 };
15944 const savedColor = this.#color;
15945 this.addCommands({
15946 cmd: setColor.bind(this, color),
15947 undo: setColor.bind(this, savedColor),
15948 post: this._uiManager.updateUI.bind(this._uiManager, this),
15949 mustExec: true,
15950 type: AnnotationEditorParamsType.FREETEXT_COLOR,
15951 overwriteIfSameType: true,
15952 keepUndo: true
15953 });
15954 }
15955 _translateEmpty(x, y) {
15956 this._uiManager.translateSelectedEditors(x, y, true);
15957 }
15958 getInitialTranslation() {
15959 const scale = this.parentScale;
15960 return [-FreeTextEditor._internalPadding * scale, -(FreeTextEditor._internalPadding + this.#fontSize) * scale];
15961 }
15962 rebuild() {
15963 if (!this.parent) {
15964 return;
15965 }
15966 super.rebuild();
15967 if (this.div === null) {
15968 return;
15969 }
15970 if (!this.isAttachedToDOM) {
15971 this.parent.add(this);
15972 }
15973 }
15974 enableEditMode() {
15975 if (this.isInEditMode()) {
15976 return;
15977 }
15978 this.parent.setEditingState(false);
15979 this.parent.updateToolbar(AnnotationEditorType.FREETEXT);
15980 super.enableEditMode();
15981 this.overlayDiv.classList.remove("enabled");
15982 this.editorDiv.contentEditable = true;
15983 this._isDraggable = false;
15984 this.div.removeAttribute("aria-activedescendant");
15985 this.#editModeAC = new AbortController();
15986 const signal = this._uiManager.combinedSignal(this.#editModeAC);
15987 this.editorDiv.addEventListener("keydown", this.editorDivKeydown.bind(this), {
15988 signal
15989 });
15990 this.editorDiv.addEventListener("focus", this.editorDivFocus.bind(this), {
15991 signal
15992 });
15993 this.editorDiv.addEventListener("blur", this.editorDivBlur.bind(this), {
15994 signal
15995 });
15996 this.editorDiv.addEventListener("input", this.editorDivInput.bind(this), {
15997 signal
15998 });
15999 this.editorDiv.addEventListener("paste", this.editorDivPaste.bind(this), {
16000 signal
16001 });
16002 }
16003 disableEditMode() {
16004 if (!this.isInEditMode()) {
16005 return;
16006 }
16007 this.parent.setEditingState(true);
16008 super.disableEditMode();
16009 this.overlayDiv.classList.add("enabled");
16010 this.editorDiv.contentEditable = false;
16011 this.div.setAttribute("aria-activedescendant", this.#editorDivId);
16012 this._isDraggable = true;
16013 this.#editModeAC?.abort();
16014 this.#editModeAC = null;
16015 this.div.focus({
16016 preventScroll: true
16017 });
16018 this.isEditing = false;
16019 this.parent.div.classList.add("freetextEditing");
16020 }
16021 focusin(event) {
16022 if (!this._focusEventsAllowed) {
16023 return;
16024 }
16025 super.focusin(event);
16026 if (event.target !== this.editorDiv) {
16027 this.editorDiv.focus();
16028 }
16029 }
16030 onceAdded() {
16031 if (this.width) {
16032 return;
16033 }
16034 this.enableEditMode();
16035 this.editorDiv.focus();
16036 if (this._initialOptions?.isCentered) {
16037 this.center();
16038 }
16039 this._initialOptions = null;
16040 }
16041 isEmpty() {
16042 return !this.editorDiv || this.editorDiv.innerText.trim() === "";
16043 }
16044 remove() {
16045 this.isEditing = false;
16046 if (this.parent) {
16047 this.parent.setEditingState(true);
16048 this.parent.div.classList.add("freetextEditing");
16049 }
16050 super.remove();
16051 }
16052 #extractText() {
16053 const buffer = [];
16054 this.editorDiv.normalize();
16055 let prevChild = null;
16056 for (const child of this.editorDiv.childNodes) {
16057 if (prevChild?.nodeType === Node.TEXT_NODE && child.nodeName === "BR") {
16058 continue;
16059 }
16060 buffer.push(FreeTextEditor.#getNodeContent(child));
16061 prevChild = child;
16062 }
16063 return buffer.join("\n");
16064 }
16065 #setEditorDimensions() {
16066 const [parentWidth, parentHeight] = this.parentDimensions;
16067 let rect;
16068 if (this.isAttachedToDOM) {
16069 rect = this.div.getBoundingClientRect();
16070 } else {
16071 const {
16072 currentLayer,
16073 div
16074 } = this;
16075 const savedDisplay = div.style.display;
16076 const savedVisibility = div.classList.contains("hidden");
16077 div.classList.remove("hidden");
16078 div.style.display = "hidden";
16079 currentLayer.div.append(this.div);
16080 rect = div.getBoundingClientRect();
16081 div.remove();
16082 div.style.display = savedDisplay;
16083 div.classList.toggle("hidden", savedVisibility);
16084 }
16085 if (this.rotation % 180 === this.parentRotation % 180) {
16086 this.width = rect.width / parentWidth;
16087 this.height = rect.height / parentHeight;
16088 } else {
16089 this.width = rect.height / parentWidth;
16090 this.height = rect.width / parentHeight;
16091 }
16092 this.fixAndSetPosition();
16093 }
16094 commit() {
16095 if (!this.isInEditMode()) {
16096 return;
16097 }
16098 super.commit();
16099 this.disableEditMode();
16100 const savedText = this.#content;
16101 const newText = this.#content = this.#extractText().trimEnd();
16102 if (savedText === newText) {
16103 return;
16104 }
16105 const setText = text => {
16106 this.#content = text;
16107 if (!text) {
16108 this.remove();
16109 return;
16110 }
16111 this.#setContent();
16112 this._uiManager.rebuild(this);
16113 this.#setEditorDimensions();
16114 };
16115 this.addCommands({
16116 cmd: () => {
16117 setText(newText);
16118 },
16119 undo: () => {
16120 setText(savedText);
16121 },
16122 mustExec: false
16123 });
16124 this.#setEditorDimensions();
16125 }
16126 shouldGetKeyboardEvents() {
16127 return this.isInEditMode();
16128 }
16129 enterInEditMode() {
16130 this.enableEditMode();
16131 this.editorDiv.focus();
16132 }
16133 dblclick(event) {
16134 this.enterInEditMode();
16135 }
16136 keydown(event) {
16137 if (event.target === this.div && event.key === "Enter") {
16138 this.enterInEditMode();
16139 event.preventDefault();
16140 }
16141 }
16142 editorDivKeydown(event) {
16143 FreeTextEditor._keyboardManager.exec(this, event);
16144 }
16145 editorDivFocus(event) {
16146 this.isEditing = true;
16147 }
16148 editorDivBlur(event) {
16149 this.isEditing = false;
16150 }
16151 editorDivInput(event) {
16152 this.parent.div.classList.toggle("freetextEditing", this.isEmpty());
16153 }
16154 disableEditing() {
16155 this.editorDiv.setAttribute("role", "comment");
16156 this.editorDiv.removeAttribute("aria-multiline");
16157 }
16158 enableEditing() {
16159 this.editorDiv.setAttribute("role", "textbox");
16160 this.editorDiv.setAttribute("aria-multiline", true);
16161 }
16162 render() {
16163 if (this.div) {
16164 return this.div;
16165 }
16166 let baseX, baseY;
16167 if (this.width) {
16168 baseX = this.x;
16169 baseY = this.y;
16170 }
16171 super.render();
16172 this.editorDiv = document.createElement("div");
16173 this.editorDiv.className = "internal";
16174 this.editorDiv.setAttribute("id", this.#editorDivId);
16175 this.editorDiv.setAttribute("data-l10n-id", "pdfjs-free-text");
16176 this.enableEditing();
16177 AnnotationEditor._l10nPromise.get("pdfjs-free-text-default-content").then(msg => this.editorDiv?.setAttribute("default-content", msg));
16178 this.editorDiv.contentEditable = true;
16179 const {
16180 style
16181 } = this.editorDiv;
16182 style.fontSize = `calc(${this.#fontSize}px * var(--scale-factor))`;
16183 style.color = this.#color;
16184 this.div.append(this.editorDiv);
16185 this.overlayDiv = document.createElement("div");
16186 this.overlayDiv.classList.add("overlay", "enabled");
16187 this.div.append(this.overlayDiv);
16188 bindEvents(this, this.div, ["dblclick", "keydown"]);
16189 if (this.width) {
16190 const [parentWidth, parentHeight] = this.parentDimensions;
16191 if (this.annotationElementId) {
16192 const {
16193 position
16194 } = this._initialData;
16195 let [tx, ty] = this.getInitialTranslation();
16196 [tx, ty] = this.pageTranslationToScreen(tx, ty);
16197 const [pageWidth, pageHeight] = this.pageDimensions;
16198 const [pageX, pageY] = this.pageTranslation;
16199 let posX, posY;
16200 switch (this.rotation) {
16201 case 0:
16202 posX = baseX + (position[0] - pageX) / pageWidth;
16203 posY = baseY + this.height - (position[1] - pageY) / pageHeight;
16204 break;
16205 case 90:
16206 posX = baseX + (position[0] - pageX) / pageWidth;
16207 posY = baseY - (position[1] - pageY) / pageHeight;
16208 [tx, ty] = [ty, -tx];
16209 break;
16210 case 180:
16211 posX = baseX - this.width + (position[0] - pageX) / pageWidth;
16212 posY = baseY - (position[1] - pageY) / pageHeight;
16213 [tx, ty] = [-tx, -ty];
16214 break;
16215 case 270:
16216 posX = baseX + (position[0] - pageX - this.height * pageHeight) / pageWidth;
16217 posY = baseY + (position[1] - pageY - this.width * pageWidth) / pageHeight;
16218 [tx, ty] = [-ty, tx];
16219 break;
16220 }
16221 this.setAt(posX * parentWidth, posY * parentHeight, tx, ty);
16222 } else {
16223 this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
16224 }
16225 this.#setContent();
16226 this._isDraggable = true;
16227 this.editorDiv.contentEditable = false;
16228 } else {
16229 this._isDraggable = false;
16230 this.editorDiv.contentEditable = true;
16231 }
16232 return this.div;
16233 }
16234 static #getNodeContent(node) {
16235 return (node.nodeType === Node.TEXT_NODE ? node.nodeValue : node.innerText).replaceAll(EOL_PATTERN, "");
16236 }
16237 editorDivPaste(event) {
16238 const clipboardData = event.clipboardData || window.clipboardData;
16239 const {
16240 types
16241 } = clipboardData;
16242 if (types.length === 1 && types[0] === "text/plain") {
16243 return;
16244 }
16245 event.preventDefault();
16246 const paste = FreeTextEditor.#deserializeContent(clipboardData.getData("text") || "").replaceAll(EOL_PATTERN, "\n");
16247 if (!paste) {
16248 return;
16249 }
16250 const selection = window.getSelection();
16251 if (!selection.rangeCount) {
16252 return;
16253 }
16254 this.editorDiv.normalize();
16255 selection.deleteFromDocument();
16256 const range = selection.getRangeAt(0);
16257 if (!paste.includes("\n")) {
16258 range.insertNode(document.createTextNode(paste));
16259 this.editorDiv.normalize();
16260 selection.collapseToStart();
16261 return;
16262 }
16263 const {
16264 startContainer,
16265 startOffset
16266 } = range;
16267 const bufferBefore = [];
16268 const bufferAfter = [];
16269 if (startContainer.nodeType === Node.TEXT_NODE) {
16270 const parent = startContainer.parentElement;
16271 bufferAfter.push(startContainer.nodeValue.slice(startOffset).replaceAll(EOL_PATTERN, ""));
16272 if (parent !== this.editorDiv) {
16273 let buffer = bufferBefore;
16274 for (const child of this.editorDiv.childNodes) {
16275 if (child === parent) {
16276 buffer = bufferAfter;
16277 continue;
16278 }
16279 buffer.push(FreeTextEditor.#getNodeContent(child));
16280 }
16281 }
16282 bufferBefore.push(startContainer.nodeValue.slice(0, startOffset).replaceAll(EOL_PATTERN, ""));
16283 } else if (startContainer === this.editorDiv) {
16284 let buffer = bufferBefore;
16285 let i = 0;
16286 for (const child of this.editorDiv.childNodes) {
16287 if (i++ === startOffset) {
16288 buffer = bufferAfter;
16289 }
16290 buffer.push(FreeTextEditor.#getNodeContent(child));
16291 }
16292 }
16293 this.#content = `${bufferBefore.join("\n")}${paste}${bufferAfter.join("\n")}`;
16294 this.#setContent();
16295 const newRange = new Range();
16296 let beforeLength = bufferBefore.reduce((acc, line) => acc + line.length, 0);
16297 for (const {
16298 firstChild
16299 } of this.editorDiv.childNodes) {
16300 if (firstChild.nodeType === Node.TEXT_NODE) {
16301 const length = firstChild.nodeValue.length;
16302 if (beforeLength <= length) {
16303 newRange.setStart(firstChild, beforeLength);
16304 newRange.setEnd(firstChild, beforeLength);
16305 break;
16306 }
16307 beforeLength -= length;
16308 }
16309 }
16310 selection.removeAllRanges();
16311 selection.addRange(newRange);
16312 }
16313 #setContent() {
16314 this.editorDiv.replaceChildren();
16315 if (!this.#content) {
16316 return;
16317 }
16318 for (const line of this.#content.split("\n")) {
16319 const div = document.createElement("div");
16320 div.append(line ? document.createTextNode(line) : document.createElement("br"));
16321 this.editorDiv.append(div);
16322 }
16323 }
16324 #serializeContent() {
16325 return this.#content.replaceAll("\xa0", " ");
16326 }
16327 static #deserializeContent(content) {
16328 return content.replaceAll(" ", "\xa0");
16329 }
16330 get contentDiv() {
16331 return this.editorDiv;
16332 }
16333 static async deserialize(data, parent, uiManager) {
16334 let initialData = null;
16335 if (data instanceof FreeTextAnnotationElement) {
16336 const {
16337 data: {
16338 defaultAppearanceData: {
16339 fontSize,
16340 fontColor
16341 },
16342 rect,
16343 rotation,
16344 id,
16345 popupRef
16346 },
16347 textContent,
16348 textPosition,
16349 parent: {
16350 page: {
16351 pageNumber
16352 }
16353 }
16354 } = data;
16355 if (!textContent || textContent.length === 0) {
16356 return null;
16357 }
16358 initialData = data = {
16359 annotationType: AnnotationEditorType.FREETEXT,
16360 color: Array.from(fontColor),
16361 fontSize,
16362 value: textContent.join("\n"),
16363 position: textPosition,
16364 pageIndex: pageNumber - 1,
16365 rect: rect.slice(0),
16366 rotation,
16367 id,
16368 deleted: false,
16369 popupRef
16370 };
16371 }
16372 const editor = await super.deserialize(data, parent, uiManager);
16373 editor.#fontSize = data.fontSize;
16374 editor.#color = Util.makeHexColor(...data.color);
16375 editor.#content = FreeTextEditor.#deserializeContent(data.value);
16376 editor.annotationElementId = data.id || null;
16377 editor._initialData = initialData;
16378 return editor;
16379 }
16380 serialize(isForCopying = false) {
16381 if (this.isEmpty()) {
16382 return null;
16383 }
16384 if (this.deleted) {
16385 return this.serializeDeleted();
16386 }
16387 const padding = FreeTextEditor._internalPadding * this.parentScale;
16388 const rect = this.getRect(padding, padding);
16389 const color = AnnotationEditor._colorManager.convert(this.isAttachedToDOM ? getComputedStyle(this.editorDiv).color : this.#color);
16390 const serialized = {
16391 annotationType: AnnotationEditorType.FREETEXT,
16392 color,
16393 fontSize: this.#fontSize,
16394 value: this.#serializeContent(),
16395 pageIndex: this.pageIndex,
16396 rect,
16397 rotation: this.rotation,
16398 structTreeParentId: this._structTreeParentId
16399 };
16400 if (isForCopying) {
16401 return serialized;
16402 }
16403 if (this.annotationElementId && !this.#hasElementChanged(serialized)) {
16404 return null;
16405 }
16406 serialized.id = this.annotationElementId;
16407 return serialized;
16408 }
16409 #hasElementChanged(serialized) {
16410 const {
16411 value,
16412 fontSize,
16413 color,
16414 pageIndex
16415 } = this._initialData;
16416 return this._hasBeenMoved || serialized.value !== value || serialized.fontSize !== fontSize || serialized.color.some((c, i) => c !== color[i]) || serialized.pageIndex !== pageIndex;
16417 }
16418 renderAnnotationElement(annotation) {
16419 const content = super.renderAnnotationElement(annotation);
16420 if (this.deleted) {
16421 return content;
16422 }
16423 const {
16424 style
16425 } = content;
16426 style.fontSize = `calc(${this.#fontSize}px * var(--scale-factor))`;
16427 style.color = this.#color;
16428 content.replaceChildren();
16429 for (const line of this.#content.split("\n")) {
16430 const div = document.createElement("div");
16431 div.append(line ? document.createTextNode(line) : document.createElement("br"));
16432 content.append(div);
16433 }
16434 const padding = FreeTextEditor._internalPadding * this.parentScale;
16435 annotation.updateEdited({
16436 rect: this.getRect(padding, padding),
16437 popupContent: this.#content
16438 });
16439 return content;
16440 }
16441 resetAnnotationElement(annotation) {
16442 super.resetAnnotationElement(annotation);
16443 annotation.resetEdited();
16444 }
16445 }
16446
16447 ;// ./src/display/editor/outliner.js
16448
16449 class Outliner {
16450 #box;
16451 #verticalEdges = [];
16452 #intervals = [];
16453 constructor(boxes, borderWidth = 0, innerMargin = 0, isLTR = true) {
16454 let minX = Infinity;
16455 let maxX = -Infinity;
16456 let minY = Infinity;
16457 let maxY = -Infinity;
16458 const NUMBER_OF_DIGITS = 4;
16459 const EPSILON = 10 ** -NUMBER_OF_DIGITS;
16460 for (const {
16461 x,
16462 y,
16463 width,
16464 height
16465 } of boxes) {
16466 const x1 = Math.floor((x - borderWidth) / EPSILON) * EPSILON;
16467 const x2 = Math.ceil((x + width + borderWidth) / EPSILON) * EPSILON;
16468 const y1 = Math.floor((y - borderWidth) / EPSILON) * EPSILON;
16469 const y2 = Math.ceil((y + height + borderWidth) / EPSILON) * EPSILON;
16470 const left = [x1, y1, y2, true];
16471 const right = [x2, y1, y2, false];
16472 this.#verticalEdges.push(left, right);
16473 minX = Math.min(minX, x1);
16474 maxX = Math.max(maxX, x2);
16475 minY = Math.min(minY, y1);
16476 maxY = Math.max(maxY, y2);
16477 }
16478 const bboxWidth = maxX - minX + 2 * innerMargin;
16479 const bboxHeight = maxY - minY + 2 * innerMargin;
16480 const shiftedMinX = minX - innerMargin;
16481 const shiftedMinY = minY - innerMargin;
16482 const lastEdge = this.#verticalEdges.at(isLTR ? -1 : -2);
16483 const lastPoint = [lastEdge[0], lastEdge[2]];
16484 for (const edge of this.#verticalEdges) {
16485 const [x, y1, y2] = edge;
16486 edge[0] = (x - shiftedMinX) / bboxWidth;
16487 edge[1] = (y1 - shiftedMinY) / bboxHeight;
16488 edge[2] = (y2 - shiftedMinY) / bboxHeight;
16489 }
16490 this.#box = {
16491 x: shiftedMinX,
16492 y: shiftedMinY,
16493 width: bboxWidth,
16494 height: bboxHeight,
16495 lastPoint
16496 };
16497 }
16498 getOutlines() {
16499 this.#verticalEdges.sort((a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]);
16500 const outlineVerticalEdges = [];
16501 for (const edge of this.#verticalEdges) {
16502 if (edge[3]) {
16503 outlineVerticalEdges.push(...this.#breakEdge(edge));
16504 this.#insert(edge);
16505 } else {
16506 this.#remove(edge);
16507 outlineVerticalEdges.push(...this.#breakEdge(edge));
16508 }
16509 }
16510 return this.#getOutlines(outlineVerticalEdges);
16511 }
16512 #getOutlines(outlineVerticalEdges) {
16513 const edges = [];
16514 const allEdges = new Set();
16515 for (const edge of outlineVerticalEdges) {
16516 const [x, y1, y2] = edge;
16517 edges.push([x, y1, edge], [x, y2, edge]);
16518 }
16519 edges.sort((a, b) => a[1] - b[1] || a[0] - b[0]);
16520 for (let i = 0, ii = edges.length; i < ii; i += 2) {
16521 const edge1 = edges[i][2];
16522 const edge2 = edges[i + 1][2];
16523 edge1.push(edge2);
16524 edge2.push(edge1);
16525 allEdges.add(edge1);
16526 allEdges.add(edge2);
16527 }
16528 const outlines = [];
16529 let outline;
16530 while (allEdges.size > 0) {
16531 const edge = allEdges.values().next().value;
16532 let [x, y1, y2, edge1, edge2] = edge;
16533 allEdges.delete(edge);
16534 let lastPointX = x;
16535 let lastPointY = y1;
16536 outline = [x, y2];
16537 outlines.push(outline);
16538 while (true) {
16539 let e;
16540 if (allEdges.has(edge1)) {
16541 e = edge1;
16542 } else if (allEdges.has(edge2)) {
16543 e = edge2;
16544 } else {
16545 break;
16546 }
16547 allEdges.delete(e);
16548 [x, y1, y2, edge1, edge2] = e;
16549 if (lastPointX !== x) {
16550 outline.push(lastPointX, lastPointY, x, lastPointY === y1 ? y1 : y2);
16551 lastPointX = x;
16552 }
16553 lastPointY = lastPointY === y1 ? y2 : y1;
16554 }
16555 outline.push(lastPointX, lastPointY);
16556 }
16557 return new HighlightOutline(outlines, this.#box);
16558 }
16559 #binarySearch(y) {
16560 const array = this.#intervals;
16561 let start = 0;
16562 let end = array.length - 1;
16563 while (start <= end) {
16564 const middle = start + end >> 1;
16565 const y1 = array[middle][0];
16566 if (y1 === y) {
16567 return middle;
16568 }
16569 if (y1 < y) {
16570 start = middle + 1;
16571 } else {
16572 end = middle - 1;
16573 }
16574 }
16575 return end + 1;
16576 }
16577 #insert([, y1, y2]) {
16578 const index = this.#binarySearch(y1);
16579 this.#intervals.splice(index, 0, [y1, y2]);
16580 }
16581 #remove([, y1, y2]) {
16582 const index = this.#binarySearch(y1);
16583 for (let i = index; i < this.#intervals.length; i++) {
16584 const [start, end] = this.#intervals[i];
16585 if (start !== y1) {
16586 break;
16587 }
16588 if (start === y1 && end === y2) {
16589 this.#intervals.splice(i, 1);
16590 return;
16591 }
16592 }
16593 for (let i = index - 1; i >= 0; i--) {
16594 const [start, end] = this.#intervals[i];
16595 if (start !== y1) {
16596 break;
16597 }
16598 if (start === y1 && end === y2) {
16599 this.#intervals.splice(i, 1);
16600 return;
16601 }
16602 }
16603 }
16604 #breakEdge(edge) {
16605 const [x, y1, y2] = edge;
16606 const results = [[x, y1, y2]];
16607 const index = this.#binarySearch(y2);
16608 for (let i = 0; i < index; i++) {
16609 const [start, end] = this.#intervals[i];
16610 for (let j = 0, jj = results.length; j < jj; j++) {
16611 const [, y3, y4] = results[j];
16612 if (end <= y3 || y4 <= start) {
16613 continue;
16614 }
16615 if (y3 >= start) {
16616 if (y4 > end) {
16617 results[j][1] = end;
16618 } else {
16619 if (jj === 1) {
16620 return [];
16621 }
16622 results.splice(j, 1);
16623 j--;
16624 jj--;
16625 }
16626 continue;
16627 }
16628 results[j][2] = start;
16629 if (y4 > end) {
16630 results.push([x, end, y4]);
16631 }
16632 }
16633 }
16634 return results;
16635 }
16636 }
16637 class Outline {
16638 toSVGPath() {
16639 throw new Error("Abstract method `toSVGPath` must be implemented.");
16640 }
16641 get box() {
16642 throw new Error("Abstract getter `box` must be implemented.");
16643 }
16644 serialize(_bbox, _rotation) {
16645 throw new Error("Abstract method `serialize` must be implemented.");
16646 }
16647 get free() {
16648 return this instanceof FreeHighlightOutline;
16649 }
16650 }
16651 class HighlightOutline extends Outline {
16652 #box;
16653 #outlines;
16654 constructor(outlines, box) {
16655 super();
16656 this.#outlines = outlines;
16657 this.#box = box;
16658 }
16659 toSVGPath() {
16660 const buffer = [];
16661 for (const polygon of this.#outlines) {
16662 let [prevX, prevY] = polygon;
16663 buffer.push(`M${prevX} ${prevY}`);
16664 for (let i = 2; i < polygon.length; i += 2) {
16665 const x = polygon[i];
16666 const y = polygon[i + 1];
16667 if (x === prevX) {
16668 buffer.push(`V${y}`);
16669 prevY = y;
16670 } else if (y === prevY) {
16671 buffer.push(`H${x}`);
16672 prevX = x;
16673 }
16674 }
16675 buffer.push("Z");
16676 }
16677 return buffer.join(" ");
16678 }
16679 serialize([blX, blY, trX, trY], _rotation) {
16680 const outlines = [];
16681 const width = trX - blX;
16682 const height = trY - blY;
16683 for (const outline of this.#outlines) {
16684 const points = new Array(outline.length);
16685 for (let i = 0; i < outline.length; i += 2) {
16686 points[i] = blX + outline[i] * width;
16687 points[i + 1] = trY - outline[i + 1] * height;
16688 }
16689 outlines.push(points);
16690 }
16691 return outlines;
16692 }
16693 get box() {
16694 return this.#box;
16695 }
16696 }
16697 class FreeOutliner {
16698 #box;
16699 #bottom = [];
16700 #innerMargin;
16701 #isLTR;
16702 #top = [];
16703 #last = new Float64Array(18);
16704 #lastX;
16705 #lastY;
16706 #min;
16707 #min_dist;
16708 #scaleFactor;
16709 #thickness;
16710 #points = [];
16711 static #MIN_DIST = 8;
16712 static #MIN_DIFF = 2;
16713 static #MIN = FreeOutliner.#MIN_DIST + FreeOutliner.#MIN_DIFF;
16714 constructor({
16715 x,
16716 y
16717 }, box, scaleFactor, thickness, isLTR, innerMargin = 0) {
16718 this.#box = box;
16719 this.#thickness = thickness * scaleFactor;
16720 this.#isLTR = isLTR;
16721 this.#last.set([NaN, NaN, NaN, NaN, x, y], 6);
16722 this.#innerMargin = innerMargin;
16723 this.#min_dist = FreeOutliner.#MIN_DIST * scaleFactor;
16724 this.#min = FreeOutliner.#MIN * scaleFactor;
16725 this.#scaleFactor = scaleFactor;
16726 this.#points.push(x, y);
16727 }
16728 get free() {
16729 return true;
16730 }
16731 isEmpty() {
16732 return isNaN(this.#last[8]);
16733 }
16734 #getLastCoords() {
16735 const lastTop = this.#last.subarray(4, 6);
16736 const lastBottom = this.#last.subarray(16, 18);
16737 const [x, y, width, height] = this.#box;
16738 return [(this.#lastX + (lastTop[0] - lastBottom[0]) / 2 - x) / width, (this.#lastY + (lastTop[1] - lastBottom[1]) / 2 - y) / height, (this.#lastX + (lastBottom[0] - lastTop[0]) / 2 - x) / width, (this.#lastY + (lastBottom[1] - lastTop[1]) / 2 - y) / height];
16739 }
16740 add({
16741 x,
16742 y
16743 }) {
16744 this.#lastX = x;
16745 this.#lastY = y;
16746 const [layerX, layerY, layerWidth, layerHeight] = this.#box;
16747 let [x1, y1, x2, y2] = this.#last.subarray(8, 12);
16748 const diffX = x - x2;
16749 const diffY = y - y2;
16750 const d = Math.hypot(diffX, diffY);
16751 if (d < this.#min) {
16752 return false;
16753 }
16754 const diffD = d - this.#min_dist;
16755 const K = diffD / d;
16756 const shiftX = K * diffX;
16757 const shiftY = K * diffY;
16758 let x0 = x1;
16759 let y0 = y1;
16760 x1 = x2;
16761 y1 = y2;
16762 x2 += shiftX;
16763 y2 += shiftY;
16764 this.#points?.push(x, y);
16765 const nX = -shiftY / diffD;
16766 const nY = shiftX / diffD;
16767 const thX = nX * this.#thickness;
16768 const thY = nY * this.#thickness;
16769 this.#last.set(this.#last.subarray(2, 8), 0);
16770 this.#last.set([x2 + thX, y2 + thY], 4);
16771 this.#last.set(this.#last.subarray(14, 18), 12);
16772 this.#last.set([x2 - thX, y2 - thY], 16);
16773 if (isNaN(this.#last[6])) {
16774 if (this.#top.length === 0) {
16775 this.#last.set([x1 + thX, y1 + thY], 2);
16776 this.#top.push(NaN, NaN, NaN, NaN, (x1 + thX - layerX) / layerWidth, (y1 + thY - layerY) / layerHeight);
16777 this.#last.set([x1 - thX, y1 - thY], 14);
16778 this.#bottom.push(NaN, NaN, NaN, NaN, (x1 - thX - layerX) / layerWidth, (y1 - thY - layerY) / layerHeight);
16779 }
16780 this.#last.set([x0, y0, x1, y1, x2, y2], 6);
16781 return !this.isEmpty();
16782 }
16783 this.#last.set([x0, y0, x1, y1, x2, y2], 6);
16784 const angle = Math.abs(Math.atan2(y0 - y1, x0 - x1) - Math.atan2(shiftY, shiftX));
16785 if (angle < Math.PI / 2) {
16786 [x1, y1, x2, y2] = this.#last.subarray(2, 6);
16787 this.#top.push(NaN, NaN, NaN, NaN, ((x1 + x2) / 2 - layerX) / layerWidth, ((y1 + y2) / 2 - layerY) / layerHeight);
16788 [x1, y1, x0, y0] = this.#last.subarray(14, 18);
16789 this.#bottom.push(NaN, NaN, NaN, NaN, ((x0 + x1) / 2 - layerX) / layerWidth, ((y0 + y1) / 2 - layerY) / layerHeight);
16790 return true;
16791 }
16792 [x0, y0, x1, y1, x2, y2] = this.#last.subarray(0, 6);
16793 this.#top.push(((x0 + 5 * x1) / 6 - layerX) / layerWidth, ((y0 + 5 * y1) / 6 - layerY) / layerHeight, ((5 * x1 + x2) / 6 - layerX) / layerWidth, ((5 * y1 + y2) / 6 - layerY) / layerHeight, ((x1 + x2) / 2 - layerX) / layerWidth, ((y1 + y2) / 2 - layerY) / layerHeight);
16794 [x2, y2, x1, y1, x0, y0] = this.#last.subarray(12, 18);
16795 this.#bottom.push(((x0 + 5 * x1) / 6 - layerX) / layerWidth, ((y0 + 5 * y1) / 6 - layerY) / layerHeight, ((5 * x1 + x2) / 6 - layerX) / layerWidth, ((5 * y1 + y2) / 6 - layerY) / layerHeight, ((x1 + x2) / 2 - layerX) / layerWidth, ((y1 + y2) / 2 - layerY) / layerHeight);
16796 return true;
16797 }
16798 toSVGPath() {
16799 if (this.isEmpty()) {
16800 return "";
16801 }
16802 const top = this.#top;
16803 const bottom = this.#bottom;
16804 const lastTop = this.#last.subarray(4, 6);
16805 const lastBottom = this.#last.subarray(16, 18);
16806 const [x, y, width, height] = this.#box;
16807 const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords();
16808 if (isNaN(this.#last[6]) && !this.isEmpty()) {
16809 return `M${(this.#last[2] - x) / width} ${(this.#last[3] - y) / height} L${(this.#last[4] - x) / width} ${(this.#last[5] - y) / height} L${lastTopX} ${lastTopY} L${lastBottomX} ${lastBottomY} L${(this.#last[16] - x) / width} ${(this.#last[17] - y) / height} L${(this.#last[14] - x) / width} ${(this.#last[15] - y) / height} Z`;
16810 }
16811 const buffer = [];
16812 buffer.push(`M${top[4]} ${top[5]}`);
16813 for (let i = 6; i < top.length; i += 6) {
16814 if (isNaN(top[i])) {
16815 buffer.push(`L${top[i + 4]} ${top[i + 5]}`);
16816 } else {
16817 buffer.push(`C${top[i]} ${top[i + 1]} ${top[i + 2]} ${top[i + 3]} ${top[i + 4]} ${top[i + 5]}`);
16818 }
16819 }
16820 buffer.push(`L${(lastTop[0] - x) / width} ${(lastTop[1] - y) / height} L${lastTopX} ${lastTopY} L${lastBottomX} ${lastBottomY} L${(lastBottom[0] - x) / width} ${(lastBottom[1] - y) / height}`);
16821 for (let i = bottom.length - 6; i >= 6; i -= 6) {
16822 if (isNaN(bottom[i])) {
16823 buffer.push(`L${bottom[i + 4]} ${bottom[i + 5]}`);
16824 } else {
16825 buffer.push(`C${bottom[i]} ${bottom[i + 1]} ${bottom[i + 2]} ${bottom[i + 3]} ${bottom[i + 4]} ${bottom[i + 5]}`);
16826 }
16827 }
16828 buffer.push(`L${bottom[4]} ${bottom[5]} Z`);
16829 return buffer.join(" ");
16830 }
16831 getOutlines() {
16832 const top = this.#top;
16833 const bottom = this.#bottom;
16834 const last = this.#last;
16835 const lastTop = last.subarray(4, 6);
16836 const lastBottom = last.subarray(16, 18);
16837 const [layerX, layerY, layerWidth, layerHeight] = this.#box;
16838 const points = new Float64Array((this.#points?.length ?? 0) + 2);
16839 for (let i = 0, ii = points.length - 2; i < ii; i += 2) {
16840 points[i] = (this.#points[i] - layerX) / layerWidth;
16841 points[i + 1] = (this.#points[i + 1] - layerY) / layerHeight;
16842 }
16843 points[points.length - 2] = (this.#lastX - layerX) / layerWidth;
16844 points[points.length - 1] = (this.#lastY - layerY) / layerHeight;
16845 const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords();
16846 if (isNaN(last[6]) && !this.isEmpty()) {
16847 const outline = new Float64Array(36);
16848 outline.set([NaN, NaN, NaN, NaN, (last[2] - layerX) / layerWidth, (last[3] - layerY) / layerHeight, NaN, NaN, NaN, NaN, (last[4] - layerX) / layerWidth, (last[5] - layerY) / layerHeight, NaN, NaN, NaN, NaN, lastTopX, lastTopY, NaN, NaN, NaN, NaN, lastBottomX, lastBottomY, NaN, NaN, NaN, NaN, (last[16] - layerX) / layerWidth, (last[17] - layerY) / layerHeight, NaN, NaN, NaN, NaN, (last[14] - layerX) / layerWidth, (last[15] - layerY) / layerHeight], 0);
16849 return new FreeHighlightOutline(outline, points, this.#box, this.#scaleFactor, this.#innerMargin, this.#isLTR);
16850 }
16851 const outline = new Float64Array(this.#top.length + 24 + this.#bottom.length);
16852 let N = top.length;
16853 for (let i = 0; i < N; i += 2) {
16854 if (isNaN(top[i])) {
16855 outline[i] = outline[i + 1] = NaN;
16856 continue;
16857 }
16858 outline[i] = top[i];
16859 outline[i + 1] = top[i + 1];
16860 }
16861 outline.set([NaN, NaN, NaN, NaN, (lastTop[0] - layerX) / layerWidth, (lastTop[1] - layerY) / layerHeight, NaN, NaN, NaN, NaN, lastTopX, lastTopY, NaN, NaN, NaN, NaN, lastBottomX, lastBottomY, NaN, NaN, NaN, NaN, (lastBottom[0] - layerX) / layerWidth, (lastBottom[1] - layerY) / layerHeight], N);
16862 N += 24;
16863 for (let i = bottom.length - 6; i >= 6; i -= 6) {
16864 for (let j = 0; j < 6; j += 2) {
16865 if (isNaN(bottom[i + j])) {
16866 outline[N] = outline[N + 1] = NaN;
16867 N += 2;
16868 continue;
16869 }
16870 outline[N] = bottom[i + j];
16871 outline[N + 1] = bottom[i + j + 1];
16872 N += 2;
16873 }
16874 }
16875 outline.set([NaN, NaN, NaN, NaN, bottom[4], bottom[5]], N);
16876 return new FreeHighlightOutline(outline, points, this.#box, this.#scaleFactor, this.#innerMargin, this.#isLTR);
16877 }
16878 }
16879 class FreeHighlightOutline extends Outline {
16880 #box;
16881 #bbox = null;
16882 #innerMargin;
16883 #isLTR;
16884 #points;
16885 #scaleFactor;
16886 #outline;
16887 constructor(outline, points, box, scaleFactor, innerMargin, isLTR) {
16888 super();
16889 this.#outline = outline;
16890 this.#points = points;
16891 this.#box = box;
16892 this.#scaleFactor = scaleFactor;
16893 this.#innerMargin = innerMargin;
16894 this.#isLTR = isLTR;
16895 this.#computeMinMax(isLTR);
16896 const {
16897 x,
16898 y,
16899 width,
16900 height
16901 } = this.#bbox;
16902 for (let i = 0, ii = outline.length; i < ii; i += 2) {
16903 outline[i] = (outline[i] - x) / width;
16904 outline[i + 1] = (outline[i + 1] - y) / height;
16905 }
16906 for (let i = 0, ii = points.length; i < ii; i += 2) {
16907 points[i] = (points[i] - x) / width;
16908 points[i + 1] = (points[i + 1] - y) / height;
16909 }
16910 }
16911 toSVGPath() {
16912 const buffer = [`M${this.#outline[4]} ${this.#outline[5]}`];
16913 for (let i = 6, ii = this.#outline.length; i < ii; i += 6) {
16914 if (isNaN(this.#outline[i])) {
16915 buffer.push(`L${this.#outline[i + 4]} ${this.#outline[i + 5]}`);
16916 continue;
16917 }
16918 buffer.push(`C${this.#outline[i]} ${this.#outline[i + 1]} ${this.#outline[i + 2]} ${this.#outline[i + 3]} ${this.#outline[i + 4]} ${this.#outline[i + 5]}`);
16919 }
16920 buffer.push("Z");
16921 return buffer.join(" ");
16922 }
16923 serialize([blX, blY, trX, trY], rotation) {
16924 const width = trX - blX;
16925 const height = trY - blY;
16926 let outline;
16927 let points;
16928 switch (rotation) {
16929 case 0:
16930 outline = this.#rescale(this.#outline, blX, trY, width, -height);
16931 points = this.#rescale(this.#points, blX, trY, width, -height);
16932 break;
16933 case 90:
16934 outline = this.#rescaleAndSwap(this.#outline, blX, blY, width, height);
16935 points = this.#rescaleAndSwap(this.#points, blX, blY, width, height);
16936 break;
16937 case 180:
16938 outline = this.#rescale(this.#outline, trX, blY, -width, height);
16939 points = this.#rescale(this.#points, trX, blY, -width, height);
16940 break;
16941 case 270:
16942 outline = this.#rescaleAndSwap(this.#outline, trX, trY, -width, -height);
16943 points = this.#rescaleAndSwap(this.#points, trX, trY, -width, -height);
16944 break;
16945 }
16946 return {
16947 outline: Array.from(outline),
16948 points: [Array.from(points)]
16949 };
16950 }
16951 #rescale(src, tx, ty, sx, sy) {
16952 const dest = new Float64Array(src.length);
16953 for (let i = 0, ii = src.length; i < ii; i += 2) {
16954 dest[i] = tx + src[i] * sx;
16955 dest[i + 1] = ty + src[i + 1] * sy;
16956 }
16957 return dest;
16958 }
16959 #rescaleAndSwap(src, tx, ty, sx, sy) {
16960 const dest = new Float64Array(src.length);
16961 for (let i = 0, ii = src.length; i < ii; i += 2) {
16962 dest[i] = tx + src[i + 1] * sx;
16963 dest[i + 1] = ty + src[i] * sy;
16964 }
16965 return dest;
16966 }
16967 #computeMinMax(isLTR) {
16968 const outline = this.#outline;
16969 let lastX = outline[4];
16970 let lastY = outline[5];
16971 let minX = lastX;
16972 let minY = lastY;
16973 let maxX = lastX;
16974 let maxY = lastY;
16975 let lastPointX = lastX;
16976 let lastPointY = lastY;
16977 const ltrCallback = isLTR ? Math.max : Math.min;
16978 for (let i = 6, ii = outline.length; i < ii; i += 6) {
16979 if (isNaN(outline[i])) {
16980 minX = Math.min(minX, outline[i + 4]);
16981 minY = Math.min(minY, outline[i + 5]);
16982 maxX = Math.max(maxX, outline[i + 4]);
16983 maxY = Math.max(maxY, outline[i + 5]);
16984 if (lastPointY < outline[i + 5]) {
16985 lastPointX = outline[i + 4];
16986 lastPointY = outline[i + 5];
16987 } else if (lastPointY === outline[i + 5]) {
16988 lastPointX = ltrCallback(lastPointX, outline[i + 4]);
16989 }
16990 } else {
16991 const bbox = Util.bezierBoundingBox(lastX, lastY, ...outline.slice(i, i + 6));
16992 minX = Math.min(minX, bbox[0]);
16993 minY = Math.min(minY, bbox[1]);
16994 maxX = Math.max(maxX, bbox[2]);
16995 maxY = Math.max(maxY, bbox[3]);
16996 if (lastPointY < bbox[3]) {
16997 lastPointX = bbox[2];
16998 lastPointY = bbox[3];
16999 } else if (lastPointY === bbox[3]) {
17000 lastPointX = ltrCallback(lastPointX, bbox[2]);
17001 }
17002 }
17003 lastX = outline[i + 4];
17004 lastY = outline[i + 5];
17005 }
17006 const x = minX - this.#innerMargin,
17007 y = minY - this.#innerMargin,
17008 width = maxX - minX + 2 * this.#innerMargin,
17009 height = maxY - minY + 2 * this.#innerMargin;
17010 this.#bbox = {
17011 x,
17012 y,
17013 width,
17014 height,
17015 lastPoint: [lastPointX, lastPointY]
17016 };
17017 }
17018 get box() {
17019 return this.#bbox;
17020 }
17021 getNewOutline(thickness, innerMargin) {
17022 const {
17023 x,
17024 y,
17025 width,
17026 height
17027 } = this.#bbox;
17028 const [layerX, layerY, layerWidth, layerHeight] = this.#box;
17029 const sx = width * layerWidth;
17030 const sy = height * layerHeight;
17031 const tx = x * layerWidth + layerX;
17032 const ty = y * layerHeight + layerY;
17033 const outliner = new FreeOutliner({
17034 x: this.#points[0] * sx + tx,
17035 y: this.#points[1] * sy + ty
17036 }, this.#box, this.#scaleFactor, thickness, this.#isLTR, innerMargin ?? this.#innerMargin);
17037 for (let i = 2; i < this.#points.length; i += 2) {
17038 outliner.add({
17039 x: this.#points[i] * sx + tx,
17040 y: this.#points[i + 1] * sy + ty
17041 });
17042 }
17043 return outliner.getOutlines();
17044 }
17045 }
17046
17047 ;// ./src/display/editor/color_picker.js
17048
17049
17050
17051 class ColorPicker {
17052 #boundKeyDown = this.#keyDown.bind(this);
17053 #boundPointerDown = this.#pointerDown.bind(this);
17054 #button = null;
17055 #buttonSwatch = null;
17056 #defaultColor;
17057 #dropdown = null;
17058 #dropdownWasFromKeyboard = false;
17059 #isMainColorPicker = false;
17060 #editor = null;
17061 #eventBus;
17062 #uiManager = null;
17063 #type;
17064 static #l10nColor = null;
17065 static get _keyboardManager() {
17066 return shadow(this, "_keyboardManager", new KeyboardManager([[["Escape", "mac+Escape"], ColorPicker.prototype._hideDropdownFromKeyboard], [[" ", "mac+ "], ColorPicker.prototype._colorSelectFromKeyboard], [["ArrowDown", "ArrowRight", "mac+ArrowDown", "mac+ArrowRight"], ColorPicker.prototype._moveToNext], [["ArrowUp", "ArrowLeft", "mac+ArrowUp", "mac+ArrowLeft"], ColorPicker.prototype._moveToPrevious], [["Home", "mac+Home"], ColorPicker.prototype._moveToBeginning], [["End", "mac+End"], ColorPicker.prototype._moveToEnd]]));
17067 }
17068 constructor({
17069 editor = null,
17070 uiManager = null
17071 }) {
17072 if (editor) {
17073 this.#isMainColorPicker = false;
17074 this.#type = AnnotationEditorParamsType.HIGHLIGHT_COLOR;
17075 this.#editor = editor;
17076 } else {
17077 this.#isMainColorPicker = true;
17078 this.#type = AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR;
17079 }
17080 this.#uiManager = editor?._uiManager || uiManager;
17081 this.#eventBus = this.#uiManager._eventBus;
17082 this.#defaultColor = editor?.color || this.#uiManager?.highlightColors.values().next().value || "#FFFF98";
17083 ColorPicker.#l10nColor ||= Object.freeze({
17084 blue: "pdfjs-editor-colorpicker-blue",
17085 green: "pdfjs-editor-colorpicker-green",
17086 pink: "pdfjs-editor-colorpicker-pink",
17087 red: "pdfjs-editor-colorpicker-red",
17088 yellow: "pdfjs-editor-colorpicker-yellow"
17089 });
17090 }
17091 renderButton() {
17092 const button = this.#button = document.createElement("button");
17093 button.className = "colorPicker";
17094 button.tabIndex = "0";
17095 button.setAttribute("data-l10n-id", "pdfjs-editor-colorpicker-button");
17096 button.setAttribute("aria-haspopup", true);
17097 const signal = this.#uiManager._signal;
17098 button.addEventListener("click", this.#openDropdown.bind(this), {
17099 signal
17100 });
17101 button.addEventListener("keydown", this.#boundKeyDown, {
17102 signal
17103 });
17104 const swatch = this.#buttonSwatch = document.createElement("span");
17105 swatch.className = "swatch";
17106 swatch.setAttribute("aria-hidden", true);
17107 swatch.style.backgroundColor = this.#defaultColor;
17108 button.append(swatch);
17109 return button;
17110 }
17111 renderMainDropdown() {
17112 const dropdown = this.#dropdown = this.#getDropdownRoot();
17113 dropdown.setAttribute("aria-orientation", "horizontal");
17114 dropdown.setAttribute("aria-labelledby", "highlightColorPickerLabel");
17115 return dropdown;
17116 }
17117 #getDropdownRoot() {
17118 const div = document.createElement("div");
17119 const signal = this.#uiManager._signal;
17120 div.addEventListener("contextmenu", noContextMenu, {
17121 signal
17122 });
17123 div.className = "dropdown";
17124 div.role = "listbox";
17125 div.setAttribute("aria-multiselectable", false);
17126 div.setAttribute("aria-orientation", "vertical");
17127 div.setAttribute("data-l10n-id", "pdfjs-editor-colorpicker-dropdown");
17128 for (const [name, color] of this.#uiManager.highlightColors) {
17129 const button = document.createElement("button");
17130 button.tabIndex = "0";
17131 button.role = "option";
17132 button.setAttribute("data-color", color);
17133 button.title = name;
17134 button.setAttribute("data-l10n-id", ColorPicker.#l10nColor[name]);
17135 const swatch = document.createElement("span");
17136 button.append(swatch);
17137 swatch.className = "swatch";
17138 swatch.style.backgroundColor = color;
17139 button.setAttribute("aria-selected", color === this.#defaultColor);
17140 button.addEventListener("click", this.#colorSelect.bind(this, color), {
17141 signal
17142 });
17143 div.append(button);
17144 }
17145 div.addEventListener("keydown", this.#boundKeyDown, {
17146 signal
17147 });
17148 return div;
17149 }
17150 #colorSelect(color, event) {
17151 event.stopPropagation();
17152 this.#eventBus.dispatch("switchannotationeditorparams", {
17153 source: this,
17154 type: this.#type,
17155 value: color
17156 });
17157 }
17158 _colorSelectFromKeyboard(event) {
17159 if (event.target === this.#button) {
17160 this.#openDropdown(event);
17161 return;
17162 }
17163 const color = event.target.getAttribute("data-color");
17164 if (!color) {
17165 return;
17166 }
17167 this.#colorSelect(color, event);
17168 }
17169 _moveToNext(event) {
17170 if (!this.#isDropdownVisible) {
17171 this.#openDropdown(event);
17172 return;
17173 }
17174 if (event.target === this.#button) {
17175 this.#dropdown.firstChild?.focus();
17176 return;
17177 }
17178 event.target.nextSibling?.focus();
17179 }
17180 _moveToPrevious(event) {
17181 if (event.target === this.#dropdown?.firstChild || event.target === this.#button) {
17182 if (this.#isDropdownVisible) {
17183 this._hideDropdownFromKeyboard();
17184 }
17185 return;
17186 }
17187 if (!this.#isDropdownVisible) {
17188 this.#openDropdown(event);
17189 }
17190 event.target.previousSibling?.focus();
17191 }
17192 _moveToBeginning(event) {
17193 if (!this.#isDropdownVisible) {
17194 this.#openDropdown(event);
17195 return;
17196 }
17197 this.#dropdown.firstChild?.focus();
17198 }
17199 _moveToEnd(event) {
17200 if (!this.#isDropdownVisible) {
17201 this.#openDropdown(event);
17202 return;
17203 }
17204 this.#dropdown.lastChild?.focus();
17205 }
17206 #keyDown(event) {
17207 ColorPicker._keyboardManager.exec(this, event);
17208 }
17209 #openDropdown(event) {
17210 if (this.#isDropdownVisible) {
17211 this.hideDropdown();
17212 return;
17213 }
17214 this.#dropdownWasFromKeyboard = event.detail === 0;
17215 window.addEventListener("pointerdown", this.#boundPointerDown, {
17216 signal: this.#uiManager._signal
17217 });
17218 if (this.#dropdown) {
17219 this.#dropdown.classList.remove("hidden");
17220 return;
17221 }
17222 const root = this.#dropdown = this.#getDropdownRoot();
17223 this.#button.append(root);
17224 }
17225 #pointerDown(event) {
17226 if (this.#dropdown?.contains(event.target)) {
17227 return;
17228 }
17229 this.hideDropdown();
17230 }
17231 hideDropdown() {
17232 this.#dropdown?.classList.add("hidden");
17233 window.removeEventListener("pointerdown", this.#boundPointerDown);
17234 }
17235 get #isDropdownVisible() {
17236 return this.#dropdown && !this.#dropdown.classList.contains("hidden");
17237 }
17238 _hideDropdownFromKeyboard() {
17239 if (this.#isMainColorPicker) {
17240 return;
17241 }
17242 if (!this.#isDropdownVisible) {
17243 this.#editor?.unselect();
17244 return;
17245 }
17246 this.hideDropdown();
17247 this.#button.focus({
17248 preventScroll: true,
17249 focusVisible: this.#dropdownWasFromKeyboard
17250 });
17251 }
17252 updateColor(color) {
17253 if (this.#buttonSwatch) {
17254 this.#buttonSwatch.style.backgroundColor = color;
17255 }
17256 if (!this.#dropdown) {
17257 return;
17258 }
17259 const i = this.#uiManager.highlightColors.values();
17260 for (const child of this.#dropdown.children) {
17261 child.setAttribute("aria-selected", i.next().value === color);
17262 }
17263 }
17264 destroy() {
17265 this.#button?.remove();
17266 this.#button = null;
17267 this.#buttonSwatch = null;
17268 this.#dropdown?.remove();
17269 this.#dropdown = null;
17270 }
17271 }
17272
17273 ;// ./src/display/editor/highlight.js
17274
17275
17276
17277
17278
17279
17280
17281 class HighlightEditor extends AnnotationEditor {
17282 #anchorNode = null;
17283 #anchorOffset = 0;
17284 #boxes;
17285 #clipPathId = null;
17286 #colorPicker = null;
17287 #focusOutlines = null;
17288 #focusNode = null;
17289 #focusOffset = 0;
17290 #highlightDiv = null;
17291 #highlightOutlines = null;
17292 #id = null;
17293 #isFreeHighlight = false;
17294 #lastPoint = null;
17295 #opacity;
17296 #outlineId = null;
17297 #text = "";
17298 #thickness;
17299 #methodOfCreation = "";
17300 static _defaultColor = null;
17301 static _defaultOpacity = 1;
17302 static _defaultThickness = 12;
17303 static _type = "highlight";
17304 static _editorType = AnnotationEditorType.HIGHLIGHT;
17305 static _freeHighlightId = -1;
17306 static _freeHighlight = null;
17307 static _freeHighlightClipId = "";
17308 static get _keyboardManager() {
17309 const proto = HighlightEditor.prototype;
17310 return shadow(this, "_keyboardManager", new KeyboardManager([[["ArrowLeft", "mac+ArrowLeft"], proto._moveCaret, {
17311 args: [0]
17312 }], [["ArrowRight", "mac+ArrowRight"], proto._moveCaret, {
17313 args: [1]
17314 }], [["ArrowUp", "mac+ArrowUp"], proto._moveCaret, {
17315 args: [2]
17316 }], [["ArrowDown", "mac+ArrowDown"], proto._moveCaret, {
17317 args: [3]
17318 }]]));
17319 }
17320 constructor(params) {
17321 super({
17322 ...params,
17323 name: "highlightEditor"
17324 });
17325 this.color = params.color || HighlightEditor._defaultColor;
17326 this.#thickness = params.thickness || HighlightEditor._defaultThickness;
17327 this.#opacity = params.opacity || HighlightEditor._defaultOpacity;
17328 this.#boxes = params.boxes || null;
17329 this.#methodOfCreation = params.methodOfCreation || "";
17330 this.#text = params.text || "";
17331 this._isDraggable = false;
17332 if (params.highlightId > -1) {
17333 this.#isFreeHighlight = true;
17334 this.#createFreeOutlines(params);
17335 this.#addToDrawLayer();
17336 } else if (this.#boxes) {
17337 this.#anchorNode = params.anchorNode;
17338 this.#anchorOffset = params.anchorOffset;
17339 this.#focusNode = params.focusNode;
17340 this.#focusOffset = params.focusOffset;
17341 this.#createOutlines();
17342 this.#addToDrawLayer();
17343 this.rotate(this.rotation);
17344 }
17345 }
17346 get telemetryInitialData() {
17347 return {
17348 action: "added",
17349 type: this.#isFreeHighlight ? "free_highlight" : "highlight",
17350 color: this._uiManager.highlightColorNames.get(this.color),
17351 thickness: this.#thickness,
17352 methodOfCreation: this.#methodOfCreation
17353 };
17354 }
17355 get telemetryFinalData() {
17356 return {
17357 type: "highlight",
17358 color: this._uiManager.highlightColorNames.get(this.color)
17359 };
17360 }
17361 static computeTelemetryFinalData(data) {
17362 return {
17363 numberOfColors: data.get("color").size
17364 };
17365 }
17366 #createOutlines() {
17367 const outliner = new Outliner(this.#boxes, 0.001);
17368 this.#highlightOutlines = outliner.getOutlines();
17369 ({
17370 x: this.x,
17371 y: this.y,
17372 width: this.width,
17373 height: this.height
17374 } = this.#highlightOutlines.box);
17375 const outlinerForOutline = new Outliner(this.#boxes, 0.0025, 0.001, this._uiManager.direction === "ltr");
17376 this.#focusOutlines = outlinerForOutline.getOutlines();
17377 const {
17378 lastPoint
17379 } = this.#focusOutlines.box;
17380 this.#lastPoint = [(lastPoint[0] - this.x) / this.width, (lastPoint[1] - this.y) / this.height];
17381 }
17382 #createFreeOutlines({
17383 highlightOutlines,
17384 highlightId,
17385 clipPathId
17386 }) {
17387 this.#highlightOutlines = highlightOutlines;
17388 const extraThickness = 1.5;
17389 this.#focusOutlines = highlightOutlines.getNewOutline(this.#thickness / 2 + extraThickness, 0.0025);
17390 if (highlightId >= 0) {
17391 this.#id = highlightId;
17392 this.#clipPathId = clipPathId;
17393 this.parent.drawLayer.finalizeLine(highlightId, highlightOutlines);
17394 this.#outlineId = this.parent.drawLayer.highlightOutline(this.#focusOutlines);
17395 } else if (this.parent) {
17396 const angle = this.parent.viewport.rotation;
17397 this.parent.drawLayer.updateLine(this.#id, highlightOutlines);
17398 this.parent.drawLayer.updateBox(this.#id, HighlightEditor.#rotateBbox(this.#highlightOutlines.box, (angle - this.rotation + 360) % 360));
17399 this.parent.drawLayer.updateLine(this.#outlineId, this.#focusOutlines);
17400 this.parent.drawLayer.updateBox(this.#outlineId, HighlightEditor.#rotateBbox(this.#focusOutlines.box, angle));
17401 }
17402 const {
17403 x,
17404 y,
17405 width,
17406 height
17407 } = highlightOutlines.box;
17408 switch (this.rotation) {
17409 case 0:
17410 this.x = x;
17411 this.y = y;
17412 this.width = width;
17413 this.height = height;
17414 break;
17415 case 90:
17416 {
17417 const [pageWidth, pageHeight] = this.parentDimensions;
17418 this.x = y;
17419 this.y = 1 - x;
17420 this.width = width * pageHeight / pageWidth;
17421 this.height = height * pageWidth / pageHeight;
17422 break;
17423 }
17424 case 180:
17425 this.x = 1 - x;
17426 this.y = 1 - y;
17427 this.width = width;
17428 this.height = height;
17429 break;
17430 case 270:
17431 {
17432 const [pageWidth, pageHeight] = this.parentDimensions;
17433 this.x = 1 - y;
17434 this.y = x;
17435 this.width = width * pageHeight / pageWidth;
17436 this.height = height * pageWidth / pageHeight;
17437 break;
17438 }
17439 }
17440 const {
17441 lastPoint
17442 } = this.#focusOutlines.box;
17443 this.#lastPoint = [(lastPoint[0] - x) / width, (lastPoint[1] - y) / height];
17444 }
17445 static initialize(l10n, uiManager) {
17446 AnnotationEditor.initialize(l10n, uiManager);
17447 HighlightEditor._defaultColor ||= uiManager.highlightColors?.values().next().value || "#fff066";
17448 }
17449 static updateDefaultParams(type, value) {
17450 switch (type) {
17451 case AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR:
17452 HighlightEditor._defaultColor = value;
17453 break;
17454 case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:
17455 HighlightEditor._defaultThickness = value;
17456 break;
17457 }
17458 }
17459 translateInPage(x, y) {}
17460 get toolbarPosition() {
17461 return this.#lastPoint;
17462 }
17463 updateParams(type, value) {
17464 switch (type) {
17465 case AnnotationEditorParamsType.HIGHLIGHT_COLOR:
17466 this.#updateColor(value);
17467 break;
17468 case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:
17469 this.#updateThickness(value);
17470 break;
17471 }
17472 }
17473 static get defaultPropertiesToUpdate() {
17474 return [[AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR, HighlightEditor._defaultColor], [AnnotationEditorParamsType.HIGHLIGHT_THICKNESS, HighlightEditor._defaultThickness]];
17475 }
17476 get propertiesToUpdate() {
17477 return [[AnnotationEditorParamsType.HIGHLIGHT_COLOR, this.color || HighlightEditor._defaultColor], [AnnotationEditorParamsType.HIGHLIGHT_THICKNESS, this.#thickness || HighlightEditor._defaultThickness], [AnnotationEditorParamsType.HIGHLIGHT_FREE, this.#isFreeHighlight]];
17478 }
17479 #updateColor(color) {
17480 const setColorAndOpacity = (col, opa) => {
17481 this.color = col;
17482 this.parent?.drawLayer.changeColor(this.#id, col);
17483 this.#colorPicker?.updateColor(col);
17484 this.#opacity = opa;
17485 this.parent?.drawLayer.changeOpacity(this.#id, opa);
17486 };
17487 const savedColor = this.color;
17488 const savedOpacity = this.#opacity;
17489 this.addCommands({
17490 cmd: setColorAndOpacity.bind(this, color, HighlightEditor._defaultOpacity),
17491 undo: setColorAndOpacity.bind(this, savedColor, savedOpacity),
17492 post: this._uiManager.updateUI.bind(this._uiManager, this),
17493 mustExec: true,
17494 type: AnnotationEditorParamsType.HIGHLIGHT_COLOR,
17495 overwriteIfSameType: true,
17496 keepUndo: true
17497 });
17498 this._reportTelemetry({
17499 action: "color_changed",
17500 color: this._uiManager.highlightColorNames.get(color)
17501 }, true);
17502 }
17503 #updateThickness(thickness) {
17504 const savedThickness = this.#thickness;
17505 const setThickness = th => {
17506 this.#thickness = th;
17507 this.#changeThickness(th);
17508 };
17509 this.addCommands({
17510 cmd: setThickness.bind(this, thickness),
17511 undo: setThickness.bind(this, savedThickness),
17512 post: this._uiManager.updateUI.bind(this._uiManager, this),
17513 mustExec: true,
17514 type: AnnotationEditorParamsType.INK_THICKNESS,
17515 overwriteIfSameType: true,
17516 keepUndo: true
17517 });
17518 this._reportTelemetry({
17519 action: "thickness_changed",
17520 thickness
17521 }, true);
17522 }
17523 async addEditToolbar() {
17524 const toolbar = await super.addEditToolbar();
17525 if (!toolbar) {
17526 return null;
17527 }
17528 if (this._uiManager.highlightColors) {
17529 this.#colorPicker = new ColorPicker({
17530 editor: this
17531 });
17532 toolbar.addColorPicker(this.#colorPicker);
17533 }
17534 return toolbar;
17535 }
17536 disableEditing() {
17537 super.disableEditing();
17538 this.div.classList.toggle("disabled", true);
17539 }
17540 enableEditing() {
17541 super.enableEditing();
17542 this.div.classList.toggle("disabled", false);
17543 }
17544 fixAndSetPosition() {
17545 return super.fixAndSetPosition(this.#getRotation());
17546 }
17547 getBaseTranslation() {
17548 return [0, 0];
17549 }
17550 getRect(tx, ty) {
17551 return super.getRect(tx, ty, this.#getRotation());
17552 }
17553 onceAdded() {
17554 if (!this.annotationElementId) {
17555 this.parent.addUndoableEditor(this);
17556 }
17557 this.div.focus();
17558 }
17559 remove() {
17560 this.#cleanDrawLayer();
17561 this._reportTelemetry({
17562 action: "deleted"
17563 });
17564 super.remove();
17565 }
17566 rebuild() {
17567 if (!this.parent) {
17568 return;
17569 }
17570 super.rebuild();
17571 if (this.div === null) {
17572 return;
17573 }
17574 this.#addToDrawLayer();
17575 if (!this.isAttachedToDOM) {
17576 this.parent.add(this);
17577 }
17578 }
17579 setParent(parent) {
17580 let mustBeSelected = false;
17581 if (this.parent && !parent) {
17582 this.#cleanDrawLayer();
17583 } else if (parent) {
17584 this.#addToDrawLayer(parent);
17585 mustBeSelected = !this.parent && this.div?.classList.contains("selectedEditor");
17586 }
17587 super.setParent(parent);
17588 this.show(this._isVisible);
17589 if (mustBeSelected) {
17590 this.select();
17591 }
17592 }
17593 #changeThickness(thickness) {
17594 if (!this.#isFreeHighlight) {
17595 return;
17596 }
17597 this.#createFreeOutlines({
17598 highlightOutlines: this.#highlightOutlines.getNewOutline(thickness / 2)
17599 });
17600 this.fixAndSetPosition();
17601 const [parentWidth, parentHeight] = this.parentDimensions;
17602 this.setDims(this.width * parentWidth, this.height * parentHeight);
17603 }
17604 #cleanDrawLayer() {
17605 if (this.#id === null || !this.parent) {
17606 return;
17607 }
17608 this.parent.drawLayer.remove(this.#id);
17609 this.#id = null;
17610 this.parent.drawLayer.remove(this.#outlineId);
17611 this.#outlineId = null;
17612 }
17613 #addToDrawLayer(parent = this.parent) {
17614 if (this.#id !== null) {
17615 return;
17616 }
17617 ({
17618 id: this.#id,
17619 clipPathId: this.#clipPathId
17620 } = parent.drawLayer.highlight(this.#highlightOutlines, this.color, this.#opacity));
17621 this.#outlineId = parent.drawLayer.highlightOutline(this.#focusOutlines);
17622 if (this.#highlightDiv) {
17623 this.#highlightDiv.style.clipPath = this.#clipPathId;
17624 }
17625 }
17626 static #rotateBbox({
17627 x,
17628 y,
17629 width,
17630 height
17631 }, angle) {
17632 switch (angle) {
17633 case 90:
17634 return {
17635 x: 1 - y - height,
17636 y: x,
17637 width: height,
17638 height: width
17639 };
17640 case 180:
17641 return {
17642 x: 1 - x - width,
17643 y: 1 - y - height,
17644 width,
17645 height
17646 };
17647 case 270:
17648 return {
17649 x: y,
17650 y: 1 - x - width,
17651 width: height,
17652 height: width
17653 };
17654 }
17655 return {
17656 x,
17657 y,
17658 width,
17659 height
17660 };
17661 }
17662 rotate(angle) {
17663 const {
17664 drawLayer
17665 } = this.parent;
17666 let box;
17667 if (this.#isFreeHighlight) {
17668 angle = (angle - this.rotation + 360) % 360;
17669 box = HighlightEditor.#rotateBbox(this.#highlightOutlines.box, angle);
17670 } else {
17671 box = HighlightEditor.#rotateBbox(this, angle);
17672 }
17673 drawLayer.rotate(this.#id, angle);
17674 drawLayer.rotate(this.#outlineId, angle);
17675 drawLayer.updateBox(this.#id, box);
17676 drawLayer.updateBox(this.#outlineId, HighlightEditor.#rotateBbox(this.#focusOutlines.box, angle));
17677 }
17678 render() {
17679 if (this.div) {
17680 return this.div;
17681 }
17682 const div = super.render();
17683 if (this.#text) {
17684 div.setAttribute("aria-label", this.#text);
17685 div.setAttribute("role", "mark");
17686 }
17687 if (this.#isFreeHighlight) {
17688 div.classList.add("free");
17689 } else {
17690 this.div.addEventListener("keydown", this.#keydown.bind(this), {
17691 signal: this._uiManager._signal
17692 });
17693 }
17694 const highlightDiv = this.#highlightDiv = document.createElement("div");
17695 div.append(highlightDiv);
17696 highlightDiv.setAttribute("aria-hidden", "true");
17697 highlightDiv.className = "internal";
17698 highlightDiv.style.clipPath = this.#clipPathId;
17699 const [parentWidth, parentHeight] = this.parentDimensions;
17700 this.setDims(this.width * parentWidth, this.height * parentHeight);
17701 bindEvents(this, this.#highlightDiv, ["pointerover", "pointerleave"]);
17702 this.enableEditing();
17703 return div;
17704 }
17705 pointerover() {
17706 this.parent.drawLayer.addClass(this.#outlineId, "hovered");
17707 }
17708 pointerleave() {
17709 this.parent.drawLayer.removeClass(this.#outlineId, "hovered");
17710 }
17711 #keydown(event) {
17712 HighlightEditor._keyboardManager.exec(this, event);
17713 }
17714 _moveCaret(direction) {
17715 this.parent.unselect(this);
17716 switch (direction) {
17717 case 0:
17718 case 2:
17719 this.#setCaret(true);
17720 break;
17721 case 1:
17722 case 3:
17723 this.#setCaret(false);
17724 break;
17725 }
17726 }
17727 #setCaret(start) {
17728 if (!this.#anchorNode) {
17729 return;
17730 }
17731 const selection = window.getSelection();
17732 if (start) {
17733 selection.setPosition(this.#anchorNode, this.#anchorOffset);
17734 } else {
17735 selection.setPosition(this.#focusNode, this.#focusOffset);
17736 }
17737 }
17738 select() {
17739 super.select();
17740 if (!this.#outlineId) {
17741 return;
17742 }
17743 this.parent?.drawLayer.removeClass(this.#outlineId, "hovered");
17744 this.parent?.drawLayer.addClass(this.#outlineId, "selected");
17745 }
17746 unselect() {
17747 super.unselect();
17748 if (!this.#outlineId) {
17749 return;
17750 }
17751 this.parent?.drawLayer.removeClass(this.#outlineId, "selected");
17752 if (!this.#isFreeHighlight) {
17753 this.#setCaret(false);
17754 }
17755 }
17756 get _mustFixPosition() {
17757 return !this.#isFreeHighlight;
17758 }
17759 show(visible = this._isVisible) {
17760 super.show(visible);
17761 if (this.parent) {
17762 this.parent.drawLayer.show(this.#id, visible);
17763 this.parent.drawLayer.show(this.#outlineId, visible);
17764 }
17765 }
17766 #getRotation() {
17767 return this.#isFreeHighlight ? this.rotation : 0;
17768 }
17769 #serializeBoxes() {
17770 if (this.#isFreeHighlight) {
17771 return null;
17772 }
17773 const [pageWidth, pageHeight] = this.pageDimensions;
17774 const [pageX, pageY] = this.pageTranslation;
17775 const boxes = this.#boxes;
17776 const quadPoints = new Float32Array(boxes.length * 8);
17777 let i = 0;
17778 for (const {
17779 x,
17780 y,
17781 width,
17782 height
17783 } of boxes) {
17784 const sx = x * pageWidth + pageX;
17785 const sy = (1 - y - height) * pageHeight + pageY;
17786 quadPoints[i] = quadPoints[i + 4] = sx;
17787 quadPoints[i + 1] = quadPoints[i + 3] = sy;
17788 quadPoints[i + 2] = quadPoints[i + 6] = sx + width * pageWidth;
17789 quadPoints[i + 5] = quadPoints[i + 7] = sy + height * pageHeight;
17790 i += 8;
17791 }
17792 return quadPoints;
17793 }
17794 #serializeOutlines(rect) {
17795 return this.#highlightOutlines.serialize(rect, this.#getRotation());
17796 }
17797 static startHighlighting(parent, isLTR, {
17798 target: textLayer,
17799 x,
17800 y
17801 }) {
17802 const {
17803 x: layerX,
17804 y: layerY,
17805 width: parentWidth,
17806 height: parentHeight
17807 } = textLayer.getBoundingClientRect();
17808 const ac = new AbortController();
17809 const signal = parent.combinedSignal(ac);
17810 const pointerDown = e => {
17811 e.preventDefault();
17812 e.stopPropagation();
17813 };
17814 const pointerUpCallback = e => {
17815 ac.abort();
17816 this.#endHighlight(parent, e);
17817 };
17818 window.addEventListener("blur", pointerUpCallback, {
17819 signal
17820 });
17821 window.addEventListener("pointerup", pointerUpCallback, {
17822 signal
17823 });
17824 window.addEventListener("pointerdown", pointerDown, {
17825 capture: true,
17826 passive: false,
17827 signal
17828 });
17829 window.addEventListener("contextmenu", noContextMenu, {
17830 signal
17831 });
17832 textLayer.addEventListener("pointermove", this.#highlightMove.bind(this, parent), {
17833 signal
17834 });
17835 this._freeHighlight = new FreeOutliner({
17836 x,
17837 y
17838 }, [layerX, layerY, parentWidth, parentHeight], parent.scale, this._defaultThickness / 2, isLTR, 0.001);
17839 ({
17840 id: this._freeHighlightId,
17841 clipPathId: this._freeHighlightClipId
17842 } = parent.drawLayer.highlight(this._freeHighlight, this._defaultColor, this._defaultOpacity, true));
17843 }
17844 static #highlightMove(parent, event) {
17845 if (this._freeHighlight.add(event)) {
17846 parent.drawLayer.updatePath(this._freeHighlightId, this._freeHighlight);
17847 }
17848 }
17849 static #endHighlight(parent, event) {
17850 if (!this._freeHighlight.isEmpty()) {
17851 parent.createAndAddNewEditor(event, false, {
17852 highlightId: this._freeHighlightId,
17853 highlightOutlines: this._freeHighlight.getOutlines(),
17854 clipPathId: this._freeHighlightClipId,
17855 methodOfCreation: "main_toolbar"
17856 });
17857 } else {
17858 parent.drawLayer.removeFreeHighlight(this._freeHighlightId);
17859 }
17860 this._freeHighlightId = -1;
17861 this._freeHighlight = null;
17862 this._freeHighlightClipId = "";
17863 }
17864 static async deserialize(data, parent, uiManager) {
17865 let initialData = null;
17866 if (data instanceof HighlightAnnotationElement) {
17867 const {
17868 data: {
17869 quadPoints,
17870 rect,
17871 rotation,
17872 id,
17873 color,
17874 opacity,
17875 popupRef
17876 },
17877 parent: {
17878 page: {
17879 pageNumber
17880 }
17881 }
17882 } = data;
17883 initialData = data = {
17884 annotationType: AnnotationEditorType.HIGHLIGHT,
17885 color: Array.from(color),
17886 opacity,
17887 quadPoints,
17888 boxes: null,
17889 pageIndex: pageNumber - 1,
17890 rect: rect.slice(0),
17891 rotation,
17892 id,
17893 deleted: false,
17894 popupRef
17895 };
17896 } else if (data instanceof InkAnnotationElement) {
17897 const {
17898 data: {
17899 inkLists,
17900 rect,
17901 rotation,
17902 id,
17903 color,
17904 borderStyle: {
17905 rawWidth: thickness
17906 },
17907 popupRef
17908 },
17909 parent: {
17910 page: {
17911 pageNumber
17912 }
17913 }
17914 } = data;
17915 initialData = data = {
17916 annotationType: AnnotationEditorType.HIGHLIGHT,
17917 color: Array.from(color),
17918 thickness,
17919 inkLists,
17920 boxes: null,
17921 pageIndex: pageNumber - 1,
17922 rect: rect.slice(0),
17923 rotation,
17924 id,
17925 deleted: false,
17926 popupRef
17927 };
17928 }
17929 const {
17930 color,
17931 quadPoints,
17932 inkLists,
17933 opacity
17934 } = data;
17935 const editor = await super.deserialize(data, parent, uiManager);
17936 editor.color = Util.makeHexColor(...color);
17937 editor.#opacity = opacity || 1;
17938 if (inkLists) {
17939 editor.#thickness = data.thickness;
17940 }
17941 editor.annotationElementId = data.id || null;
17942 editor._initialData = initialData;
17943 const [pageWidth, pageHeight] = editor.pageDimensions;
17944 const [pageX, pageY] = editor.pageTranslation;
17945 if (quadPoints) {
17946 const boxes = editor.#boxes = [];
17947 for (let i = 0; i < quadPoints.length; i += 8) {
17948 boxes.push({
17949 x: (quadPoints[i] - pageX) / pageWidth,
17950 y: 1 - (quadPoints[i + 1] - pageY) / pageHeight,
17951 width: (quadPoints[i + 2] - quadPoints[i]) / pageWidth,
17952 height: (quadPoints[i + 1] - quadPoints[i + 5]) / pageHeight
17953 });
17954 }
17955 editor.#createOutlines();
17956 editor.#addToDrawLayer();
17957 editor.rotate(editor.rotation);
17958 } else if (inkLists) {
17959 editor.#isFreeHighlight = true;
17960 const points = inkLists[0];
17961 const point = {
17962 x: points[0] - pageX,
17963 y: pageHeight - (points[1] - pageY)
17964 };
17965 const outliner = new FreeOutliner(point, [0, 0, pageWidth, pageHeight], 1, editor.#thickness / 2, true, 0.001);
17966 for (let i = 0, ii = points.length; i < ii; i += 2) {
17967 point.x = points[i] - pageX;
17968 point.y = pageHeight - (points[i + 1] - pageY);
17969 outliner.add(point);
17970 }
17971 const {
17972 id,
17973 clipPathId
17974 } = parent.drawLayer.highlight(outliner, editor.color, editor._defaultOpacity, true);
17975 editor.#createFreeOutlines({
17976 highlightOutlines: outliner.getOutlines(),
17977 highlightId: id,
17978 clipPathId
17979 });
17980 editor.#addToDrawLayer();
17981 }
17982 return editor;
17983 }
17984 serialize(isForCopying = false) {
17985 if (this.isEmpty() || isForCopying) {
17986 return null;
17987 }
17988 if (this.deleted) {
17989 return this.serializeDeleted();
17990 }
17991 const rect = this.getRect(0, 0);
17992 const color = AnnotationEditor._colorManager.convert(this.color);
17993 const serialized = {
17994 annotationType: AnnotationEditorType.HIGHLIGHT,
17995 color,
17996 opacity: this.#opacity,
17997 thickness: this.#thickness,
17998 quadPoints: this.#serializeBoxes(),
17999 outlines: this.#serializeOutlines(rect),
18000 pageIndex: this.pageIndex,
18001 rect,
18002 rotation: this.#getRotation(),
18003 structTreeParentId: this._structTreeParentId
18004 };
18005 if (this.annotationElementId && !this.#hasElementChanged(serialized)) {
18006 return null;
18007 }
18008 serialized.id = this.annotationElementId;
18009 return serialized;
18010 }
18011 #hasElementChanged(serialized) {
18012 const {
18013 color
18014 } = this._initialData;
18015 return serialized.color.some((c, i) => c !== color[i]);
18016 }
18017 renderAnnotationElement(annotation) {
18018 annotation.updateEdited({
18019 rect: this.getRect(0, 0)
18020 });
18021 return null;
18022 }
18023 static canCreateNewEmptyEditor() {
18024 return false;
18025 }
18026 }
18027
18028 ;// ./src/display/editor/ink.js
18029
18030
18031
18032
18033
18034 class InkEditor extends AnnotationEditor {
18035 #baseHeight = 0;
18036 #baseWidth = 0;
18037 #canvasContextMenuTimeoutId = null;
18038 #currentPath2D = new Path2D();
18039 #disableEditing = false;
18040 #drawingAC = null;
18041 #hasSomethingToDraw = false;
18042 #isCanvasInitialized = false;
18043 #observer = null;
18044 #pointerdownAC = null;
18045 #realWidth = 0;
18046 #realHeight = 0;
18047 #requestFrameCallback = null;
18048 static _defaultColor = null;
18049 static _defaultOpacity = 1;
18050 static _defaultThickness = 1;
18051 static _type = "ink";
18052 static _editorType = AnnotationEditorType.INK;
18053 constructor(params) {
18054 super({
18055 ...params,
18056 name: "inkEditor"
18057 });
18058 this.color = params.color || null;
18059 this.thickness = params.thickness || null;
18060 this.opacity = params.opacity || null;
18061 this.paths = [];
18062 this.bezierPath2D = [];
18063 this.allRawPaths = [];
18064 this.currentPath = [];
18065 this.scaleFactor = 1;
18066 this.translationX = this.translationY = 0;
18067 this.x = 0;
18068 this.y = 0;
18069 this._willKeepAspectRatio = true;
18070 }
18071 static initialize(l10n, uiManager) {
18072 AnnotationEditor.initialize(l10n, uiManager);
18073 }
18074 static updateDefaultParams(type, value) {
18075 switch (type) {
18076 case AnnotationEditorParamsType.INK_THICKNESS:
18077 InkEditor._defaultThickness = value;
18078 break;
18079 case AnnotationEditorParamsType.INK_COLOR:
18080 InkEditor._defaultColor = value;
18081 break;
18082 case AnnotationEditorParamsType.INK_OPACITY:
18083 InkEditor._defaultOpacity = value / 100;
18084 break;
18085 }
18086 }
18087 updateParams(type, value) {
18088 switch (type) {
18089 case AnnotationEditorParamsType.INK_THICKNESS:
18090 this.#updateThickness(value);
18091 break;
18092 case AnnotationEditorParamsType.INK_COLOR:
18093 this.#updateColor(value);
18094 break;
18095 case AnnotationEditorParamsType.INK_OPACITY:
18096 this.#updateOpacity(value);
18097 break;
18098 }
18099 }
18100 static get defaultPropertiesToUpdate() {
18101 return [[AnnotationEditorParamsType.INK_THICKNESS, InkEditor._defaultThickness], [AnnotationEditorParamsType.INK_COLOR, InkEditor._defaultColor || AnnotationEditor._defaultLineColor], [AnnotationEditorParamsType.INK_OPACITY, Math.round(InkEditor._defaultOpacity * 100)]];
18102 }
18103 get propertiesToUpdate() {
18104 return [[AnnotationEditorParamsType.INK_THICKNESS, this.thickness || InkEditor._defaultThickness], [AnnotationEditorParamsType.INK_COLOR, this.color || InkEditor._defaultColor || AnnotationEditor._defaultLineColor], [AnnotationEditorParamsType.INK_OPACITY, Math.round(100 * (this.opacity ?? InkEditor._defaultOpacity))]];
18105 }
18106 #updateThickness(thickness) {
18107 const setThickness = th => {
18108 this.thickness = th;
18109 this.#fitToContent();
18110 };
18111 const savedThickness = this.thickness;
18112 this.addCommands({
18113 cmd: setThickness.bind(this, thickness),
18114 undo: setThickness.bind(this, savedThickness),
18115 post: this._uiManager.updateUI.bind(this._uiManager, this),
18116 mustExec: true,
18117 type: AnnotationEditorParamsType.INK_THICKNESS,
18118 overwriteIfSameType: true,
18119 keepUndo: true
18120 });
18121 }
18122 #updateColor(color) {
18123 const setColor = col => {
18124 this.color = col;
18125 this.#redraw();
18126 };
18127 const savedColor = this.color;
18128 this.addCommands({
18129 cmd: setColor.bind(this, color),
18130 undo: setColor.bind(this, savedColor),
18131 post: this._uiManager.updateUI.bind(this._uiManager, this),
18132 mustExec: true,
18133 type: AnnotationEditorParamsType.INK_COLOR,
18134 overwriteIfSameType: true,
18135 keepUndo: true
18136 });
18137 }
18138 #updateOpacity(opacity) {
18139 const setOpacity = op => {
18140 this.opacity = op;
18141 this.#redraw();
18142 };
18143 opacity /= 100;
18144 const savedOpacity = this.opacity;
18145 this.addCommands({
18146 cmd: setOpacity.bind(this, opacity),
18147 undo: setOpacity.bind(this, savedOpacity),
18148 post: this._uiManager.updateUI.bind(this._uiManager, this),
18149 mustExec: true,
18150 type: AnnotationEditorParamsType.INK_OPACITY,
18151 overwriteIfSameType: true,
18152 keepUndo: true
18153 });
18154 }
18155 rebuild() {
18156 if (!this.parent) {
18157 return;
18158 }
18159 super.rebuild();
18160 if (this.div === null) {
18161 return;
18162 }
18163 if (!this.canvas) {
18164 this.#createCanvas();
18165 this.#createObserver();
18166 }
18167 if (!this.isAttachedToDOM) {
18168 this.parent.add(this);
18169 this.#setCanvasDims();
18170 }
18171 this.#fitToContent();
18172 }
18173 remove() {
18174 if (this.canvas === null) {
18175 return;
18176 }
18177 if (!this.isEmpty()) {
18178 this.commit();
18179 }
18180 this.canvas.width = this.canvas.height = 0;
18181 this.canvas.remove();
18182 this.canvas = null;
18183 if (this.#canvasContextMenuTimeoutId) {
18184 clearTimeout(this.#canvasContextMenuTimeoutId);
18185 this.#canvasContextMenuTimeoutId = null;
18186 }
18187 this.#observer?.disconnect();
18188 this.#observer = null;
18189 super.remove();
18190 }
18191 setParent(parent) {
18192 if (!this.parent && parent) {
18193 this._uiManager.removeShouldRescale(this);
18194 } else if (this.parent && parent === null) {
18195 this._uiManager.addShouldRescale(this);
18196 }
18197 super.setParent(parent);
18198 }
18199 onScaleChanging() {
18200 const [parentWidth, parentHeight] = this.parentDimensions;
18201 const width = this.width * parentWidth;
18202 const height = this.height * parentHeight;
18203 this.setDimensions(width, height);
18204 }
18205 enableEditMode() {
18206 if (this.#disableEditing || this.canvas === null) {
18207 return;
18208 }
18209 super.enableEditMode();
18210 this._isDraggable = false;
18211 this.#addPointerdownListener();
18212 }
18213 disableEditMode() {
18214 if (!this.isInEditMode() || this.canvas === null) {
18215 return;
18216 }
18217 super.disableEditMode();
18218 this._isDraggable = !this.isEmpty();
18219 this.div.classList.remove("editing");
18220 this.#removePointerdownListener();
18221 }
18222 onceAdded() {
18223 this._isDraggable = !this.isEmpty();
18224 }
18225 isEmpty() {
18226 return this.paths.length === 0 || this.paths.length === 1 && this.paths[0].length === 0;
18227 }
18228 #getInitialBBox() {
18229 const {
18230 parentRotation,
18231 parentDimensions: [width, height]
18232 } = this;
18233 switch (parentRotation) {
18234 case 90:
18235 return [0, height, height, width];
18236 case 180:
18237 return [width, height, width, height];
18238 case 270:
18239 return [width, 0, height, width];
18240 default:
18241 return [0, 0, width, height];
18242 }
18243 }
18244 #setStroke() {
18245 const {
18246 ctx,
18247 color,
18248 opacity,
18249 thickness,
18250 parentScale,
18251 scaleFactor
18252 } = this;
18253 ctx.lineWidth = thickness * parentScale / scaleFactor;
18254 ctx.lineCap = "round";
18255 ctx.lineJoin = "round";
18256 ctx.miterLimit = 10;
18257 ctx.strokeStyle = `${color}${opacityToHex(opacity)}`;
18258 }
18259 #startDrawing(x, y) {
18260 this.canvas.addEventListener("contextmenu", noContextMenu, {
18261 signal: this._uiManager._signal
18262 });
18263 this.#removePointerdownListener();
18264 this.#drawingAC = new AbortController();
18265 const signal = this._uiManager.combinedSignal(this.#drawingAC);
18266 this.canvas.addEventListener("pointerleave", this.canvasPointerleave.bind(this), {
18267 signal
18268 });
18269 this.canvas.addEventListener("pointermove", this.canvasPointermove.bind(this), {
18270 signal
18271 });
18272 this.canvas.addEventListener("pointerup", this.canvasPointerup.bind(this), {
18273 signal
18274 });
18275 this.isEditing = true;
18276 if (!this.#isCanvasInitialized) {
18277 this.#isCanvasInitialized = true;
18278 this.#setCanvasDims();
18279 this.thickness ||= InkEditor._defaultThickness;
18280 this.color ||= InkEditor._defaultColor || AnnotationEditor._defaultLineColor;
18281 this.opacity ??= InkEditor._defaultOpacity;
18282 }
18283 this.currentPath.push([x, y]);
18284 this.#hasSomethingToDraw = false;
18285 this.#setStroke();
18286 this.#requestFrameCallback = () => {
18287 this.#drawPoints();
18288 if (this.#requestFrameCallback) {
18289 window.requestAnimationFrame(this.#requestFrameCallback);
18290 }
18291 };
18292 window.requestAnimationFrame(this.#requestFrameCallback);
18293 }
18294 #draw(x, y) {
18295 const [lastX, lastY] = this.currentPath.at(-1);
18296 if (this.currentPath.length > 1 && x === lastX && y === lastY) {
18297 return;
18298 }
18299 const currentPath = this.currentPath;
18300 let path2D = this.#currentPath2D;
18301 currentPath.push([x, y]);
18302 this.#hasSomethingToDraw = true;
18303 if (currentPath.length <= 2) {
18304 path2D.moveTo(...currentPath[0]);
18305 path2D.lineTo(x, y);
18306 return;
18307 }
18308 if (currentPath.length === 3) {
18309 this.#currentPath2D = path2D = new Path2D();
18310 path2D.moveTo(...currentPath[0]);
18311 }
18312 this.#makeBezierCurve(path2D, ...currentPath.at(-3), ...currentPath.at(-2), x, y);
18313 }
18314 #endPath() {
18315 if (this.currentPath.length === 0) {
18316 return;
18317 }
18318 const lastPoint = this.currentPath.at(-1);
18319 this.#currentPath2D.lineTo(...lastPoint);
18320 }
18321 #stopDrawing(x, y) {
18322 this.#requestFrameCallback = null;
18323 x = Math.min(Math.max(x, 0), this.canvas.width);
18324 y = Math.min(Math.max(y, 0), this.canvas.height);
18325 this.#draw(x, y);
18326 this.#endPath();
18327 let bezier;
18328 if (this.currentPath.length !== 1) {
18329 bezier = this.#generateBezierPoints();
18330 } else {
18331 const xy = [x, y];
18332 bezier = [[xy, xy.slice(), xy.slice(), xy]];
18333 }
18334 const path2D = this.#currentPath2D;
18335 const currentPath = this.currentPath;
18336 this.currentPath = [];
18337 this.#currentPath2D = new Path2D();
18338 const cmd = () => {
18339 this.allRawPaths.push(currentPath);
18340 this.paths.push(bezier);
18341 this.bezierPath2D.push(path2D);
18342 this._uiManager.rebuild(this);
18343 };
18344 const undo = () => {
18345 this.allRawPaths.pop();
18346 this.paths.pop();
18347 this.bezierPath2D.pop();
18348 if (this.paths.length === 0) {
18349 this.remove();
18350 } else {
18351 if (!this.canvas) {
18352 this.#createCanvas();
18353 this.#createObserver();
18354 }
18355 this.#fitToContent();
18356 }
18357 };
18358 this.addCommands({
18359 cmd,
18360 undo,
18361 mustExec: true
18362 });
18363 }
18364 #drawPoints() {
18365 if (!this.#hasSomethingToDraw) {
18366 return;
18367 }
18368 this.#hasSomethingToDraw = false;
18369 const thickness = Math.ceil(this.thickness * this.parentScale);
18370 const lastPoints = this.currentPath.slice(-3);
18371 const x = lastPoints.map(xy => xy[0]);
18372 const y = lastPoints.map(xy => xy[1]);
18373 const xMin = Math.min(...x) - thickness;
18374 const xMax = Math.max(...x) + thickness;
18375 const yMin = Math.min(...y) - thickness;
18376 const yMax = Math.max(...y) + thickness;
18377 const {
18378 ctx
18379 } = this;
18380 ctx.save();
18381 ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
18382 for (const path of this.bezierPath2D) {
18383 ctx.stroke(path);
18384 }
18385 ctx.stroke(this.#currentPath2D);
18386 ctx.restore();
18387 }
18388 #makeBezierCurve(path2D, x0, y0, x1, y1, x2, y2) {
18389 const prevX = (x0 + x1) / 2;
18390 const prevY = (y0 + y1) / 2;
18391 const x3 = (x1 + x2) / 2;
18392 const y3 = (y1 + y2) / 2;
18393 path2D.bezierCurveTo(prevX + 2 * (x1 - prevX) / 3, prevY + 2 * (y1 - prevY) / 3, x3 + 2 * (x1 - x3) / 3, y3 + 2 * (y1 - y3) / 3, x3, y3);
18394 }
18395 #generateBezierPoints() {
18396 const path = this.currentPath;
18397 if (path.length <= 2) {
18398 return [[path[0], path[0], path.at(-1), path.at(-1)]];
18399 }
18400 const bezierPoints = [];
18401 let i;
18402 let [x0, y0] = path[0];
18403 for (i = 1; i < path.length - 2; i++) {
18404 const [x1, y1] = path[i];
18405 const [x2, y2] = path[i + 1];
18406 const x3 = (x1 + x2) / 2;
18407 const y3 = (y1 + y2) / 2;
18408 const control1 = [x0 + 2 * (x1 - x0) / 3, y0 + 2 * (y1 - y0) / 3];
18409 const control2 = [x3 + 2 * (x1 - x3) / 3, y3 + 2 * (y1 - y3) / 3];
18410 bezierPoints.push([[x0, y0], control1, control2, [x3, y3]]);
18411 [x0, y0] = [x3, y3];
18412 }
18413 const [x1, y1] = path[i];
18414 const [x2, y2] = path[i + 1];
18415 const control1 = [x0 + 2 * (x1 - x0) / 3, y0 + 2 * (y1 - y0) / 3];
18416 const control2 = [x2 + 2 * (x1 - x2) / 3, y2 + 2 * (y1 - y2) / 3];
18417 bezierPoints.push([[x0, y0], control1, control2, [x2, y2]]);
18418 return bezierPoints;
18419 }
18420 #redraw() {
18421 if (this.isEmpty()) {
18422 this.#updateTransform();
18423 return;
18424 }
18425 this.#setStroke();
18426 const {
18427 canvas,
18428 ctx
18429 } = this;
18430 ctx.setTransform(1, 0, 0, 1, 0, 0);
18431 ctx.clearRect(0, 0, canvas.width, canvas.height);
18432 this.#updateTransform();
18433 for (const path of this.bezierPath2D) {
18434 ctx.stroke(path);
18435 }
18436 }
18437 commit() {
18438 if (this.#disableEditing) {
18439 return;
18440 }
18441 super.commit();
18442 this.isEditing = false;
18443 this.disableEditMode();
18444 this.setInForeground();
18445 this.#disableEditing = true;
18446 this.div.classList.add("disabled");
18447 this.#fitToContent(true);
18448 this.select();
18449 this.parent.addInkEditorIfNeeded(true);
18450 this.moveInDOM();
18451 this.div.focus({
18452 preventScroll: true
18453 });
18454 }
18455 focusin(event) {
18456 if (!this._focusEventsAllowed) {
18457 return;
18458 }
18459 super.focusin(event);
18460 this.enableEditMode();
18461 }
18462 #addPointerdownListener() {
18463 if (this.#pointerdownAC) {
18464 return;
18465 }
18466 this.#pointerdownAC = new AbortController();
18467 const signal = this._uiManager.combinedSignal(this.#pointerdownAC);
18468 this.canvas.addEventListener("pointerdown", this.canvasPointerdown.bind(this), {
18469 signal
18470 });
18471 }
18472 #removePointerdownListener() {
18473 this.pointerdownAC?.abort();
18474 this.pointerdownAC = null;
18475 }
18476 canvasPointerdown(event) {
18477 if (event.button !== 0 || !this.isInEditMode() || this.#disableEditing) {
18478 return;
18479 }
18480 this.setInForeground();
18481 event.preventDefault();
18482 if (!this.div.contains(document.activeElement)) {
18483 this.div.focus({
18484 preventScroll: true
18485 });
18486 }
18487 this.#startDrawing(event.offsetX, event.offsetY);
18488 }
18489 canvasPointermove(event) {
18490 event.preventDefault();
18491 this.#draw(event.offsetX, event.offsetY);
18492 }
18493 canvasPointerup(event) {
18494 event.preventDefault();
18495 this.#endDrawing(event);
18496 }
18497 canvasPointerleave(event) {
18498 this.#endDrawing(event);
18499 }
18500 #endDrawing(event) {
18501 this.#drawingAC?.abort();
18502 this.#drawingAC = null;
18503 this.#addPointerdownListener();
18504 if (this.#canvasContextMenuTimeoutId) {
18505 clearTimeout(this.#canvasContextMenuTimeoutId);
18506 }
18507 this.#canvasContextMenuTimeoutId = setTimeout(() => {
18508 this.#canvasContextMenuTimeoutId = null;
18509 this.canvas.removeEventListener("contextmenu", noContextMenu);
18510 }, 10);
18511 this.#stopDrawing(event.offsetX, event.offsetY);
18512 this.addToAnnotationStorage();
18513 this.setInBackground();
18514 }
18515 #createCanvas() {
18516 this.canvas = document.createElement("canvas");
18517 this.canvas.width = this.canvas.height = 0;
18518 this.canvas.className = "inkEditorCanvas";
18519 this.canvas.setAttribute("data-l10n-id", "pdfjs-ink-canvas");
18520 this.div.append(this.canvas);
18521 this.ctx = this.canvas.getContext("2d");
18522 }
18523 #createObserver() {
18524 this.#observer = new ResizeObserver(entries => {
18525 const rect = entries[0].contentRect;
18526 if (rect.width && rect.height) {
18527 this.setDimensions(rect.width, rect.height);
18528 }
18529 });
18530 this.#observer.observe(this.div);
18531 this._uiManager._signal.addEventListener("abort", () => {
18532 this.#observer?.disconnect();
18533 this.#observer = null;
18534 }, {
18535 once: true
18536 });
18537 }
18538 get isResizable() {
18539 return !this.isEmpty() && this.#disableEditing;
18540 }
18541 render() {
18542 if (this.div) {
18543 return this.div;
18544 }
18545 let baseX, baseY;
18546 if (this.width) {
18547 baseX = this.x;
18548 baseY = this.y;
18549 }
18550 super.render();
18551 this.div.setAttribute("data-l10n-id", "pdfjs-ink");
18552 const [x, y, w, h] = this.#getInitialBBox();
18553 this.setAt(x, y, 0, 0);
18554 this.setDims(w, h);
18555 this.#createCanvas();
18556 if (this.width) {
18557 const [parentWidth, parentHeight] = this.parentDimensions;
18558 this.setAspectRatio(this.width * parentWidth, this.height * parentHeight);
18559 this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
18560 this.#isCanvasInitialized = true;
18561 this.#setCanvasDims();
18562 this.setDims(this.width * parentWidth, this.height * parentHeight);
18563 this.#redraw();
18564 this.div.classList.add("disabled");
18565 } else {
18566 this.div.classList.add("editing");
18567 this.enableEditMode();
18568 }
18569 this.#createObserver();
18570 return this.div;
18571 }
18572 #setCanvasDims() {
18573 if (!this.#isCanvasInitialized) {
18574 return;
18575 }
18576 const [parentWidth, parentHeight] = this.parentDimensions;
18577 this.canvas.width = Math.ceil(this.width * parentWidth);
18578 this.canvas.height = Math.ceil(this.height * parentHeight);
18579 this.#updateTransform();
18580 }
18581 setDimensions(width, height) {
18582 const roundedWidth = Math.round(width);
18583 const roundedHeight = Math.round(height);
18584 if (this.#realWidth === roundedWidth && this.#realHeight === roundedHeight) {
18585 return;
18586 }
18587 this.#realWidth = roundedWidth;
18588 this.#realHeight = roundedHeight;
18589 this.canvas.style.visibility = "hidden";
18590 const [parentWidth, parentHeight] = this.parentDimensions;
18591 this.width = width / parentWidth;
18592 this.height = height / parentHeight;
18593 this.fixAndSetPosition();
18594 if (this.#disableEditing) {
18595 this.#setScaleFactor(width, height);
18596 }
18597 this.#setCanvasDims();
18598 this.#redraw();
18599 this.canvas.style.visibility = "visible";
18600 this.fixDims();
18601 }
18602 #setScaleFactor(width, height) {
18603 const padding = this.#getPadding();
18604 const scaleFactorW = (width - padding) / this.#baseWidth;
18605 const scaleFactorH = (height - padding) / this.#baseHeight;
18606 this.scaleFactor = Math.min(scaleFactorW, scaleFactorH);
18607 }
18608 #updateTransform() {
18609 const padding = this.#getPadding() / 2;
18610 this.ctx.setTransform(this.scaleFactor, 0, 0, this.scaleFactor, this.translationX * this.scaleFactor + padding, this.translationY * this.scaleFactor + padding);
18611 }
18612 static #buildPath2D(bezier) {
18613 const path2D = new Path2D();
18614 for (let i = 0, ii = bezier.length; i < ii; i++) {
18615 const [first, control1, control2, second] = bezier[i];
18616 if (i === 0) {
18617 path2D.moveTo(...first);
18618 }
18619 path2D.bezierCurveTo(control1[0], control1[1], control2[0], control2[1], second[0], second[1]);
18620 }
18621 return path2D;
18622 }
18623 static #toPDFCoordinates(points, rect, rotation) {
18624 const [blX, blY, trX, trY] = rect;
18625 switch (rotation) {
18626 case 0:
18627 for (let i = 0, ii = points.length; i < ii; i += 2) {
18628 points[i] += blX;
18629 points[i + 1] = trY - points[i + 1];
18630 }
18631 break;
18632 case 90:
18633 for (let i = 0, ii = points.length; i < ii; i += 2) {
18634 const x = points[i];
18635 points[i] = points[i + 1] + blX;
18636 points[i + 1] = x + blY;
18637 }
18638 break;
18639 case 180:
18640 for (let i = 0, ii = points.length; i < ii; i += 2) {
18641 points[i] = trX - points[i];
18642 points[i + 1] += blY;
18643 }
18644 break;
18645 case 270:
18646 for (let i = 0, ii = points.length; i < ii; i += 2) {
18647 const x = points[i];
18648 points[i] = trX - points[i + 1];
18649 points[i + 1] = trY - x;
18650 }
18651 break;
18652 default:
18653 throw new Error("Invalid rotation");
18654 }
18655 return points;
18656 }
18657 static #fromPDFCoordinates(points, rect, rotation) {
18658 const [blX, blY, trX, trY] = rect;
18659 switch (rotation) {
18660 case 0:
18661 for (let i = 0, ii = points.length; i < ii; i += 2) {
18662 points[i] -= blX;
18663 points[i + 1] = trY - points[i + 1];
18664 }
18665 break;
18666 case 90:
18667 for (let i = 0, ii = points.length; i < ii; i += 2) {
18668 const x = points[i];
18669 points[i] = points[i + 1] - blY;
18670 points[i + 1] = x - blX;
18671 }
18672 break;
18673 case 180:
18674 for (let i = 0, ii = points.length; i < ii; i += 2) {
18675 points[i] = trX - points[i];
18676 points[i + 1] -= blY;
18677 }
18678 break;
18679 case 270:
18680 for (let i = 0, ii = points.length; i < ii; i += 2) {
18681 const x = points[i];
18682 points[i] = trY - points[i + 1];
18683 points[i + 1] = trX - x;
18684 }
18685 break;
18686 default:
18687 throw new Error("Invalid rotation");
18688 }
18689 return points;
18690 }
18691 #serializePaths(s, tx, ty, rect) {
18692 const paths = [];
18693 const padding = this.thickness / 2;
18694 const shiftX = s * tx + padding;
18695 const shiftY = s * ty + padding;
18696 for (const bezier of this.paths) {
18697 const buffer = [];
18698 const points = [];
18699 for (let j = 0, jj = bezier.length; j < jj; j++) {
18700 const [first, control1, control2, second] = bezier[j];
18701 if (first[0] === second[0] && first[1] === second[1] && jj === 1) {
18702 const p0 = s * first[0] + shiftX;
18703 const p1 = s * first[1] + shiftY;
18704 buffer.push(p0, p1);
18705 points.push(p0, p1);
18706 break;
18707 }
18708 const p10 = s * first[0] + shiftX;
18709 const p11 = s * first[1] + shiftY;
18710 const p20 = s * control1[0] + shiftX;
18711 const p21 = s * control1[1] + shiftY;
18712 const p30 = s * control2[0] + shiftX;
18713 const p31 = s * control2[1] + shiftY;
18714 const p40 = s * second[0] + shiftX;
18715 const p41 = s * second[1] + shiftY;
18716 if (j === 0) {
18717 buffer.push(p10, p11);
18718 points.push(p10, p11);
18719 }
18720 buffer.push(p20, p21, p30, p31, p40, p41);
18721 points.push(p20, p21);
18722 if (j === jj - 1) {
18723 points.push(p40, p41);
18724 }
18725 }
18726 paths.push({
18727 bezier: InkEditor.#toPDFCoordinates(buffer, rect, this.rotation),
18728 points: InkEditor.#toPDFCoordinates(points, rect, this.rotation)
18729 });
18730 }
18731 return paths;
18732 }
18733 #getBbox() {
18734 let xMin = Infinity;
18735 let xMax = -Infinity;
18736 let yMin = Infinity;
18737 let yMax = -Infinity;
18738 for (const path of this.paths) {
18739 for (const [first, control1, control2, second] of path) {
18740 const bbox = Util.bezierBoundingBox(...first, ...control1, ...control2, ...second);
18741 xMin = Math.min(xMin, bbox[0]);
18742 yMin = Math.min(yMin, bbox[1]);
18743 xMax = Math.max(xMax, bbox[2]);
18744 yMax = Math.max(yMax, bbox[3]);
18745 }
18746 }
18747 return [xMin, yMin, xMax, yMax];
18748 }
18749 #getPadding() {
18750 return this.#disableEditing ? Math.ceil(this.thickness * this.parentScale) : 0;
18751 }
18752 #fitToContent(firstTime = false) {
18753 if (this.isEmpty()) {
18754 return;
18755 }
18756 if (!this.#disableEditing) {
18757 this.#redraw();
18758 return;
18759 }
18760 const bbox = this.#getBbox();
18761 const padding = this.#getPadding();
18762 this.#baseWidth = Math.max(AnnotationEditor.MIN_SIZE, bbox[2] - bbox[0]);
18763 this.#baseHeight = Math.max(AnnotationEditor.MIN_SIZE, bbox[3] - bbox[1]);
18764 const width = Math.ceil(padding + this.#baseWidth * this.scaleFactor);
18765 const height = Math.ceil(padding + this.#baseHeight * this.scaleFactor);
18766 const [parentWidth, parentHeight] = this.parentDimensions;
18767 this.width = width / parentWidth;
18768 this.height = height / parentHeight;
18769 this.setAspectRatio(width, height);
18770 const prevTranslationX = this.translationX;
18771 const prevTranslationY = this.translationY;
18772 this.translationX = -bbox[0];
18773 this.translationY = -bbox[1];
18774 this.#setCanvasDims();
18775 this.#redraw();
18776 this.#realWidth = width;
18777 this.#realHeight = height;
18778 this.setDims(width, height);
18779 const unscaledPadding = firstTime ? padding / this.scaleFactor / 2 : 0;
18780 this.translate(prevTranslationX - this.translationX - unscaledPadding, prevTranslationY - this.translationY - unscaledPadding);
18781 }
18782 static async deserialize(data, parent, uiManager) {
18783 if (data instanceof InkAnnotationElement) {
18784 return null;
18785 }
18786 const editor = await super.deserialize(data, parent, uiManager);
18787 editor.thickness = data.thickness;
18788 editor.color = Util.makeHexColor(...data.color);
18789 editor.opacity = data.opacity;
18790 const [pageWidth, pageHeight] = editor.pageDimensions;
18791 const width = editor.width * pageWidth;
18792 const height = editor.height * pageHeight;
18793 const scaleFactor = editor.parentScale;
18794 const padding = data.thickness / 2;
18795 editor.#disableEditing = true;
18796 editor.#realWidth = Math.round(width);
18797 editor.#realHeight = Math.round(height);
18798 const {
18799 paths,
18800 rect,
18801 rotation
18802 } = data;
18803 for (let {
18804 bezier
18805 } of paths) {
18806 bezier = InkEditor.#fromPDFCoordinates(bezier, rect, rotation);
18807 const path = [];
18808 editor.paths.push(path);
18809 let p0 = scaleFactor * (bezier[0] - padding);
18810 let p1 = scaleFactor * (bezier[1] - padding);
18811 for (let i = 2, ii = bezier.length; i < ii; i += 6) {
18812 const p10 = scaleFactor * (bezier[i] - padding);
18813 const p11 = scaleFactor * (bezier[i + 1] - padding);
18814 const p20 = scaleFactor * (bezier[i + 2] - padding);
18815 const p21 = scaleFactor * (bezier[i + 3] - padding);
18816 const p30 = scaleFactor * (bezier[i + 4] - padding);
18817 const p31 = scaleFactor * (bezier[i + 5] - padding);
18818 path.push([[p0, p1], [p10, p11], [p20, p21], [p30, p31]]);
18819 p0 = p30;
18820 p1 = p31;
18821 }
18822 const path2D = this.#buildPath2D(path);
18823 editor.bezierPath2D.push(path2D);
18824 }
18825 const bbox = editor.#getBbox();
18826 editor.#baseWidth = Math.max(AnnotationEditor.MIN_SIZE, bbox[2] - bbox[0]);
18827 editor.#baseHeight = Math.max(AnnotationEditor.MIN_SIZE, bbox[3] - bbox[1]);
18828 editor.#setScaleFactor(width, height);
18829 return editor;
18830 }
18831 serialize() {
18832 if (this.isEmpty()) {
18833 return null;
18834 }
18835 const rect = this.getRect(0, 0);
18836 const color = AnnotationEditor._colorManager.convert(this.ctx.strokeStyle);
18837 return {
18838 annotationType: AnnotationEditorType.INK,
18839 color,
18840 thickness: this.thickness,
18841 opacity: this.opacity,
18842 paths: this.#serializePaths(this.scaleFactor / this.parentScale, this.translationX, this.translationY, rect),
18843 pageIndex: this.pageIndex,
18844 rect,
18845 rotation: this.rotation,
18846 structTreeParentId: this._structTreeParentId
18847 };
18848 }
18849 }
18850
18851 ;// ./src/display/editor/stamp.js
18852
18853
18854
18855
18856 class StampEditor extends AnnotationEditor {
18857 #bitmap = null;
18858 #bitmapId = null;
18859 #bitmapPromise = null;
18860 #bitmapUrl = null;
18861 #bitmapFile = null;
18862 #bitmapFileName = "";
18863 #canvas = null;
18864 #observer = null;
18865 #resizeTimeoutId = null;
18866 #isSvg = false;
18867 #hasBeenAddedInUndoStack = false;
18868 static _type = "stamp";
18869 static _editorType = AnnotationEditorType.STAMP;
18870 constructor(params) {
18871 super({
18872 ...params,
18873 name: "stampEditor"
18874 });
18875 this.#bitmapUrl = params.bitmapUrl;
18876 this.#bitmapFile = params.bitmapFile;
18877 }
18878 static initialize(l10n, uiManager) {
18879 AnnotationEditor.initialize(l10n, uiManager);
18880 }
18881 static get supportedTypes() {
18882 const types = ["apng", "avif", "bmp", "gif", "jpeg", "png", "svg+xml", "webp", "x-icon"];
18883 return shadow(this, "supportedTypes", types.map(type => `image/${type}`));
18884 }
18885 static get supportedTypesStr() {
18886 return shadow(this, "supportedTypesStr", this.supportedTypes.join(","));
18887 }
18888 static isHandlingMimeForPasting(mime) {
18889 return this.supportedTypes.includes(mime);
18890 }
18891 static paste(item, parent) {
18892 parent.pasteEditor(AnnotationEditorType.STAMP, {
18893 bitmapFile: item.getAsFile()
18894 });
18895 }
18896 altTextFinish() {
18897 if (this._uiManager.useNewAltTextFlow) {
18898 this.div.hidden = false;
18899 }
18900 super.altTextFinish();
18901 }
18902 get telemetryFinalData() {
18903 return {
18904 type: "stamp",
18905 hasAltText: !!this.altTextData?.altText
18906 };
18907 }
18908 static computeTelemetryFinalData(data) {
18909 const hasAltTextStats = data.get("hasAltText");
18910 return {
18911 hasAltText: hasAltTextStats.get(true) ?? 0,
18912 hasNoAltText: hasAltTextStats.get(false) ?? 0
18913 };
18914 }
18915 #getBitmapFetched(data, fromId = false) {
18916 if (!data) {
18917 this.remove();
18918 return;
18919 }
18920 this.#bitmap = data.bitmap;
18921 if (!fromId) {
18922 this.#bitmapId = data.id;
18923 this.#isSvg = data.isSvg;
18924 }
18925 if (data.file) {
18926 this.#bitmapFileName = data.file.name;
18927 }
18928 this.#createCanvas();
18929 }
18930 #getBitmapDone() {
18931 this.#bitmapPromise = null;
18932 this._uiManager.enableWaiting(false);
18933 if (!this.#canvas) {
18934 return;
18935 }
18936 if (this._uiManager.useNewAltTextWhenAddingImage && this._uiManager.useNewAltTextFlow && this.#bitmap) {
18937 this._editToolbar.hide();
18938 this._uiManager.editAltText(this, true);
18939 return;
18940 }
18941 if (!this._uiManager.useNewAltTextWhenAddingImage && this._uiManager.useNewAltTextFlow && this.#bitmap) {
18942 this._reportTelemetry({
18943 action: "pdfjs.image.image_added",
18944 data: {
18945 alt_text_modal: false,
18946 alt_text_type: "empty"
18947 }
18948 });
18949 try {
18950 this.mlGuessAltText();
18951 } catch {}
18952 }
18953 this.div.focus();
18954 }
18955 async mlGuessAltText(imageData = null, updateAltTextData = true) {
18956 if (this.hasAltTextData()) {
18957 return null;
18958 }
18959 const {
18960 mlManager
18961 } = this._uiManager;
18962 if (!mlManager) {
18963 throw new Error("No ML.");
18964 }
18965 if (!(await mlManager.isEnabledFor("altText"))) {
18966 throw new Error("ML isn't enabled for alt text.");
18967 }
18968 const {
18969 data,
18970 width,
18971 height
18972 } = imageData || this.copyCanvas(null, null, true).imageData;
18973 const response = await mlManager.guess({
18974 name: "altText",
18975 request: {
18976 data,
18977 width,
18978 height,
18979 channels: data.length / (width * height)
18980 }
18981 });
18982 if (!response) {
18983 throw new Error("No response from the AI service.");
18984 }
18985 if (response.error) {
18986 throw new Error("Error from the AI service.");
18987 }
18988 if (response.cancel) {
18989 return null;
18990 }
18991 if (!response.output) {
18992 throw new Error("No valid response from the AI service.");
18993 }
18994 const altText = response.output;
18995 await this.setGuessedAltText(altText);
18996 if (updateAltTextData && !this.hasAltTextData()) {
18997 this.altTextData = {
18998 alt: altText,
18999 decorative: false
19000 };
19001 }
19002 return altText;
19003 }
19004 #getBitmap() {
19005 if (this.#bitmapId) {
19006 this._uiManager.enableWaiting(true);
19007 this._uiManager.imageManager.getFromId(this.#bitmapId).then(data => this.#getBitmapFetched(data, true)).finally(() => this.#getBitmapDone());
19008 return;
19009 }
19010 if (this.#bitmapUrl) {
19011 const url = this.#bitmapUrl;
19012 this.#bitmapUrl = null;
19013 this._uiManager.enableWaiting(true);
19014 this.#bitmapPromise = this._uiManager.imageManager.getFromUrl(url).then(data => this.#getBitmapFetched(data)).finally(() => this.#getBitmapDone());
19015 return;
19016 }
19017 if (this.#bitmapFile) {
19018 const file = this.#bitmapFile;
19019 this.#bitmapFile = null;
19020 this._uiManager.enableWaiting(true);
19021 this.#bitmapPromise = this._uiManager.imageManager.getFromFile(file).then(data => this.#getBitmapFetched(data)).finally(() => this.#getBitmapDone());
19022 return;
19023 }
19024 const input = document.createElement("input");
19025 input.type = "file";
19026 input.accept = StampEditor.supportedTypesStr;
19027 const signal = this._uiManager._signal;
19028 this.#bitmapPromise = new Promise(resolve => {
19029 input.addEventListener("change", async () => {
19030 if (!input.files || input.files.length === 0) {
19031 this.remove();
19032 } else {
19033 this._uiManager.enableWaiting(true);
19034 const data = await this._uiManager.imageManager.getFromFile(input.files[0]);
19035 this._reportTelemetry({
19036 action: "pdfjs.image.image_selected",
19037 data: {
19038 alt_text_modal: this._uiManager.useNewAltTextFlow
19039 }
19040 });
19041 this.#getBitmapFetched(data);
19042 }
19043 resolve();
19044 }, {
19045 signal
19046 });
19047 input.addEventListener("cancel", () => {
19048 this.remove();
19049 resolve();
19050 }, {
19051 signal
19052 });
19053 }).finally(() => this.#getBitmapDone());
19054 input.click();
19055 }
19056 remove() {
19057 if (this.#bitmapId) {
19058 this.#bitmap = null;
19059 this._uiManager.imageManager.deleteId(this.#bitmapId);
19060 this.#canvas?.remove();
19061 this.#canvas = null;
19062 this.#observer?.disconnect();
19063 this.#observer = null;
19064 if (this.#resizeTimeoutId) {
19065 clearTimeout(this.#resizeTimeoutId);
19066 this.#resizeTimeoutId = null;
19067 }
19068 }
19069 super.remove();
19070 }
19071 rebuild() {
19072 if (!this.parent) {
19073 if (this.#bitmapId) {
19074 this.#getBitmap();
19075 }
19076 return;
19077 }
19078 super.rebuild();
19079 if (this.div === null) {
19080 return;
19081 }
19082 if (this.#bitmapId && this.#canvas === null) {
19083 this.#getBitmap();
19084 }
19085 if (!this.isAttachedToDOM) {
19086 this.parent.add(this);
19087 }
19088 }
19089 onceAdded() {
19090 this._isDraggable = true;
19091 this.div.focus();
19092 }
19093 isEmpty() {
19094 return !(this.#bitmapPromise || this.#bitmap || this.#bitmapUrl || this.#bitmapFile || this.#bitmapId);
19095 }
19096 get isResizable() {
19097 return true;
19098 }
19099 render() {
19100 if (this.div) {
19101 return this.div;
19102 }
19103 let baseX, baseY;
19104 if (this.width) {
19105 baseX = this.x;
19106 baseY = this.y;
19107 }
19108 super.render();
19109 this.div.hidden = true;
19110 this.div.setAttribute("role", "figure");
19111 this.addAltTextButton();
19112 if (this.#bitmap) {
19113 this.#createCanvas();
19114 } else {
19115 this.#getBitmap();
19116 }
19117 if (this.width && !this.annotationElementId) {
19118 const [parentWidth, parentHeight] = this.parentDimensions;
19119 this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
19120 }
19121 return this.div;
19122 }
19123 #createCanvas() {
19124 const {
19125 div
19126 } = this;
19127 let {
19128 width,
19129 height
19130 } = this.#bitmap;
19131 const [pageWidth, pageHeight] = this.pageDimensions;
19132 const MAX_RATIO = 0.75;
19133 if (this.width) {
19134 width = this.width * pageWidth;
19135 height = this.height * pageHeight;
19136 } else if (width > MAX_RATIO * pageWidth || height > MAX_RATIO * pageHeight) {
19137 const factor = Math.min(MAX_RATIO * pageWidth / width, MAX_RATIO * pageHeight / height);
19138 width *= factor;
19139 height *= factor;
19140 }
19141 const [parentWidth, parentHeight] = this.parentDimensions;
19142 this.setDims(width * parentWidth / pageWidth, height * parentHeight / pageHeight);
19143 this._uiManager.enableWaiting(false);
19144 const canvas = this.#canvas = document.createElement("canvas");
19145 canvas.setAttribute("role", "img");
19146 this.addContainer(canvas);
19147 if (!this._uiManager.useNewAltTextWhenAddingImage || !this._uiManager.useNewAltTextFlow || this.annotationElementId) {
19148 div.hidden = false;
19149 }
19150 this.#drawBitmap(width, height);
19151 this.#createObserver();
19152 if (!this.#hasBeenAddedInUndoStack) {
19153 this.parent.addUndoableEditor(this);
19154 this.#hasBeenAddedInUndoStack = true;
19155 }
19156 this._reportTelemetry({
19157 action: "inserted_image"
19158 });
19159 if (this.#bitmapFileName) {
19160 canvas.setAttribute("aria-label", this.#bitmapFileName);
19161 }
19162 }
19163 copyCanvas(maxDataDimension, maxPreviewDimension, createImageData = false) {
19164 if (!maxDataDimension) {
19165 maxDataDimension = 224;
19166 }
19167 const {
19168 width: bitmapWidth,
19169 height: bitmapHeight
19170 } = this.#bitmap;
19171 const outputScale = new OutputScale();
19172 let bitmap = this.#bitmap;
19173 let width = bitmapWidth,
19174 height = bitmapHeight;
19175 let canvas = null;
19176 if (maxPreviewDimension) {
19177 if (bitmapWidth > maxPreviewDimension || bitmapHeight > maxPreviewDimension) {
19178 const ratio = Math.min(maxPreviewDimension / bitmapWidth, maxPreviewDimension / bitmapHeight);
19179 width = Math.floor(bitmapWidth * ratio);
19180 height = Math.floor(bitmapHeight * ratio);
19181 }
19182 canvas = document.createElement("canvas");
19183 const scaledWidth = canvas.width = Math.ceil(width * outputScale.sx);
19184 const scaledHeight = canvas.height = Math.ceil(height * outputScale.sy);
19185 if (!this.#isSvg) {
19186 bitmap = this.#scaleBitmap(scaledWidth, scaledHeight);
19187 }
19188 const ctx = canvas.getContext("2d");
19189 ctx.filter = this._uiManager.hcmFilter;
19190 let white = "white",
19191 black = "#cfcfd8";
19192 if (this._uiManager.hcmFilter !== "none") {
19193 black = "black";
19194 } else if (window.matchMedia?.("(prefers-color-scheme: dark)").matches) {
19195 white = "#8f8f9d";
19196 black = "#42414d";
19197 }
19198 const boxDim = 15;
19199 const boxDimWidth = boxDim * outputScale.sx;
19200 const boxDimHeight = boxDim * outputScale.sy;
19201 const pattern = new OffscreenCanvas(boxDimWidth * 2, boxDimHeight * 2);
19202 const patternCtx = pattern.getContext("2d");
19203 patternCtx.fillStyle = white;
19204 patternCtx.fillRect(0, 0, boxDimWidth * 2, boxDimHeight * 2);
19205 patternCtx.fillStyle = black;
19206 patternCtx.fillRect(0, 0, boxDimWidth, boxDimHeight);
19207 patternCtx.fillRect(boxDimWidth, boxDimHeight, boxDimWidth, boxDimHeight);
19208 ctx.fillStyle = ctx.createPattern(pattern, "repeat");
19209 ctx.fillRect(0, 0, scaledWidth, scaledHeight);
19210 ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, scaledWidth, scaledHeight);
19211 }
19212 let imageData = null;
19213 if (createImageData) {
19214 let dataWidth, dataHeight;
19215 if (outputScale.symmetric && bitmap.width < maxDataDimension && bitmap.height < maxDataDimension) {
19216 dataWidth = bitmap.width;
19217 dataHeight = bitmap.height;
19218 } else {
19219 bitmap = this.#bitmap;
19220 if (bitmapWidth > maxDataDimension || bitmapHeight > maxDataDimension) {
19221 const ratio = Math.min(maxDataDimension / bitmapWidth, maxDataDimension / bitmapHeight);
19222 dataWidth = Math.floor(bitmapWidth * ratio);
19223 dataHeight = Math.floor(bitmapHeight * ratio);
19224 if (!this.#isSvg) {
19225 bitmap = this.#scaleBitmap(dataWidth, dataHeight);
19226 }
19227 }
19228 }
19229 const offscreen = new OffscreenCanvas(dataWidth, dataHeight);
19230 const offscreenCtx = offscreen.getContext("2d", {
19231 willReadFrequently: true
19232 });
19233 offscreenCtx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, dataWidth, dataHeight);
19234 imageData = {
19235 width: dataWidth,
19236 height: dataHeight,
19237 data: offscreenCtx.getImageData(0, 0, dataWidth, dataHeight).data
19238 };
19239 }
19240 return {
19241 canvas,
19242 width,
19243 height,
19244 imageData
19245 };
19246 }
19247 #setDimensions(width, height) {
19248 const [parentWidth, parentHeight] = this.parentDimensions;
19249 this.width = width / parentWidth;
19250 this.height = height / parentHeight;
19251 if (this._initialOptions?.isCentered) {
19252 this.center();
19253 } else {
19254 this.fixAndSetPosition();
19255 }
19256 this._initialOptions = null;
19257 if (this.#resizeTimeoutId !== null) {
19258 clearTimeout(this.#resizeTimeoutId);
19259 }
19260 const TIME_TO_WAIT = 200;
19261 this.#resizeTimeoutId = setTimeout(() => {
19262 this.#resizeTimeoutId = null;
19263 this.#drawBitmap(width, height);
19264 }, TIME_TO_WAIT);
19265 }
19266 #scaleBitmap(width, height) {
19267 const {
19268 width: bitmapWidth,
19269 height: bitmapHeight
19270 } = this.#bitmap;
19271 let newWidth = bitmapWidth;
19272 let newHeight = bitmapHeight;
19273 let bitmap = this.#bitmap;
19274 while (newWidth > 2 * width || newHeight > 2 * height) {
19275 const prevWidth = newWidth;
19276 const prevHeight = newHeight;
19277 if (newWidth > 2 * width) {
19278 newWidth = newWidth >= 16384 ? Math.floor(newWidth / 2) - 1 : Math.ceil(newWidth / 2);
19279 }
19280 if (newHeight > 2 * height) {
19281 newHeight = newHeight >= 16384 ? Math.floor(newHeight / 2) - 1 : Math.ceil(newHeight / 2);
19282 }
19283 const offscreen = new OffscreenCanvas(newWidth, newHeight);
19284 const ctx = offscreen.getContext("2d");
19285 ctx.drawImage(bitmap, 0, 0, prevWidth, prevHeight, 0, 0, newWidth, newHeight);
19286 bitmap = offscreen.transferToImageBitmap();
19287 }
19288 return bitmap;
19289 }
19290 #drawBitmap(width, height) {
19291 const outputScale = new OutputScale();
19292 const scaledWidth = Math.ceil(width * outputScale.sx);
19293 const scaledHeight = Math.ceil(height * outputScale.sy);
19294 const canvas = this.#canvas;
19295 if (!canvas || canvas.width === scaledWidth && canvas.height === scaledHeight) {
19296 return;
19297 }
19298 canvas.width = scaledWidth;
19299 canvas.height = scaledHeight;
19300 const bitmap = this.#isSvg ? this.#bitmap : this.#scaleBitmap(scaledWidth, scaledHeight);
19301 const ctx = canvas.getContext("2d");
19302 ctx.filter = this._uiManager.hcmFilter;
19303 ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, scaledWidth, scaledHeight);
19304 }
19305 getImageForAltText() {
19306 return this.#canvas;
19307 }
19308 #serializeBitmap(toUrl) {
19309 if (toUrl) {
19310 if (this.#isSvg) {
19311 const url = this._uiManager.imageManager.getSvgUrl(this.#bitmapId);
19312 if (url) {
19313 return url;
19314 }
19315 }
19316 const canvas = document.createElement("canvas");
19317 ({
19318 width: canvas.width,
19319 height: canvas.height
19320 } = this.#bitmap);
19321 const ctx = canvas.getContext("2d");
19322 ctx.drawImage(this.#bitmap, 0, 0);
19323 return canvas.toDataURL();
19324 }
19325 if (this.#isSvg) {
19326 const [pageWidth, pageHeight] = this.pageDimensions;
19327 const width = Math.round(this.width * pageWidth * PixelsPerInch.PDF_TO_CSS_UNITS);
19328 const height = Math.round(this.height * pageHeight * PixelsPerInch.PDF_TO_CSS_UNITS);
19329 const offscreen = new OffscreenCanvas(width, height);
19330 const ctx = offscreen.getContext("2d");
19331 ctx.drawImage(this.#bitmap, 0, 0, this.#bitmap.width, this.#bitmap.height, 0, 0, width, height);
19332 return offscreen.transferToImageBitmap();
19333 }
19334 return structuredClone(this.#bitmap);
19335 }
19336 #createObserver() {
19337 if (!this._uiManager._signal) {
19338 return;
19339 }
19340 this.#observer = new ResizeObserver(entries => {
19341 const rect = entries[0].contentRect;
19342 if (rect.width && rect.height) {
19343 this.#setDimensions(rect.width, rect.height);
19344 }
19345 });
19346 this.#observer.observe(this.div);
19347 this._uiManager._signal.addEventListener("abort", () => {
19348 this.#observer?.disconnect();
19349 this.#observer = null;
19350 }, {
19351 once: true
19352 });
19353 }
19354 static async deserialize(data, parent, uiManager) {
19355 let initialData = null;
19356 if (data instanceof StampAnnotationElement) {
19357 const {
19358 data: {
19359 rect,
19360 rotation,
19361 id,
19362 structParent,
19363 popupRef
19364 },
19365 container,
19366 parent: {
19367 page: {
19368 pageNumber
19369 }
19370 }
19371 } = data;
19372 const canvas = container.querySelector("canvas");
19373 const imageData = uiManager.imageManager.getFromCanvas(container.id, canvas);
19374 canvas.remove();
19375 const altText = (await parent._structTree.getAriaAttributes(`${AnnotationPrefix}${id}`))?.get("aria-label") || "";
19376 initialData = data = {
19377 annotationType: AnnotationEditorType.STAMP,
19378 bitmapId: imageData.id,
19379 bitmap: imageData.bitmap,
19380 pageIndex: pageNumber - 1,
19381 rect: rect.slice(0),
19382 rotation,
19383 id,
19384 deleted: false,
19385 accessibilityData: {
19386 decorative: false,
19387 altText
19388 },
19389 isSvg: false,
19390 structParent,
19391 popupRef
19392 };
19393 }
19394 const editor = await super.deserialize(data, parent, uiManager);
19395 const {
19396 rect,
19397 bitmap,
19398 bitmapUrl,
19399 bitmapId,
19400 isSvg,
19401 accessibilityData
19402 } = data;
19403 if (bitmapId && uiManager.imageManager.isValidId(bitmapId)) {
19404 editor.#bitmapId = bitmapId;
19405 if (bitmap) {
19406 editor.#bitmap = bitmap;
19407 }
19408 } else {
19409 editor.#bitmapUrl = bitmapUrl;
19410 }
19411 editor.#isSvg = isSvg;
19412 const [parentWidth, parentHeight] = editor.pageDimensions;
19413 editor.width = (rect[2] - rect[0]) / parentWidth;
19414 editor.height = (rect[3] - rect[1]) / parentHeight;
19415 editor.annotationElementId = data.id || null;
19416 if (accessibilityData) {
19417 editor.altTextData = accessibilityData;
19418 }
19419 editor._initialData = initialData;
19420 editor.#hasBeenAddedInUndoStack = !!initialData;
19421 return editor;
19422 }
19423 serialize(isForCopying = false, context = null) {
19424 if (this.isEmpty()) {
19425 return null;
19426 }
19427 if (this.deleted) {
19428 return this.serializeDeleted();
19429 }
19430 const serialized = {
19431 annotationType: AnnotationEditorType.STAMP,
19432 bitmapId: this.#bitmapId,
19433 pageIndex: this.pageIndex,
19434 rect: this.getRect(0, 0),
19435 rotation: this.rotation,
19436 isSvg: this.#isSvg,
19437 structTreeParentId: this._structTreeParentId
19438 };
19439 if (isForCopying) {
19440 serialized.bitmapUrl = this.#serializeBitmap(true);
19441 serialized.accessibilityData = this.serializeAltText(true);
19442 return serialized;
19443 }
19444 const {
19445 decorative,
19446 altText
19447 } = this.serializeAltText(false);
19448 if (!decorative && altText) {
19449 serialized.accessibilityData = {
19450 type: "Figure",
19451 alt: altText
19452 };
19453 }
19454 if (this.annotationElementId) {
19455 const changes = this.#hasElementChanged(serialized);
19456 if (changes.isSame) {
19457 return null;
19458 }
19459 if (changes.isSameAltText) {
19460 delete serialized.accessibilityData;
19461 } else {
19462 serialized.accessibilityData.structParent = this._initialData.structParent ?? -1;
19463 }
19464 }
19465 serialized.id = this.annotationElementId;
19466 if (context === null) {
19467 return serialized;
19468 }
19469 context.stamps ||= new Map();
19470 const area = this.#isSvg ? (serialized.rect[2] - serialized.rect[0]) * (serialized.rect[3] - serialized.rect[1]) : null;
19471 if (!context.stamps.has(this.#bitmapId)) {
19472 context.stamps.set(this.#bitmapId, {
19473 area,
19474 serialized
19475 });
19476 serialized.bitmap = this.#serializeBitmap(false);
19477 } else if (this.#isSvg) {
19478 const prevData = context.stamps.get(this.#bitmapId);
19479 if (area > prevData.area) {
19480 prevData.area = area;
19481 prevData.serialized.bitmap.close();
19482 prevData.serialized.bitmap = this.#serializeBitmap(false);
19483 }
19484 }
19485 return serialized;
19486 }
19487 #hasElementChanged(serialized) {
19488 const {
19489 rect,
19490 pageIndex,
19491 accessibilityData: {
19492 altText
19493 }
19494 } = this._initialData;
19495 const isSameRect = serialized.rect.every((x, i) => Math.abs(x - rect[i]) < 1);
19496 const isSamePageIndex = serialized.pageIndex === pageIndex;
19497 const isSameAltText = (serialized.accessibilityData?.alt || "") === altText;
19498 return {
19499 isSame: isSameRect && isSamePageIndex && isSameAltText,
19500 isSameAltText
19501 };
19502 }
19503 renderAnnotationElement(annotation) {
19504 annotation.updateEdited({
19505 rect: this.getRect(0, 0)
19506 });
19507 return null;
19508 }
19509 }
19510
19511 ;// ./src/display/editor/annotation_editor_layer.js
19512
19513
19514
19515
19516
19517
19518
19519 class AnnotationEditorLayer {
19520 #accessibilityManager;
19521 #allowClick = false;
19522 #annotationLayer = null;
19523 #clickAC = null;
19524 #editorFocusTimeoutId = null;
19525 #editors = new Map();
19526 #hadPointerDown = false;
19527 #isCleaningUp = false;
19528 #isDisabling = false;
19529 #textLayer = null;
19530 #textSelectionAC = null;
19531 #uiManager;
19532 static _initialized = false;
19533 static #editorTypes = new Map([FreeTextEditor, InkEditor, StampEditor, HighlightEditor].map(type => [type._editorType, type]));
19534 constructor({
19535 uiManager,
19536 pageIndex,
19537 div,
19538 structTreeLayer,
19539 accessibilityManager,
19540 annotationLayer,
19541 drawLayer,
19542 textLayer,
19543 viewport,
19544 l10n
19545 }) {
19546 const editorTypes = [...AnnotationEditorLayer.#editorTypes.values()];
19547 if (!AnnotationEditorLayer._initialized) {
19548 AnnotationEditorLayer._initialized = true;
19549 for (const editorType of editorTypes) {
19550 editorType.initialize(l10n, uiManager);
19551 }
19552 }
19553 uiManager.registerEditorTypes(editorTypes);
19554 this.#uiManager = uiManager;
19555 this.pageIndex = pageIndex;
19556 this.div = div;
19557 this.#accessibilityManager = accessibilityManager;
19558 this.#annotationLayer = annotationLayer;
19559 this.viewport = viewport;
19560 this.#textLayer = textLayer;
19561 this.drawLayer = drawLayer;
19562 this._structTree = structTreeLayer;
19563 this.#uiManager.addLayer(this);
19564 }
19565 get isEmpty() {
19566 return this.#editors.size === 0;
19567 }
19568 get isInvisible() {
19569 return this.isEmpty && this.#uiManager.getMode() === AnnotationEditorType.NONE;
19570 }
19571 updateToolbar(mode) {
19572 this.#uiManager.updateToolbar(mode);
19573 }
19574 updateMode(mode = this.#uiManager.getMode()) {
19575 this.#cleanup();
19576 switch (mode) {
19577 case AnnotationEditorType.NONE:
19578 this.disableTextSelection();
19579 this.togglePointerEvents(false);
19580 this.toggleAnnotationLayerPointerEvents(true);
19581 this.disableClick();
19582 return;
19583 case AnnotationEditorType.INK:
19584 this.addInkEditorIfNeeded(false);
19585 this.disableTextSelection();
19586 this.togglePointerEvents(true);
19587 this.disableClick();
19588 break;
19589 case AnnotationEditorType.HIGHLIGHT:
19590 this.enableTextSelection();
19591 this.togglePointerEvents(false);
19592 this.disableClick();
19593 break;
19594 default:
19595 this.disableTextSelection();
19596 this.togglePointerEvents(true);
19597 this.enableClick();
19598 }
19599 this.toggleAnnotationLayerPointerEvents(false);
19600 const {
19601 classList
19602 } = this.div;
19603 for (const editorType of AnnotationEditorLayer.#editorTypes.values()) {
19604 classList.toggle(`${editorType._type}Editing`, mode === editorType._editorType);
19605 }
19606 this.div.hidden = false;
19607 }
19608 hasTextLayer(textLayer) {
19609 return textLayer === this.#textLayer?.div;
19610 }
19611 addInkEditorIfNeeded(isCommitting) {
19612 if (this.#uiManager.getMode() !== AnnotationEditorType.INK) {
19613 return;
19614 }
19615 if (!isCommitting) {
19616 for (const editor of this.#editors.values()) {
19617 if (editor.isEmpty()) {
19618 editor.setInBackground();
19619 return;
19620 }
19621 }
19622 }
19623 const editor = this.createAndAddNewEditor({
19624 offsetX: 0,
19625 offsetY: 0
19626 }, false);
19627 editor.setInBackground();
19628 }
19629 setEditingState(isEditing) {
19630 this.#uiManager.setEditingState(isEditing);
19631 }
19632 addCommands(params) {
19633 this.#uiManager.addCommands(params);
19634 }
19635 toggleDrawing(enabled = false) {
19636 this.div.classList.toggle("drawing", !enabled);
19637 }
19638 togglePointerEvents(enabled = false) {
19639 this.div.classList.toggle("disabled", !enabled);
19640 }
19641 toggleAnnotationLayerPointerEvents(enabled = false) {
19642 this.#annotationLayer?.div.classList.toggle("disabled", !enabled);
19643 }
19644 async enable() {
19645 this.div.tabIndex = 0;
19646 this.togglePointerEvents(true);
19647 const annotationElementIds = new Set();
19648 for (const editor of this.#editors.values()) {
19649 editor.enableEditing();
19650 editor.show(true);
19651 if (editor.annotationElementId) {
19652 this.#uiManager.removeChangedExistingAnnotation(editor);
19653 annotationElementIds.add(editor.annotationElementId);
19654 }
19655 }
19656 if (!this.#annotationLayer) {
19657 return;
19658 }
19659 const editables = this.#annotationLayer.getEditableAnnotations();
19660 for (const editable of editables) {
19661 editable.hide();
19662 if (this.#uiManager.isDeletedAnnotationElement(editable.data.id)) {
19663 continue;
19664 }
19665 if (annotationElementIds.has(editable.data.id)) {
19666 continue;
19667 }
19668 const editor = await this.deserialize(editable);
19669 if (!editor) {
19670 continue;
19671 }
19672 this.addOrRebuild(editor);
19673 editor.enableEditing();
19674 }
19675 }
19676 disable() {
19677 this.#isDisabling = true;
19678 this.div.tabIndex = -1;
19679 this.togglePointerEvents(false);
19680 const changedAnnotations = new Map();
19681 const resetAnnotations = new Map();
19682 for (const editor of this.#editors.values()) {
19683 editor.disableEditing();
19684 if (!editor.annotationElementId) {
19685 continue;
19686 }
19687 if (editor.serialize() !== null) {
19688 changedAnnotations.set(editor.annotationElementId, editor);
19689 continue;
19690 } else {
19691 resetAnnotations.set(editor.annotationElementId, editor);
19692 }
19693 this.getEditableAnnotation(editor.annotationElementId)?.show();
19694 editor.remove();
19695 }
19696 if (this.#annotationLayer) {
19697 const editables = this.#annotationLayer.getEditableAnnotations();
19698 for (const editable of editables) {
19699 const {
19700 id
19701 } = editable.data;
19702 if (this.#uiManager.isDeletedAnnotationElement(id)) {
19703 continue;
19704 }
19705 let editor = resetAnnotations.get(id);
19706 if (editor) {
19707 editor.resetAnnotationElement(editable);
19708 editor.show(false);
19709 editable.show();
19710 continue;
19711 }
19712 editor = changedAnnotations.get(id);
19713 if (editor) {
19714 this.#uiManager.addChangedExistingAnnotation(editor);
19715 if (editor.renderAnnotationElement(editable)) {
19716 editor.show(false);
19717 }
19718 }
19719 editable.show();
19720 }
19721 }
19722 this.#cleanup();
19723 if (this.isEmpty) {
19724 this.div.hidden = true;
19725 }
19726 const {
19727 classList
19728 } = this.div;
19729 for (const editorType of AnnotationEditorLayer.#editorTypes.values()) {
19730 classList.remove(`${editorType._type}Editing`);
19731 }
19732 this.disableTextSelection();
19733 this.toggleAnnotationLayerPointerEvents(true);
19734 this.#isDisabling = false;
19735 }
19736 getEditableAnnotation(id) {
19737 return this.#annotationLayer?.getEditableAnnotation(id) || null;
19738 }
19739 setActiveEditor(editor) {
19740 const currentActive = this.#uiManager.getActive();
19741 if (currentActive === editor) {
19742 return;
19743 }
19744 this.#uiManager.setActiveEditor(editor);
19745 }
19746 enableTextSelection() {
19747 this.div.tabIndex = -1;
19748 if (this.#textLayer?.div && !this.#textSelectionAC) {
19749 this.#textSelectionAC = new AbortController();
19750 const signal = this.#uiManager.combinedSignal(this.#textSelectionAC);
19751 this.#textLayer.div.addEventListener("pointerdown", this.#textLayerPointerDown.bind(this), {
19752 signal
19753 });
19754 this.#textLayer.div.classList.add("highlighting");
19755 }
19756 }
19757 disableTextSelection() {
19758 this.div.tabIndex = 0;
19759 if (this.#textLayer?.div && this.#textSelectionAC) {
19760 this.#textSelectionAC.abort();
19761 this.#textSelectionAC = null;
19762 this.#textLayer.div.classList.remove("highlighting");
19763 }
19764 }
19765 #textLayerPointerDown(event) {
19766 this.#uiManager.unselectAll();
19767 const {
19768 target
19769 } = event;
19770 if (target === this.#textLayer.div || (target.getAttribute("role") === "img" || target.classList.contains("endOfContent")) && this.#textLayer.div.contains(target)) {
19771 const {
19772 isMac
19773 } = util_FeatureTest.platform;
19774 if (event.button !== 0 || event.ctrlKey && isMac) {
19775 return;
19776 }
19777 this.#uiManager.showAllEditors("highlight", true, true);
19778 this.#textLayer.div.classList.add("free");
19779 this.toggleDrawing();
19780 HighlightEditor.startHighlighting(this, this.#uiManager.direction === "ltr", {
19781 target: this.#textLayer.div,
19782 x: event.x,
19783 y: event.y
19784 });
19785 this.#textLayer.div.addEventListener("pointerup", () => {
19786 this.#textLayer.div.classList.remove("free");
19787 this.toggleDrawing(true);
19788 }, {
19789 once: true,
19790 signal: this.#uiManager._signal
19791 });
19792 event.preventDefault();
19793 }
19794 }
19795 enableClick() {
19796 if (this.#clickAC) {
19797 return;
19798 }
19799 this.#clickAC = new AbortController();
19800 const signal = this.#uiManager.combinedSignal(this.#clickAC);
19801 this.div.addEventListener("pointerdown", this.pointerdown.bind(this), {
19802 signal
19803 });
19804 this.div.addEventListener("pointerup", this.pointerup.bind(this), {
19805 signal
19806 });
19807 }
19808 disableClick() {
19809 this.#clickAC?.abort();
19810 this.#clickAC = null;
19811 }
19812 attach(editor) {
19813 this.#editors.set(editor.id, editor);
19814 const {
19815 annotationElementId
19816 } = editor;
19817 if (annotationElementId && this.#uiManager.isDeletedAnnotationElement(annotationElementId)) {
19818 this.#uiManager.removeDeletedAnnotationElement(editor);
19819 }
19820 }
19821 detach(editor) {
19822 this.#editors.delete(editor.id);
19823 this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);
19824 if (!this.#isDisabling && editor.annotationElementId) {
19825 this.#uiManager.addDeletedAnnotationElement(editor);
19826 }
19827 }
19828 remove(editor) {
19829 this.detach(editor);
19830 this.#uiManager.removeEditor(editor);
19831 editor.div.remove();
19832 editor.isAttachedToDOM = false;
19833 if (!this.#isCleaningUp) {
19834 this.addInkEditorIfNeeded(false);
19835 }
19836 }
19837 changeParent(editor) {
19838 if (editor.parent === this) {
19839 return;
19840 }
19841 if (editor.parent && editor.annotationElementId) {
19842 this.#uiManager.addDeletedAnnotationElement(editor.annotationElementId);
19843 AnnotationEditor.deleteAnnotationElement(editor);
19844 editor.annotationElementId = null;
19845 }
19846 this.attach(editor);
19847 editor.parent?.detach(editor);
19848 editor.setParent(this);
19849 if (editor.div && editor.isAttachedToDOM) {
19850 editor.div.remove();
19851 this.div.append(editor.div);
19852 }
19853 }
19854 add(editor) {
19855 if (editor.parent === this && editor.isAttachedToDOM) {
19856 return;
19857 }
19858 this.changeParent(editor);
19859 this.#uiManager.addEditor(editor);
19860 this.attach(editor);
19861 if (!editor.isAttachedToDOM) {
19862 const div = editor.render();
19863 this.div.append(div);
19864 editor.isAttachedToDOM = true;
19865 }
19866 editor.fixAndSetPosition();
19867 editor.onceAdded();
19868 this.#uiManager.addToAnnotationStorage(editor);
19869 editor._reportTelemetry(editor.telemetryInitialData);
19870 }
19871 moveEditorInDOM(editor) {
19872 if (!editor.isAttachedToDOM) {
19873 return;
19874 }
19875 const {
19876 activeElement
19877 } = document;
19878 if (editor.div.contains(activeElement) && !this.#editorFocusTimeoutId) {
19879 editor._focusEventsAllowed = false;
19880 this.#editorFocusTimeoutId = setTimeout(() => {
19881 this.#editorFocusTimeoutId = null;
19882 if (!editor.div.contains(document.activeElement)) {
19883 editor.div.addEventListener("focusin", () => {
19884 editor._focusEventsAllowed = true;
19885 }, {
19886 once: true,
19887 signal: this.#uiManager._signal
19888 });
19889 activeElement.focus();
19890 } else {
19891 editor._focusEventsAllowed = true;
19892 }
19893 }, 0);
19894 }
19895 editor._structTreeParentId = this.#accessibilityManager?.moveElementInDOM(this.div, editor.div, editor.contentDiv, true);
19896 }
19897 addOrRebuild(editor) {
19898 if (editor.needsToBeRebuilt()) {
19899 editor.parent ||= this;
19900 editor.rebuild();
19901 editor.show();
19902 } else {
19903 this.add(editor);
19904 }
19905 }
19906 addUndoableEditor(editor) {
19907 const cmd = () => editor._uiManager.rebuild(editor);
19908 const undo = () => {
19909 editor.remove();
19910 };
19911 this.addCommands({
19912 cmd,
19913 undo,
19914 mustExec: false
19915 });
19916 }
19917 getNextId() {
19918 return this.#uiManager.getId();
19919 }
19920 get #currentEditorType() {
19921 return AnnotationEditorLayer.#editorTypes.get(this.#uiManager.getMode());
19922 }
19923 combinedSignal(ac) {
19924 return this.#uiManager.combinedSignal(ac);
19925 }
19926 #createNewEditor(params) {
19927 const editorType = this.#currentEditorType;
19928 return editorType ? new editorType.prototype.constructor(params) : null;
19929 }
19930 canCreateNewEmptyEditor() {
19931 return this.#currentEditorType?.canCreateNewEmptyEditor();
19932 }
19933 pasteEditor(mode, params) {
19934 this.#uiManager.updateToolbar(mode);
19935 this.#uiManager.updateMode(mode);
19936 const {
19937 offsetX,
19938 offsetY
19939 } = this.#getCenterPoint();
19940 const id = this.getNextId();
19941 const editor = this.#createNewEditor({
19942 parent: this,
19943 id,
19944 x: offsetX,
19945 y: offsetY,
19946 uiManager: this.#uiManager,
19947 isCentered: true,
19948 ...params
19949 });
19950 if (editor) {
19951 this.add(editor);
19952 }
19953 }
19954 async deserialize(data) {
19955 return (await AnnotationEditorLayer.#editorTypes.get(data.annotationType ?? data.annotationEditorType)?.deserialize(data, this, this.#uiManager)) || null;
19956 }
19957 createAndAddNewEditor(event, isCentered, data = {}) {
19958 const id = this.getNextId();
19959 const editor = this.#createNewEditor({
19960 parent: this,
19961 id,
19962 x: event.offsetX,
19963 y: event.offsetY,
19964 uiManager: this.#uiManager,
19965 isCentered,
19966 ...data
19967 });
19968 if (editor) {
19969 this.add(editor);
19970 }
19971 return editor;
19972 }
19973 #getCenterPoint() {
19974 const {
19975 x,
19976 y,
19977 width,
19978 height
19979 } = this.div.getBoundingClientRect();
19980 const tlX = Math.max(0, x);
19981 const tlY = Math.max(0, y);
19982 const brX = Math.min(window.innerWidth, x + width);
19983 const brY = Math.min(window.innerHeight, y + height);
19984 const centerX = (tlX + brX) / 2 - x;
19985 const centerY = (tlY + brY) / 2 - y;
19986 const [offsetX, offsetY] = this.viewport.rotation % 180 === 0 ? [centerX, centerY] : [centerY, centerX];
19987 return {
19988 offsetX,
19989 offsetY
19990 };
19991 }
19992 addNewEditor() {
19993 this.createAndAddNewEditor(this.#getCenterPoint(), true);
19994 }
19995 setSelected(editor) {
19996 this.#uiManager.setSelected(editor);
19997 }
19998 toggleSelected(editor) {
19999 this.#uiManager.toggleSelected(editor);
20000 }
20001 isSelected(editor) {
20002 return this.#uiManager.isSelected(editor);
20003 }
20004 unselect(editor) {
20005 this.#uiManager.unselect(editor);
20006 }
20007 pointerup(event) {
20008 const {
20009 isMac
20010 } = util_FeatureTest.platform;
20011 if (event.button !== 0 || event.ctrlKey && isMac) {
20012 return;
20013 }
20014 if (event.target !== this.div) {
20015 return;
20016 }
20017 if (!this.#hadPointerDown) {
20018 return;
20019 }
20020 this.#hadPointerDown = false;
20021 if (!this.#allowClick) {
20022 this.#allowClick = true;
20023 return;
20024 }
20025 if (this.#uiManager.getMode() === AnnotationEditorType.STAMP) {
20026 this.#uiManager.unselectAll();
20027 return;
20028 }
20029 this.createAndAddNewEditor(event, false);
20030 }
20031 pointerdown(event) {
20032 if (this.#uiManager.getMode() === AnnotationEditorType.HIGHLIGHT) {
20033 this.enableTextSelection();
20034 }
20035 if (this.#hadPointerDown) {
20036 this.#hadPointerDown = false;
20037 return;
20038 }
20039 const {
20040 isMac
20041 } = util_FeatureTest.platform;
20042 if (event.button !== 0 || event.ctrlKey && isMac) {
20043 return;
20044 }
20045 if (event.target !== this.div) {
20046 return;
20047 }
20048 this.#hadPointerDown = true;
20049 const editor = this.#uiManager.getActive();
20050 this.#allowClick = !editor || editor.isEmpty();
20051 }
20052 findNewParent(editor, x, y) {
20053 const layer = this.#uiManager.findParent(x, y);
20054 if (layer === null || layer === this) {
20055 return false;
20056 }
20057 layer.changeParent(editor);
20058 return true;
20059 }
20060 destroy() {
20061 if (this.#uiManager.getActive()?.parent === this) {
20062 this.#uiManager.commitOrRemove();
20063 this.#uiManager.setActiveEditor(null);
20064 }
20065 if (this.#editorFocusTimeoutId) {
20066 clearTimeout(this.#editorFocusTimeoutId);
20067 this.#editorFocusTimeoutId = null;
20068 }
20069 for (const editor of this.#editors.values()) {
20070 this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);
20071 editor.setParent(null);
20072 editor.isAttachedToDOM = false;
20073 editor.div.remove();
20074 }
20075 this.div = null;
20076 this.#editors.clear();
20077 this.#uiManager.removeLayer(this);
20078 }
20079 #cleanup() {
20080 this.#isCleaningUp = true;
20081 for (const editor of this.#editors.values()) {
20082 if (editor.isEmpty()) {
20083 editor.remove();
20084 }
20085 }
20086 this.#isCleaningUp = false;
20087 }
20088 render({
20089 viewport
20090 }) {
20091 this.viewport = viewport;
20092 setLayerDimensions(this.div, viewport);
20093 for (const editor of this.#uiManager.getEditors(this.pageIndex)) {
20094 this.add(editor);
20095 editor.rebuild();
20096 }
20097 this.updateMode();
20098 }
20099 update({
20100 viewport
20101 }) {
20102 this.#uiManager.commitOrRemove();
20103 this.#cleanup();
20104 const oldRotation = this.viewport.rotation;
20105 const rotation = viewport.rotation;
20106 this.viewport = viewport;
20107 setLayerDimensions(this.div, {
20108 rotation
20109 });
20110 if (oldRotation !== rotation) {
20111 for (const editor of this.#editors.values()) {
20112 editor.rotate(rotation);
20113 }
20114 }
20115 this.addInkEditorIfNeeded(false);
20116 }
20117 get pageDimensions() {
20118 const {
20119 pageWidth,
20120 pageHeight
20121 } = this.viewport.rawDims;
20122 return [pageWidth, pageHeight];
20123 }
20124 get scale() {
20125 return this.#uiManager.viewParameters.realScale;
20126 }
20127 }
20128
20129 ;// ./src/display/draw_layer.js
20130
20131
20132 class DrawLayer {
20133 #parent = null;
20134 #id = 0;
20135 #mapping = new Map();
20136 #toUpdate = new Map();
20137 constructor({
20138 pageIndex
20139 }) {
20140 this.pageIndex = pageIndex;
20141 }
20142 setParent(parent) {
20143 if (!this.#parent) {
20144 this.#parent = parent;
20145 return;
20146 }
20147 if (this.#parent !== parent) {
20148 if (this.#mapping.size > 0) {
20149 for (const root of this.#mapping.values()) {
20150 root.remove();
20151 parent.append(root);
20152 }
20153 }
20154 this.#parent = parent;
20155 }
20156 }
20157 static get _svgFactory() {
20158 return shadow(this, "_svgFactory", new DOMSVGFactory());
20159 }
20160 static #setBox(element, {
20161 x = 0,
20162 y = 0,
20163 width = 1,
20164 height = 1
20165 } = {}) {
20166 const {
20167 style
20168 } = element;
20169 style.top = `${100 * y}%`;
20170 style.left = `${100 * x}%`;
20171 style.width = `${100 * width}%`;
20172 style.height = `${100 * height}%`;
20173 }
20174 #createSVG(box) {
20175 const svg = DrawLayer._svgFactory.create(1, 1, true);
20176 this.#parent.append(svg);
20177 svg.setAttribute("aria-hidden", true);
20178 DrawLayer.#setBox(svg, box);
20179 return svg;
20180 }
20181 #createClipPath(defs, pathId) {
20182 const clipPath = DrawLayer._svgFactory.createElement("clipPath");
20183 defs.append(clipPath);
20184 const clipPathId = `clip_${pathId}`;
20185 clipPath.setAttribute("id", clipPathId);
20186 clipPath.setAttribute("clipPathUnits", "objectBoundingBox");
20187 const clipPathUse = DrawLayer._svgFactory.createElement("use");
20188 clipPath.append(clipPathUse);
20189 clipPathUse.setAttribute("href", `#${pathId}`);
20190 clipPathUse.classList.add("clip");
20191 return clipPathId;
20192 }
20193 highlight(outlines, color, opacity, isPathUpdatable = false) {
20194 const id = this.#id++;
20195 const root = this.#createSVG(outlines.box);
20196 root.classList.add("highlight");
20197 if (outlines.free) {
20198 root.classList.add("free");
20199 }
20200 const defs = DrawLayer._svgFactory.createElement("defs");
20201 root.append(defs);
20202 const path = DrawLayer._svgFactory.createElement("path");
20203 defs.append(path);
20204 const pathId = `path_p${this.pageIndex}_${id}`;
20205 path.setAttribute("id", pathId);
20206 path.setAttribute("d", outlines.toSVGPath());
20207 if (isPathUpdatable) {
20208 this.#toUpdate.set(id, path);
20209 }
20210 const clipPathId = this.#createClipPath(defs, pathId);
20211 const use = DrawLayer._svgFactory.createElement("use");
20212 root.append(use);
20213 root.setAttribute("fill", color);
20214 root.setAttribute("fill-opacity", opacity);
20215 use.setAttribute("href", `#${pathId}`);
20216 this.#mapping.set(id, root);
20217 return {
20218 id,
20219 clipPathId: `url(#${clipPathId})`
20220 };
20221 }
20222 highlightOutline(outlines) {
20223 const id = this.#id++;
20224 const root = this.#createSVG(outlines.box);
20225 root.classList.add("highlightOutline");
20226 const defs = DrawLayer._svgFactory.createElement("defs");
20227 root.append(defs);
20228 const path = DrawLayer._svgFactory.createElement("path");
20229 defs.append(path);
20230 const pathId = `path_p${this.pageIndex}_${id}`;
20231 path.setAttribute("id", pathId);
20232 path.setAttribute("d", outlines.toSVGPath());
20233 path.setAttribute("vector-effect", "non-scaling-stroke");
20234 let maskId;
20235 if (outlines.free) {
20236 root.classList.add("free");
20237 const mask = DrawLayer._svgFactory.createElement("mask");
20238 defs.append(mask);
20239 maskId = `mask_p${this.pageIndex}_${id}`;
20240 mask.setAttribute("id", maskId);
20241 mask.setAttribute("maskUnits", "objectBoundingBox");
20242 const rect = DrawLayer._svgFactory.createElement("rect");
20243 mask.append(rect);
20244 rect.setAttribute("width", "1");
20245 rect.setAttribute("height", "1");
20246 rect.setAttribute("fill", "white");
20247 const use = DrawLayer._svgFactory.createElement("use");
20248 mask.append(use);
20249 use.setAttribute("href", `#${pathId}`);
20250 use.setAttribute("stroke", "none");
20251 use.setAttribute("fill", "black");
20252 use.setAttribute("fill-rule", "nonzero");
20253 use.classList.add("mask");
20254 }
20255 const use1 = DrawLayer._svgFactory.createElement("use");
20256 root.append(use1);
20257 use1.setAttribute("href", `#${pathId}`);
20258 if (maskId) {
20259 use1.setAttribute("mask", `url(#${maskId})`);
20260 }
20261 const use2 = use1.cloneNode();
20262 root.append(use2);
20263 use1.classList.add("mainOutline");
20264 use2.classList.add("secondaryOutline");
20265 this.#mapping.set(id, root);
20266 return id;
20267 }
20268 finalizeLine(id, line) {
20269 const path = this.#toUpdate.get(id);
20270 this.#toUpdate.delete(id);
20271 this.updateBox(id, line.box);
20272 path.setAttribute("d", line.toSVGPath());
20273 }
20274 updateLine(id, line) {
20275 const root = this.#mapping.get(id);
20276 const defs = root.firstChild;
20277 const path = defs.firstChild;
20278 path.setAttribute("d", line.toSVGPath());
20279 }
20280 removeFreeHighlight(id) {
20281 this.remove(id);
20282 this.#toUpdate.delete(id);
20283 }
20284 updatePath(id, line) {
20285 this.#toUpdate.get(id).setAttribute("d", line.toSVGPath());
20286 }
20287 updateBox(id, box) {
20288 DrawLayer.#setBox(this.#mapping.get(id), box);
20289 }
20290 show(id, visible) {
20291 this.#mapping.get(id).classList.toggle("hidden", !visible);
20292 }
20293 rotate(id, angle) {
20294 this.#mapping.get(id).setAttribute("data-main-rotation", angle);
20295 }
20296 changeColor(id, color) {
20297 this.#mapping.get(id).setAttribute("fill", color);
20298 }
20299 changeOpacity(id, opacity) {
20300 this.#mapping.get(id).setAttribute("fill-opacity", opacity);
20301 }
20302 addClass(id, className) {
20303 this.#mapping.get(id).classList.add(className);
20304 }
20305 removeClass(id, className) {
20306 this.#mapping.get(id).classList.remove(className);
20307 }
20308 getSVGRoot(id) {
20309 return this.#mapping.get(id);
20310 }
20311 remove(id) {
20312 if (this.#parent === null) {
20313 return;
20314 }
20315 this.#mapping.get(id).remove();
20316 this.#mapping.delete(id);
20317 }
20318 destroy() {
20319 this.#parent = null;
20320 for (const root of this.#mapping.values()) {
20321 root.remove();
20322 }
20323 this.#mapping.clear();
20324 }
20325 }
20326
20327 ;// ./src/pdf.js
20328
20329
20330
20331
20332
20333
20334
20335
20336
20337
20338
20339
20340 const pdfjsVersion = "4.7.76";
20341 const pdfjsBuild = "8b73b828b";
20342
20343 var __webpack_exports__AbortException = __webpack_exports__.AbortException;
20344 var __webpack_exports__AnnotationEditorLayer = __webpack_exports__.AnnotationEditorLayer;
20345 var __webpack_exports__AnnotationEditorParamsType = __webpack_exports__.AnnotationEditorParamsType;
20346 var __webpack_exports__AnnotationEditorType = __webpack_exports__.AnnotationEditorType;
20347 var __webpack_exports__AnnotationEditorUIManager = __webpack_exports__.AnnotationEditorUIManager;
20348 var __webpack_exports__AnnotationLayer = __webpack_exports__.AnnotationLayer;
20349 var __webpack_exports__AnnotationMode = __webpack_exports__.AnnotationMode;
20350 var __webpack_exports__CMapCompressionType = __webpack_exports__.CMapCompressionType;
20351 var __webpack_exports__ColorPicker = __webpack_exports__.ColorPicker;
20352 var __webpack_exports__DOMSVGFactory = __webpack_exports__.DOMSVGFactory;
20353 var __webpack_exports__DrawLayer = __webpack_exports__.DrawLayer;
20354 var __webpack_exports__FeatureTest = __webpack_exports__.FeatureTest;
20355 var __webpack_exports__GlobalWorkerOptions = __webpack_exports__.GlobalWorkerOptions;
20356 var __webpack_exports__ImageKind = __webpack_exports__.ImageKind;
20357 var __webpack_exports__InvalidPDFException = __webpack_exports__.InvalidPDFException;
20358 var __webpack_exports__MissingPDFException = __webpack_exports__.MissingPDFException;
20359 var __webpack_exports__OPS = __webpack_exports__.OPS;
20360 var __webpack_exports__OutputScale = __webpack_exports__.OutputScale;
20361 var __webpack_exports__PDFDataRangeTransport = __webpack_exports__.PDFDataRangeTransport;
20362 var __webpack_exports__PDFDateString = __webpack_exports__.PDFDateString;
20363 var __webpack_exports__PDFWorker = __webpack_exports__.PDFWorker;
20364 var __webpack_exports__PasswordResponses = __webpack_exports__.PasswordResponses;
20365 var __webpack_exports__PermissionFlag = __webpack_exports__.PermissionFlag;
20366 var __webpack_exports__PixelsPerInch = __webpack_exports__.PixelsPerInch;
20367 var __webpack_exports__RenderingCancelledException = __webpack_exports__.RenderingCancelledException;
20368 var __webpack_exports__TextLayer = __webpack_exports__.TextLayer;
20369 var __webpack_exports__UnexpectedResponseException = __webpack_exports__.UnexpectedResponseException;
20370 var __webpack_exports__Util = __webpack_exports__.Util;
20371 var __webpack_exports__VerbosityLevel = __webpack_exports__.VerbosityLevel;
20372 var __webpack_exports__XfaLayer = __webpack_exports__.XfaLayer;
20373 var __webpack_exports__build = __webpack_exports__.build;
20374 var __webpack_exports__createValidAbsoluteUrl = __webpack_exports__.createValidAbsoluteUrl;
20375 var __webpack_exports__fetchData = __webpack_exports__.fetchData;
20376 var __webpack_exports__getDocument = __webpack_exports__.getDocument;
20377 var __webpack_exports__getFilenameFromUrl = __webpack_exports__.getFilenameFromUrl;
20378 var __webpack_exports__getPdfFilenameFromUrl = __webpack_exports__.getPdfFilenameFromUrl;
20379 var __webpack_exports__getXfaPageViewport = __webpack_exports__.getXfaPageViewport;
20380 var __webpack_exports__isDataScheme = __webpack_exports__.isDataScheme;
20381 var __webpack_exports__isPdfFile = __webpack_exports__.isPdfFile;
20382 var __webpack_exports__noContextMenu = __webpack_exports__.noContextMenu;
20383 var __webpack_exports__normalizeUnicode = __webpack_exports__.normalizeUnicode;
20384 var __webpack_exports__setLayerDimensions = __webpack_exports__.setLayerDimensions;
20385 var __webpack_exports__shadow = __webpack_exports__.shadow;
20386 var __webpack_exports__version = __webpack_exports__.version;
20387 export { __webpack_exports__AbortException as AbortException, __webpack_exports__AnnotationEditorLayer as AnnotationEditorLayer, __webpack_exports__AnnotationEditorParamsType as AnnotationEditorParamsType, __webpack_exports__AnnotationEditorType as AnnotationEditorType, __webpack_exports__AnnotationEditorUIManager as AnnotationEditorUIManager, __webpack_exports__AnnotationLayer as AnnotationLayer, __webpack_exports__AnnotationMode as AnnotationMode, __webpack_exports__CMapCompressionType as CMapCompressionType, __webpack_exports__ColorPicker as ColorPicker, __webpack_exports__DOMSVGFactory as DOMSVGFactory, __webpack_exports__DrawLayer as DrawLayer, __webpack_exports__FeatureTest as FeatureTest, __webpack_exports__GlobalWorkerOptions as GlobalWorkerOptions, __webpack_exports__ImageKind as ImageKind, __webpack_exports__InvalidPDFException as InvalidPDFException, __webpack_exports__MissingPDFException as MissingPDFException, __webpack_exports__OPS as OPS, __webpack_exports__OutputScale as OutputScale, __webpack_exports__PDFDataRangeTransport as PDFDataRangeTransport, __webpack_exports__PDFDateString as PDFDateString, __webpack_exports__PDFWorker as PDFWorker, __webpack_exports__PasswordResponses as PasswordResponses, __webpack_exports__PermissionFlag as PermissionFlag, __webpack_exports__PixelsPerInch as PixelsPerInch, __webpack_exports__RenderingCancelledException as RenderingCancelledException, __webpack_exports__TextLayer as TextLayer, __webpack_exports__UnexpectedResponseException as UnexpectedResponseException, __webpack_exports__Util as Util, __webpack_exports__VerbosityLevel as VerbosityLevel, __webpack_exports__XfaLayer as XfaLayer, __webpack_exports__build as build, __webpack_exports__createValidAbsoluteUrl as createValidAbsoluteUrl, __webpack_exports__fetchData as fetchData, __webpack_exports__getDocument as getDocument, __webpack_exports__getFilenameFromUrl as getFilenameFromUrl, __webpack_exports__getPdfFilenameFromUrl as getPdfFilenameFromUrl, __webpack_exports__getXfaPageViewport as getXfaPageViewport, __webpack_exports__isDataScheme as isDataScheme, __webpack_exports__isPdfFile as isPdfFile, __webpack_exports__noContextMenu as noContextMenu, __webpack_exports__normalizeUnicode as normalizeUnicode, __webpack_exports__setLayerDimensions as setLayerDimensions, __webpack_exports__shadow as shadow, __webpack_exports__version as version };
20388
20389 //# sourceMappingURL=pdf.mjs.map