diff --git a/fixed-layout.js b/fixed-layout.js index c1ab86e..40e0a8c 100644 --- a/fixed-layout.js +++ b/fixed-layout.js @@ -56,7 +56,10 @@ export class FixedLayout extends HTMLElement { this.#observer.observe(this) } - async #createFrame({ index, src }) { + async #createFrame({ index, src: srcOption }) { + const srcOptionIsString = typeof srcOption === 'string' + const src = srcOptionIsString ? srcOption : srcOption?.src + const onZoom = srcOptionIsString ? null : srcOption?.onZoom const element = document.createElement('div') const iframe = document.createElement('iframe') element.append(iframe) @@ -73,8 +76,7 @@ export class FixedLayout extends HTMLElement { this.#root.append(element) if (!src) return { blank: true, element, iframe } return new Promise(resolve => { - const onload = () => { - iframe.removeEventListener('load', onload) + iframe.addEventListener('load', () => { const doc = iframe.contentDocument this.dispatchEvent(new CustomEvent('load', { detail: { doc, index } })) const { width, height } = getViewport(doc, this.defaultViewport) @@ -82,9 +84,9 @@ export class FixedLayout extends HTMLElement { element, iframe, width: parseFloat(width), height: parseFloat(height), + onZoom, }) - } - iframe.addEventListener('load', onload) + }, { once: true }) iframe.src = src }) } @@ -111,11 +113,13 @@ export class FixedLayout extends HTMLElement { right.height ?? blankHeight)) const transform = frame => { - const { element, iframe, width, height, blank } = frame + let { element, iframe, width, height, blank, onZoom } = frame + if (onZoom) onZoom({ doc: frame.iframe.contentDocument, scale }) + const iframeScale = onZoom ? scale : 1 Object.assign(iframe.style, { - width: `${width}px`, - height: `${height}px`, - transform: `scale(${scale})`, + width: `${width * iframeScale}px`, + height: `${height * iframeScale}px`, + transform: onZoom ? 'none' : `scale(${scale})`, transformOrigin: 'top left', display: blank ? 'none' : 'block', }) diff --git a/pdf.js b/pdf.js index b0940e5..9efcde7 100644 --- a/pdf.js +++ b/pdf.js @@ -1,534 +1,53 @@ -/* global pdfjsLib */ +import './vendor/pdfjs/pdf.mjs' +const pdfjsLib = globalThis.pdfjsLib +pdfjsLib.GlobalWorkerOptions.workerSrc = + new URL('vendor/pdfjs/pdf.worker.mjs', import.meta.url).toString() -// https://github.com/mozilla/pdf.js/blob/f04967017f22e46d70d11468dd928b4cdc2f6ea1/web/text_layer_builder.css -const textLayerBuilderCSS = ` -/* Copyright 2014 Mozilla Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +const fetchText = async url => + await (await fetch(new URL(url, import.meta.url))).text() -:root { - --highlight-bg-color: rgb(180 0 170); - --highlight-selected-bg-color: rgb(0 100 0); -} +// https://github.com/mozilla/pdf.js/blob/642b9a5ae67ef642b9a8808fd9efd447e8c350e2/web/text_layer_builder.css +const textLayerBuilderCSS = await fetchText('vendor/pdfjs/text_layer_builder.css') -@media screen and (forced-colors: active) { - :root { - --highlight-bg-color: Highlight; - --highlight-selected-bg-color: ButtonText; - } -} +// https://github.com/mozilla/pdf.js/blob/642b9a5ae67ef642b9a8808fd9efd447e8c350e2/web/annotation_layer_builder.css +const annotationLayerBuilderCSS = await fetchText('vendor/pdfjs/annotation_layer_builder.css') -.textLayer { - position: absolute; - text-align: initial; - inset: 0; - overflow: hidden; - opacity: 0.25; - line-height: 1; - text-size-adjust: none; - forced-color-adjust: none; - transform-origin: 0 0; - z-index: 2; -} - -.textLayer :is(span, br) { - color: transparent; - position: absolute; - white-space: pre; - cursor: text; - transform-origin: 0% 0%; -} - -/* Only necessary in Google Chrome, see issue 14205, and most unfortunately - * the problem doesn't show up in "text" reference tests. */ -/*#if !MOZCENTRAL*/ -.textLayer span.markedContent { - top: 0; - height: 0; -} -/*#endif*/ - -.textLayer .highlight { - margin: -1px; - padding: 1px; - background-color: var(--highlight-bg-color); - border-radius: 4px; -} - -.textLayer .highlight.appended { - position: initial; -} - -.textLayer .highlight.begin { - border-radius: 4px 0 0 4px; -} - -.textLayer .highlight.end { - border-radius: 0 4px 4px 0; -} - -.textLayer .highlight.middle { - border-radius: 0; -} - -.textLayer .highlight.selected { - background-color: var(--highlight-selected-bg-color); -} - -.textLayer ::selection { - /*#if !MOZCENTRAL*/ - background: blue; - /*#endif*/ - background: AccentColor; /* stylelint-disable-line declaration-block-no-duplicate-properties */ -} - -/* Avoids https://github.com/mozilla/pdf.js/issues/13840 in Chrome */ -/*#if !MOZCENTRAL*/ -.textLayer br::selection { - background: transparent; -} -/*#endif*/ - -.textLayer .endOfContent { - display: block; - position: absolute; - inset: 100% 0 0; - z-index: -1; - cursor: default; - user-select: none; -} - -.textLayer .endOfContent.active { - top: 0; -} -` - -//https://github.com/mozilla/pdf.js/blob/d64f223d034ad74fb62571c3acff566d25eca413/web/annotation_layer_builder.css -const annotationLayerBuilderCSS = ` -/* Copyright 2014 Mozilla Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -:root { - --annotation-unfocused-field-background: url("data:image/svg+xml;charset=UTF-8,"); - --input-focus-border-color: Highlight; - --input-focus-outline: 1px solid Canvas; - --input-unfocused-border-color: transparent; - --input-disabled-border-color: transparent; - --input-hover-border-color: black; - --link-outline: none; -} - -@media screen and (forced-colors: active) { - :root { - --input-focus-border-color: CanvasText; - --input-unfocused-border-color: ActiveText; - --input-disabled-border-color: GrayText; - --input-hover-border-color: Highlight; - --link-outline: 1.5px solid LinkText; - --hcm-highlight-filter: invert(100%); - } - .annotationLayer .textWidgetAnnotation :is(input, textarea):required, - .annotationLayer .choiceWidgetAnnotation select:required, - .annotationLayer - .buttonWidgetAnnotation:is(.checkBox, .radioButton) - input:required { - outline: 1.5px solid selectedItem; - } - - .annotationLayer .linkAnnotation:hover { - backdrop-filter: var(--hcm-highlight-filter); - } - - .annotationLayer .linkAnnotation > a:hover { - opacity: 0 !important; - background: none !important; - box-shadow: none; - } - - .annotationLayer .popupAnnotation .popup { - outline: calc(1.5px * var(--scale-factor)) solid CanvasText !important; - background-color: ButtonFace !important; - color: ButtonText !important; - } - - .annotationLayer .highlightArea:hover::after { - position: absolute; - top: 0; - left: 0; - width: 100%; - height: 100%; - backdrop-filter: var(--hcm-highlight-filter); - content: ""; - pointer-events: none; - } - - .annotationLayer .popupAnnotation.focused .popup { - outline: calc(3px * var(--scale-factor)) solid Highlight !important; - } -} - -.annotationLayer { - position: absolute; - top: 0; - left: 0; - pointer-events: none; - transform-origin: 0 0; - z-index: 3; -} - -.annotationLayer[data-main-rotation="90"] .norotate { - transform: rotate(270deg) translateX(-100%); -} -.annotationLayer[data-main-rotation="180"] .norotate { - transform: rotate(180deg) translate(-100%, -100%); -} -.annotationLayer[data-main-rotation="270"] .norotate { - transform: rotate(90deg) translateY(-100%); -} - -.annotationLayer canvas { - position: absolute; - width: 100%; - height: 100%; - pointer-events: none; -} - -.annotationLayer section { - position: absolute; - text-align: initial; - pointer-events: auto; - box-sizing: border-box; - transform-origin: 0 0; -} - -.annotationLayer .linkAnnotation { - outline: var(--link-outline); -} - -.annotationLayer :is(.linkAnnotation, .buttonWidgetAnnotation.pushButton) > a { - position: absolute; - font-size: 1em; - top: 0; - left: 0; - width: 100%; - height: 100%; -} - -.annotationLayer - :is(.linkAnnotation, .buttonWidgetAnnotation.pushButton):not(.hasBorder) - > a:hover { - opacity: 0.2; - background-color: rgb(255 255 0); - box-shadow: 0 2px 10px rgb(255 255 0); -} - -.annotationLayer .linkAnnotation.hasBorder:hover { - background-color: rgb(255 255 0 / 0.2); -} - -.annotationLayer .hasBorder { - background-size: 100% 100%; -} - -.annotationLayer .textAnnotation img { - position: absolute; - cursor: pointer; - width: 100%; - height: 100%; - top: 0; - left: 0; -} - -.annotationLayer .textWidgetAnnotation :is(input, textarea), -.annotationLayer .choiceWidgetAnnotation select, -.annotationLayer .buttonWidgetAnnotation:is(.checkBox, .radioButton) input { - background-image: var(--annotation-unfocused-field-background); - border: 2px solid var(--input-unfocused-border-color); - box-sizing: border-box; - font: calc(9px * var(--scale-factor)) sans-serif; - height: 100%; - margin: 0; - vertical-align: top; - width: 100%; -} - -.annotationLayer .textWidgetAnnotation :is(input, textarea):required, -.annotationLayer .choiceWidgetAnnotation select:required, -.annotationLayer - .buttonWidgetAnnotation:is(.checkBox, .radioButton) - input:required { - outline: 1.5px solid red; -} - -.annotationLayer .choiceWidgetAnnotation select option { - padding: 0; -} - -.annotationLayer .buttonWidgetAnnotation.radioButton input { - border-radius: 50%; -} - -.annotationLayer .textWidgetAnnotation textarea { - resize: none; -} - -.annotationLayer .textWidgetAnnotation :is(input, textarea)[disabled], -.annotationLayer .choiceWidgetAnnotation select[disabled], -.annotationLayer - .buttonWidgetAnnotation:is(.checkBox, .radioButton) - input[disabled] { - background: none; - border: 2px solid var(--input-disabled-border-color); - cursor: not-allowed; -} - -.annotationLayer .textWidgetAnnotation :is(input, textarea):hover, -.annotationLayer .choiceWidgetAnnotation select:hover, -.annotationLayer - .buttonWidgetAnnotation:is(.checkBox, .radioButton) - input:hover { - border: 2px solid var(--input-hover-border-color); -} -.annotationLayer .textWidgetAnnotation :is(input, textarea):hover, -.annotationLayer .choiceWidgetAnnotation select:hover, -.annotationLayer .buttonWidgetAnnotation.checkBox input:hover { - border-radius: 2px; -} - -.annotationLayer .textWidgetAnnotation :is(input, textarea):focus, -.annotationLayer .choiceWidgetAnnotation select:focus { - background: none; - border: 2px solid var(--input-focus-border-color); - border-radius: 2px; - outline: var(--input-focus-outline); -} - -.annotationLayer .buttonWidgetAnnotation:is(.checkBox, .radioButton) :focus { - background-image: none; - background-color: transparent; -} - -.annotationLayer .buttonWidgetAnnotation.checkBox :focus { - border: 2px solid var(--input-focus-border-color); - border-radius: 2px; - outline: var(--input-focus-outline); -} - -.annotationLayer .buttonWidgetAnnotation.radioButton :focus { - border: 2px solid var(--input-focus-border-color); - outline: var(--input-focus-outline); -} - -.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::before, -.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::after, -.annotationLayer .buttonWidgetAnnotation.radioButton input:checked::before { - background-color: CanvasText; - content: ""; - display: block; - position: absolute; -} - -.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::before, -.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::after { - height: 80%; - left: 45%; - width: 1px; -} - -.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::before { - transform: rotate(45deg); -} - -.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::after { - transform: rotate(-45deg); -} - -.annotationLayer .buttonWidgetAnnotation.radioButton input:checked::before { - border-radius: 50%; - height: 50%; - left: 30%; - top: 20%; - width: 50%; -} - -.annotationLayer .textWidgetAnnotation input.comb { - font-family: monospace; - padding-left: 2px; - padding-right: 0; -} - -.annotationLayer .textWidgetAnnotation input.comb:focus { - /* - * Letter spacing is placed on the right side of each character. Hence, the - * letter spacing of the last character may be placed outside the visible - * area, causing horizontal scrolling. We avoid this by extending the width - * when the element has focus and revert this when it loses focus. - */ - width: 103%; -} - -.annotationLayer .buttonWidgetAnnotation:is(.checkBox, .radioButton) input { - appearance: none; -} - -.annotationLayer .fileAttachmentAnnotation .popupTriggerArea { - height: 100%; - width: 100%; -} - -.annotationLayer .popupAnnotation { - position: absolute; - font-size: calc(9px * var(--scale-factor)); - pointer-events: none; - width: max-content; - max-width: 45%; - height: auto; -} - -.annotationLayer .popup { - background-color: rgb(255 255 153); - box-shadow: 0 calc(2px * var(--scale-factor)) calc(5px * var(--scale-factor)) - rgb(136 136 136); - border-radius: calc(2px * var(--scale-factor)); - outline: 1.5px solid rgb(255 255 74); - padding: calc(6px * var(--scale-factor)); - cursor: pointer; - font: message-box; - white-space: normal; - word-wrap: break-word; - pointer-events: auto; -} - -.annotationLayer .popupAnnotation.focused .popup { - outline-width: 3px; -} - -.annotationLayer .popup * { - font-size: calc(9px * var(--scale-factor)); -} - -.annotationLayer .popup > .header { - display: inline-block; -} - -.annotationLayer .popup > .header h1 { - display: inline; -} - -.annotationLayer .popup > .header .popupDate { - display: inline-block; - margin-left: calc(5px * var(--scale-factor)); - width: fit-content; -} - -.annotationLayer .popupContent { - border-top: 1px solid rgb(51 51 51); - margin-top: calc(2px * var(--scale-factor)); - padding-top: calc(2px * var(--scale-factor)); -} - -.annotationLayer .richText > * { - white-space: pre-wrap; - font-size: calc(9px * var(--scale-factor)); -} - -.annotationLayer .popupTriggerArea { - cursor: pointer; -} - -.annotationLayer section svg { - position: absolute; - width: 100%; - height: 100%; - top: 0; - left: 0; -} - -.annotationLayer .annotationTextContent { - position: absolute; - width: 100%; - height: 100%; - opacity: 0; - color: transparent; - user-select: none; - pointer-events: none; -} - -.annotationLayer .annotationTextContent span { - width: 100%; - display: inline-block; -} - -.annotationLayer svg.quadrilateralsContainer { - contain: strict; - width: 0; - height: 0; - position: absolute; - top: 0; - left: 0; - z-index: -1; -} -` - -const renderPage = async (page, getImageBlob) => { - - const naturalPdfSize = page.getViewport({ scale: 1 }) - const naturalPdfRatio = naturalPdfSize.width / naturalPdfSize.height - const appRatio = innerWidth / innerHeight - const pdfToAppResolutionRatio = appRatio / naturalPdfRatio - - const scale = devicePixelRatio * pdfToAppResolutionRatio +const render = async (page, doc, zoom) => { + const scale = zoom * devicePixelRatio + doc.documentElement.style.transform = `scale(${1 / devicePixelRatio})` + doc.documentElement.style.transformOrigin = 'top left' + doc.documentElement.style.setProperty('--scale-factor', scale) const viewport = page.getViewport({ scale }) + // for some reason must use `document`'s canvas + // using a canvas in `doc` results in tofu const canvas = document.createElement('canvas') canvas.height = viewport.height canvas.width = viewport.width const canvasContext = canvas.getContext('2d') await page.render({ canvasContext, viewport }).promise - const blob = await new Promise(resolve => canvas.toBlob(resolve)) - if (getImageBlob) return blob + doc.querySelector('#canvas').replaceChildren(doc.adoptNode(canvas)) - /* - // with the SVG backend - const operatorList = await page.getOperatorList() - const svgGraphics = new pdfjsLib.SVGGraphics(page.commonObjs, page.objs) - const svg = await svgGraphics.getSVG(operatorList, viewport) - const str = new XMLSerializer().serializeToString(svg) - const blob = new Blob([str], { type: 'image/svg+xml' }) - */ - - const container = document.createElement('div') - container.classList.add('textLayer') - await pdfjsLib.renderTextLayer({ - textContentSource: await page.getTextContent(), + const container = doc.querySelector('.textLayer') + const textLayer = new pdfjsLib.TextLayer({ + textContentSource: await page.streamTextContent(), container, viewport, - }).promise + }) + await textLayer.render() - const div = document.createElement('div') - div.classList.add('annotationLayer') + // hide "offscreen" canvases appended to docuemnt when rendering text layer + // https://github.com/mozilla/pdf.js/blob/642b9a5ae67ef642b9a8808fd9efd447e8c350e2/web/pdf_viewer.css#L51-L58 + for (const canvas of document.querySelectorAll('.hiddenCanvasElement')) + Object.assign(canvas.style, { + position: 'absolute', + top: '0', + left: '0', + width: '0', + height: '0', + display: 'none', + }) + + const div = doc.querySelector('.annotationLayer') await new pdfjsLib.AnnotationLayer({ page, viewport, div }).render({ annotations: await page.getAnnotations(), linkService: { @@ -536,15 +55,24 @@ const renderPage = async (page, getImageBlob) => { addLinkAttributes: (link, url) => link.href = url, }, }) +} - const src = URL.createObjectURL(blob) - const url = URL.createObjectURL(new Blob([` +const renderPage = async (page, getImageBlob) => { + const viewport = page.getViewport({ scale: 1 }) + if (getImageBlob) { + const canvas = document.createElement('canvas') + canvas.height = viewport.height + canvas.width = viewport.width + const canvasContext = canvas.getContext('2d') + await page.render({ canvasContext, viewport }).promise + return new Promise(resolve => canvas.toBlob(resolve)) + } + const src = URL.createObjectURL(new Blob([` + + - - ${container.outerHTML} - ${div.outerHTML} +
+
+
`], { type: 'text/html' })) - return url + const onZoom = ({ doc, scale }) => render(page, doc, scale) + return { src, onZoom } } const makeTOCItem = item => ({ @@ -592,7 +121,6 @@ export const makePDF = async file => { }, size: 1000, })) - book.sections[0].pageSpread = 'right' book.isExternal = uri => /^\w+:/i.test(uri) book.resolveHref = async href => { const parsed = JSON.parse(href) @@ -610,5 +138,6 @@ export const makePDF = async file => { } book.getTOCFragment = doc => doc.documentElement book.getCover = async () => renderPage(await pdf.getPage(1), true) + book.destroy = () => pdf.destroy() return book } diff --git a/reader.html b/reader.html index 5bc7765..18d6b5b 100644 --- a/reader.html +++ b/reader.html @@ -301,5 +301,4 @@ body { - diff --git a/vendor/pdfjs/annotation_layer_builder.css b/vendor/pdfjs/annotation_layer_builder.css new file mode 100644 index 0000000..3047adb --- /dev/null +++ b/vendor/pdfjs/annotation_layer_builder.css @@ -0,0 +1,389 @@ +/* Copyright 2014 Mozilla Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +.annotationLayer { + --annotation-unfocused-field-background: url("data:image/svg+xml;charset=UTF-8,"); + --input-focus-border-color: Highlight; + --input-focus-outline: 1px solid Canvas; + --input-unfocused-border-color: transparent; + --input-disabled-border-color: transparent; + --input-hover-border-color: black; + --link-outline: none; + + @media screen and (forced-colors: active) { + --input-focus-border-color: CanvasText; + --input-unfocused-border-color: ActiveText; + --input-disabled-border-color: GrayText; + --input-hover-border-color: Highlight; + --link-outline: 1.5px solid LinkText; + + .textWidgetAnnotation :is(input, textarea):required, + .choiceWidgetAnnotation select:required, + .buttonWidgetAnnotation:is(.checkBox, .radioButton) input:required { + outline: 1.5px solid selectedItem; + } + + .linkAnnotation { + outline: var(--link-outline); + + &:hover { + backdrop-filter: var(--hcm-highlight-filter); + } + + & > a:hover { + opacity: 0 !important; + background: none !important; + box-shadow: none; + } + } + + .popupAnnotation .popup { + outline: calc(1.5px * var(--scale-factor)) solid CanvasText !important; + background-color: ButtonFace !important; + color: ButtonText !important; + } + + .highlightArea:hover::after { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + backdrop-filter: var(--hcm-highlight-filter); + content: ""; + pointer-events: none; + } + + .popupAnnotation.focused .popup { + outline: calc(3px * var(--scale-factor)) solid Highlight !important; + } + } + + position: absolute; + top: 0; + left: 0; + pointer-events: none; + transform-origin: 0 0; + + &[data-main-rotation="90"] .norotate { + transform: rotate(270deg) translateX(-100%); + } + &[data-main-rotation="180"] .norotate { + transform: rotate(180deg) translate(-100%, -100%); + } + &[data-main-rotation="270"] .norotate { + transform: rotate(90deg) translateY(-100%); + } + + &.disabled { + section, + .popup { + pointer-events: none; + } + } + + .annotationContent { + position: absolute; + width: 100%; + height: 100%; + pointer-events: none; + + &.freetext { + background: transparent; + border: none; + inset: 0; + overflow: visible; + white-space: nowrap; + font: 10px sans-serif; + line-height: 1.35; + user-select: none; + } + } + + section { + position: absolute; + text-align: initial; + pointer-events: auto; + box-sizing: border-box; + transform-origin: 0 0; + + &:has(div.annotationContent) { + canvas.annotationContent { + display: none; + } + } + } + + .textLayer.selecting ~ & section { + pointer-events: none; + } + + :is(.linkAnnotation, .buttonWidgetAnnotation.pushButton) > a { + position: absolute; + font-size: 1em; + top: 0; + left: 0; + width: 100%; + height: 100%; + } + + :is(.linkAnnotation, .buttonWidgetAnnotation.pushButton):not(.hasBorder) + > a:hover { + opacity: 0.2; + background-color: rgb(255 255 0); + box-shadow: 0 2px 10px rgb(255 255 0); + } + + .linkAnnotation.hasBorder:hover { + background-color: rgb(255 255 0 / 0.2); + } + + .hasBorder { + background-size: 100% 100%; + } + + .textAnnotation img { + position: absolute; + cursor: pointer; + width: 100%; + height: 100%; + top: 0; + left: 0; + } + + .textWidgetAnnotation :is(input, textarea), + .choiceWidgetAnnotation select, + .buttonWidgetAnnotation:is(.checkBox, .radioButton) input { + background-image: var(--annotation-unfocused-field-background); + border: 2px solid var(--input-unfocused-border-color); + box-sizing: border-box; + font: calc(9px * var(--scale-factor)) sans-serif; + height: 100%; + margin: 0; + vertical-align: top; + width: 100%; + } + + .textWidgetAnnotation :is(input, textarea):required, + .choiceWidgetAnnotation select:required, + .buttonWidgetAnnotation:is(.checkBox, .radioButton) input:required { + outline: 1.5px solid red; + } + + .choiceWidgetAnnotation select option { + padding: 0; + } + + .buttonWidgetAnnotation.radioButton input { + border-radius: 50%; + } + + .textWidgetAnnotation textarea { + resize: none; + } + + .textWidgetAnnotation :is(input, textarea)[disabled], + .choiceWidgetAnnotation select[disabled], + .buttonWidgetAnnotation:is(.checkBox, .radioButton) input[disabled] { + background: none; + border: 2px solid var(--input-disabled-border-color); + cursor: not-allowed; + } + + .textWidgetAnnotation :is(input, textarea):hover, + .choiceWidgetAnnotation select:hover, + .buttonWidgetAnnotation:is(.checkBox, .radioButton) input:hover { + border: 2px solid var(--input-hover-border-color); + } + .textWidgetAnnotation :is(input, textarea):hover, + .choiceWidgetAnnotation select:hover, + .buttonWidgetAnnotation.checkBox input:hover { + border-radius: 2px; + } + + .textWidgetAnnotation :is(input, textarea):focus, + .choiceWidgetAnnotation select:focus { + background: none; + border: 2px solid var(--input-focus-border-color); + border-radius: 2px; + outline: var(--input-focus-outline); + } + + .buttonWidgetAnnotation:is(.checkBox, .radioButton) :focus { + background-image: none; + background-color: transparent; + } + + .buttonWidgetAnnotation.checkBox :focus { + border: 2px solid var(--input-focus-border-color); + border-radius: 2px; + outline: var(--input-focus-outline); + } + + .buttonWidgetAnnotation.radioButton :focus { + border: 2px solid var(--input-focus-border-color); + outline: var(--input-focus-outline); + } + + .buttonWidgetAnnotation.checkBox input:checked::before, + .buttonWidgetAnnotation.checkBox input:checked::after, + .buttonWidgetAnnotation.radioButton input:checked::before { + background-color: CanvasText; + content: ""; + display: block; + position: absolute; + } + + .buttonWidgetAnnotation.checkBox input:checked::before, + .buttonWidgetAnnotation.checkBox input:checked::after { + height: 80%; + left: 45%; + width: 1px; + } + + .buttonWidgetAnnotation.checkBox input:checked::before { + transform: rotate(45deg); + } + + .buttonWidgetAnnotation.checkBox input:checked::after { + transform: rotate(-45deg); + } + + .buttonWidgetAnnotation.radioButton input:checked::before { + border-radius: 50%; + height: 50%; + left: 25%; + top: 25%; + width: 50%; + } + + .textWidgetAnnotation input.comb { + font-family: monospace; + padding-left: 2px; + padding-right: 0; + } + + .textWidgetAnnotation input.comb:focus { + /* + * Letter spacing is placed on the right side of each character. Hence, the + * letter spacing of the last character may be placed outside the visible + * area, causing horizontal scrolling. We avoid this by extending the width + * when the element has focus and revert this when it loses focus. + */ + width: 103%; + } + + .buttonWidgetAnnotation:is(.checkBox, .radioButton) input { + appearance: none; + } + + .fileAttachmentAnnotation .popupTriggerArea { + height: 100%; + width: 100%; + } + + .popupAnnotation { + position: absolute; + font-size: calc(9px * var(--scale-factor)); + pointer-events: none; + width: max-content; + max-width: 45%; + height: auto; + } + + .popup { + background-color: rgb(255 255 153); + box-shadow: 0 calc(2px * var(--scale-factor)) + calc(5px * var(--scale-factor)) rgb(136 136 136); + border-radius: calc(2px * var(--scale-factor)); + outline: 1.5px solid rgb(255 255 74); + padding: calc(6px * var(--scale-factor)); + cursor: pointer; + font: message-box; + white-space: normal; + word-wrap: break-word; + pointer-events: auto; + } + + .popupAnnotation.focused .popup { + outline-width: 3px; + } + + .popup * { + font-size: calc(9px * var(--scale-factor)); + } + + .popup > .header { + display: inline-block; + } + + .popup > .header h1 { + display: inline; + } + + .popup > .header .popupDate { + display: inline-block; + margin-left: calc(5px * var(--scale-factor)); + width: fit-content; + } + + .popupContent { + border-top: 1px solid rgb(51 51 51); + margin-top: calc(2px * var(--scale-factor)); + padding-top: calc(2px * var(--scale-factor)); + } + + .richText > * { + white-space: pre-wrap; + font-size: calc(9px * var(--scale-factor)); + } + + .popupTriggerArea { + cursor: pointer; + } + + section svg { + position: absolute; + width: 100%; + height: 100%; + top: 0; + left: 0; + } + + .annotationTextContent { + position: absolute; + width: 100%; + height: 100%; + opacity: 0; + color: transparent; + user-select: none; + pointer-events: none; + + span { + width: 100%; + display: inline-block; + } + } + + svg.quadrilateralsContainer { + contain: strict; + width: 0; + height: 0; + position: absolute; + top: 0; + left: 0; + z-index: -1; + } +} diff --git a/vendor/pdfjs/pdf.js b/vendor/pdfjs/pdf.mjs similarity index 66% rename from vendor/pdfjs/pdf.js rename to vendor/pdfjs/pdf.mjs index 4acf16b..cb0a187 100644 --- a/vendor/pdfjs/pdf.js +++ b/vendor/pdfjs/pdf.mjs @@ -2,7 +2,7 @@ * @licstart The following is the entire license notice for the * JavaScript code in this page * - * Copyright 2023 Mozilla Foundation + * Copyright 2024 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,65 +20,85 @@ * JavaScript code in this page */ -(function webpackUniversalModuleDefinition(root, factory) { - if(typeof exports === 'object' && typeof module === 'object') - module.exports = root.pdfjsLib = factory(); - else if(typeof define === 'function' && define.amd) - define("pdfjs-dist/build/pdf", [], () => { return (root.pdfjsLib = factory()); }); - else if(typeof exports === 'object') - exports["pdfjs-dist/build/pdf"] = root.pdfjsLib = factory(); - else - root["pdfjs-dist/build/pdf"] = root.pdfjsLib = factory(); -})(globalThis, () => { -return /******/ (() => { // webpackBootstrap -/******/ "use strict"; -/******/ var __webpack_modules__ = ([ -/* 0 */, -/* 1 */ -/***/ ((__unused_webpack_module, exports) => { +/******/ // The require scope +/******/ var __webpack_require__ = {}; +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/define property getters */ +/******/ (() => { +/******/ // define getter functions for harmony exports +/******/ __webpack_require__.d = (exports, definition) => { +/******/ for(var key in definition) { +/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { +/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); +/******/ } +/******/ } +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/hasOwnProperty shorthand */ +/******/ (() => { +/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +/******/ })(); +/******/ +/************************************************************************/ +var __webpack_exports__ = globalThis.pdfjsLib = {}; +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + AbortException: () => (/* reexport */ AbortException), + AnnotationEditorLayer: () => (/* reexport */ AnnotationEditorLayer), + AnnotationEditorParamsType: () => (/* reexport */ AnnotationEditorParamsType), + AnnotationEditorType: () => (/* reexport */ AnnotationEditorType), + AnnotationEditorUIManager: () => (/* reexport */ AnnotationEditorUIManager), + AnnotationLayer: () => (/* reexport */ AnnotationLayer), + AnnotationMode: () => (/* reexport */ AnnotationMode), + CMapCompressionType: () => (/* reexport */ CMapCompressionType), + ColorPicker: () => (/* reexport */ ColorPicker), + DOMSVGFactory: () => (/* reexport */ DOMSVGFactory), + DrawLayer: () => (/* reexport */ DrawLayer), + FeatureTest: () => (/* reexport */ util_FeatureTest), + GlobalWorkerOptions: () => (/* reexport */ GlobalWorkerOptions), + ImageKind: () => (/* reexport */ util_ImageKind), + InvalidPDFException: () => (/* reexport */ InvalidPDFException), + MissingPDFException: () => (/* reexport */ MissingPDFException), + OPS: () => (/* reexport */ OPS), + PDFDataRangeTransport: () => (/* reexport */ PDFDataRangeTransport), + PDFDateString: () => (/* reexport */ PDFDateString), + PDFWorker: () => (/* reexport */ PDFWorker), + PasswordResponses: () => (/* reexport */ PasswordResponses), + PermissionFlag: () => (/* reexport */ PermissionFlag), + PixelsPerInch: () => (/* reexport */ PixelsPerInch), + RenderingCancelledException: () => (/* reexport */ RenderingCancelledException), + TextLayer: () => (/* reexport */ TextLayer), + UnexpectedResponseException: () => (/* reexport */ UnexpectedResponseException), + Util: () => (/* reexport */ Util), + VerbosityLevel: () => (/* reexport */ VerbosityLevel), + XfaLayer: () => (/* reexport */ XfaLayer), + build: () => (/* reexport */ build), + createValidAbsoluteUrl: () => (/* reexport */ createValidAbsoluteUrl), + fetchData: () => (/* reexport */ fetchData), + getDocument: () => (/* reexport */ getDocument), + getFilenameFromUrl: () => (/* reexport */ getFilenameFromUrl), + getPdfFilenameFromUrl: () => (/* reexport */ getPdfFilenameFromUrl), + getXfaPageViewport: () => (/* reexport */ getXfaPageViewport), + isDataScheme: () => (/* reexport */ isDataScheme), + isPdfFile: () => (/* reexport */ isPdfFile), + noContextMenu: () => (/* reexport */ noContextMenu), + normalizeUnicode: () => (/* reexport */ normalizeUnicode), + setLayerDimensions: () => (/* reexport */ setLayerDimensions), + shadow: () => (/* reexport */ shadow), + version: () => (/* reexport */ version) +}); - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.VerbosityLevel = exports.Util = exports.UnknownErrorException = exports.UnexpectedResponseException = exports.TextRenderingMode = exports.RenderingIntentFlag = exports.PromiseCapability = exports.PermissionFlag = exports.PasswordResponses = exports.PasswordException = exports.PageActionEventType = exports.OPS = exports.MissingPDFException = exports.MAX_IMAGE_SIZE_TO_CACHE = exports.LINE_FACTOR = exports.LINE_DESCENT_FACTOR = exports.InvalidPDFException = exports.ImageKind = exports.IDENTITY_MATRIX = exports.FormatError = exports.FeatureTest = exports.FONT_IDENTITY_MATRIX = exports.DocumentActionEventType = exports.CMapCompressionType = exports.BaseException = exports.BASELINE_FACTOR = exports.AnnotationType = exports.AnnotationReplyType = exports.AnnotationPrefix = exports.AnnotationMode = exports.AnnotationFlag = exports.AnnotationFieldFlag = exports.AnnotationEditorType = exports.AnnotationEditorPrefix = exports.AnnotationEditorParamsType = exports.AnnotationBorderStyleType = exports.AnnotationActionEventType = exports.AbortException = void 0; -exports.assert = assert; -exports.bytesToString = bytesToString; -exports.createValidAbsoluteUrl = createValidAbsoluteUrl; -exports.getModificationDate = getModificationDate; -exports.getUuid = getUuid; -exports.getVerbosityLevel = getVerbosityLevel; -exports.info = info; -exports.isArrayBuffer = isArrayBuffer; -exports.isArrayEqual = isArrayEqual; -exports.isNodeJS = void 0; -exports.normalizeUnicode = normalizeUnicode; -exports.objectFromMap = objectFromMap; -exports.objectSize = objectSize; -exports.setVerbosityLevel = setVerbosityLevel; -exports.shadow = shadow; -exports.string32 = string32; -exports.stringToBytes = stringToBytes; -exports.stringToPDFString = stringToPDFString; -exports.stringToUTF8String = stringToUTF8String; -exports.unreachable = unreachable; -exports.utf8StringToString = utf8StringToString; -exports.warn = warn; +;// CONCATENATED MODULE: ./src/shared/util.js const isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser"); -exports.isNodeJS = isNodeJS; const IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0]; -exports.IDENTITY_MATRIX = IDENTITY_MATRIX; const FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0]; -exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX; const MAX_IMAGE_SIZE_TO_CACHE = 10e6; -exports.MAX_IMAGE_SIZE_TO_CACHE = MAX_IMAGE_SIZE_TO_CACHE; const LINE_FACTOR = 1.35; -exports.LINE_FACTOR = LINE_FACTOR; const LINE_DESCENT_FACTOR = 0.35; -exports.LINE_DESCENT_FACTOR = LINE_DESCENT_FACTOR; const BASELINE_FACTOR = LINE_DESCENT_FACTOR / LINE_FACTOR; -exports.BASELINE_FACTOR = BASELINE_FACTOR; const RenderingIntentFlag = { ANY: 0x01, DISPLAY: 0x02, @@ -87,26 +107,24 @@ const RenderingIntentFlag = { ANNOTATIONS_FORMS: 0x10, ANNOTATIONS_STORAGE: 0x20, ANNOTATIONS_DISABLE: 0x40, + IS_EDITING: 0x80, OPLIST: 0x100 }; -exports.RenderingIntentFlag = RenderingIntentFlag; const AnnotationMode = { DISABLE: 0, ENABLE: 1, ENABLE_FORMS: 2, ENABLE_STORAGE: 3 }; -exports.AnnotationMode = AnnotationMode; const AnnotationEditorPrefix = "pdfjs_internal_editor_"; -exports.AnnotationEditorPrefix = AnnotationEditorPrefix; const AnnotationEditorType = { DISABLE: -1, NONE: 0, FREETEXT: 3, + HIGHLIGHT: 9, STAMP: 13, INK: 15 }; -exports.AnnotationEditorType = AnnotationEditorType; const AnnotationEditorParamsType = { RESIZE: 1, CREATE: 2, @@ -115,9 +133,13 @@ const AnnotationEditorParamsType = { FREETEXT_OPACITY: 13, INK_COLOR: 21, INK_THICKNESS: 22, - INK_OPACITY: 23 + INK_OPACITY: 23, + HIGHLIGHT_COLOR: 31, + HIGHLIGHT_DEFAULT_COLOR: 32, + HIGHLIGHT_THICKNESS: 33, + HIGHLIGHT_FREE: 34, + HIGHLIGHT_SHOW_ALL: 35 }; -exports.AnnotationEditorParamsType = AnnotationEditorParamsType; const PermissionFlag = { PRINT: 0x04, MODIFY_CONTENTS: 0x08, @@ -128,7 +150,6 @@ const PermissionFlag = { ASSEMBLE: 0x400, PRINT_HIGH_QUALITY: 0x800 }; -exports.PermissionFlag = PermissionFlag; const TextRenderingMode = { FILL: 0, STROKE: 1, @@ -141,13 +162,11 @@ const TextRenderingMode = { FILL_STROKE_MASK: 3, ADD_TO_PATH_FLAG: 4 }; -exports.TextRenderingMode = TextRenderingMode; -const ImageKind = { +const util_ImageKind = { GRAYSCALE_1BPP: 1, RGB_24BPP: 2, RGBA_32BPP: 3 }; -exports.ImageKind = ImageKind; const AnnotationType = { TEXT: 1, LINK: 2, @@ -176,12 +195,10 @@ const AnnotationType = { THREED: 25, REDACT: 26 }; -exports.AnnotationType = AnnotationType; const AnnotationReplyType = { GROUP: "Group", REPLY: "R" }; -exports.AnnotationReplyType = AnnotationReplyType; const AnnotationFlag = { INVISIBLE: 0x01, HIDDEN: 0x02, @@ -194,7 +211,6 @@ const AnnotationFlag = { TOGGLENOVIEW: 0x100, LOCKEDCONTENTS: 0x200 }; -exports.AnnotationFlag = AnnotationFlag; const AnnotationFieldFlag = { READONLY: 0x0000001, REQUIRED: 0x0000002, @@ -216,7 +232,6 @@ const AnnotationFieldFlag = { RADIOSINUNISON: 0x2000000, COMMITONSELCHANGE: 0x4000000 }; -exports.AnnotationFieldFlag = AnnotationFieldFlag; const AnnotationBorderStyleType = { SOLID: 1, DASHED: 2, @@ -224,7 +239,6 @@ const AnnotationBorderStyleType = { INSET: 4, UNDERLINE: 5 }; -exports.AnnotationBorderStyleType = AnnotationBorderStyleType; const AnnotationActionEventType = { E: "Mouse Enter", X: "Mouse Exit", @@ -241,7 +255,6 @@ const AnnotationActionEventType = { V: "Validate", C: "Calculate" }; -exports.AnnotationActionEventType = AnnotationActionEventType; const DocumentActionEventType = { WC: "WillClose", WS: "WillSave", @@ -249,23 +262,19 @@ const DocumentActionEventType = { WP: "WillPrint", DP: "DidPrint" }; -exports.DocumentActionEventType = DocumentActionEventType; const PageActionEventType = { O: "PageOpen", C: "PageClose" }; -exports.PageActionEventType = PageActionEventType; const VerbosityLevel = { ERRORS: 0, WARNINGS: 1, INFOS: 5 }; -exports.VerbosityLevel = VerbosityLevel; const CMapCompressionType = { NONE: 0, BINARY: 1 }; -exports.CMapCompressionType = CMapCompressionType; const OPS = { dependency: 1, setLineWidth: 2, @@ -354,14 +363,14 @@ const OPS = { paintImageXObjectRepeat: 88, paintImageMaskXObjectRepeat: 89, paintSolidColorImageMask: 90, - constructPath: 91 + constructPath: 91, + setStrokeTransparent: 92, + setFillTransparent: 93 }; -exports.OPS = OPS; const PasswordResponses = { NEED_PASSWORD: 1, INCORRECT_PASSWORD: 2 }; -exports.PasswordResponses = PasswordResponses; let verbosity = VerbosityLevel.WARNINGS; function setVerbosityLevel(level) { if (Number.isInteger(level)) { @@ -437,9 +446,6 @@ function shadow(obj, prop, value, nonSerializable = false) { } const BaseException = function BaseExceptionClosure() { function BaseException(message, name) { - if (this.constructor === BaseException) { - unreachable("Cannot initialize BaseException."); - } this.message = message; this.name = name; } @@ -447,52 +453,44 @@ const BaseException = function BaseExceptionClosure() { BaseException.constructor = BaseException; return BaseException; }(); -exports.BaseException = BaseException; class PasswordException extends BaseException { constructor(msg, code) { super(msg, "PasswordException"); this.code = code; } } -exports.PasswordException = PasswordException; class UnknownErrorException extends BaseException { constructor(msg, details) { super(msg, "UnknownErrorException"); this.details = details; } } -exports.UnknownErrorException = UnknownErrorException; class InvalidPDFException extends BaseException { constructor(msg) { super(msg, "InvalidPDFException"); } } -exports.InvalidPDFException = InvalidPDFException; class MissingPDFException extends BaseException { constructor(msg) { super(msg, "MissingPDFException"); } } -exports.MissingPDFException = MissingPDFException; class UnexpectedResponseException extends BaseException { constructor(msg, status) { super(msg, "UnexpectedResponseException"); this.status = status; } } -exports.UnexpectedResponseException = UnexpectedResponseException; class FormatError extends BaseException { constructor(msg) { super(msg, "FormatError"); } } -exports.FormatError = FormatError; class AbortException extends BaseException { constructor(msg) { super(msg, "AbortException"); } } -exports.AbortException = AbortException; function bytesToString(bytes) { if (typeof bytes !== "object" || bytes?.length === undefined) { unreachable("Invalid argument for bytesToString"); @@ -548,7 +546,7 @@ function isEvalSupported() { return false; } } -class FeatureTest { +class util_FeatureTest { static get isLittleEndian() { return shadow(this, "isLittleEndian", isLittleEndian()); } @@ -559,23 +557,20 @@ class FeatureTest { return shadow(this, "isOffscreenCanvasSupported", typeof OffscreenCanvas !== "undefined"); } static get platform() { - if (typeof navigator === "undefined") { + if (typeof navigator !== "undefined" && typeof navigator?.platform === "string") { return shadow(this, "platform", { - isWin: false, - isMac: false + isMac: navigator.platform.includes("Mac") }); } return shadow(this, "platform", { - isWin: navigator.platform.includes("Win"), - isMac: navigator.platform.includes("Mac") + isMac: false }); } static get isCSSRoundSupported() { return shadow(this, "isCSSRoundSupported", globalThis.CSS?.supports?.("width: round(1.5px, 1px)")); } } -exports.FeatureTest = FeatureTest; -const hexNumbers = [...Array(256).keys()].map(n => n.toString(16).padStart(2, "0")); +const hexNumbers = Array.from(Array(256).keys(), n => n.toString(16).padStart(2, "0")); class Util { static makeHexColor(r, g, b) { return `#${hexNumbers[r]}${hexNumbers[g]}${hexNumbers[b]}`; @@ -585,43 +580,43 @@ class Util { if (transform[0]) { if (transform[0] < 0) { temp = minMax[0]; - minMax[0] = minMax[1]; - minMax[1] = temp; + minMax[0] = minMax[2]; + minMax[2] = temp; } minMax[0] *= transform[0]; - minMax[1] *= transform[0]; + minMax[2] *= transform[0]; if (transform[3] < 0) { - temp = minMax[2]; - minMax[2] = minMax[3]; + temp = minMax[1]; + minMax[1] = minMax[3]; minMax[3] = temp; } - minMax[2] *= transform[3]; + minMax[1] *= transform[3]; minMax[3] *= transform[3]; } else { temp = minMax[0]; - minMax[0] = minMax[2]; - minMax[2] = temp; - temp = minMax[1]; - minMax[1] = minMax[3]; + minMax[0] = minMax[1]; + minMax[1] = temp; + temp = minMax[2]; + minMax[2] = minMax[3]; minMax[3] = temp; if (transform[1] < 0) { - temp = minMax[2]; - minMax[2] = minMax[3]; + temp = minMax[1]; + minMax[1] = minMax[3]; minMax[3] = temp; } - minMax[2] *= transform[1]; + minMax[1] *= transform[1]; minMax[3] *= transform[1]; if (transform[2] < 0) { temp = minMax[0]; - minMax[0] = minMax[1]; - minMax[1] = temp; + minMax[0] = minMax[2]; + minMax[2] = temp; } minMax[0] *= transform[2]; - minMax[1] *= transform[2]; + minMax[2] *= transform[2]; } minMax[0] += transform[4]; - minMax[1] += transform[4]; - minMax[2] += transform[5]; + minMax[1] += transform[5]; + minMax[2] += transform[4]; minMax[3] += transform[5]; } static transform(m1, m2) { @@ -686,70 +681,64 @@ class Util { } return [xLow, yLow, xHigh, yHigh]; } - static bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3) { - const tvalues = [], - bounds = [[], []]; - let a, b, c, t, t1, t2, b2ac, sqrtb2ac; - for (let i = 0; i < 2; ++i) { - if (i === 0) { - b = 6 * x0 - 12 * x1 + 6 * x2; - a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3; - c = 3 * x1 - 3 * x0; - } else { - b = 6 * y0 - 12 * y1 + 6 * y2; - a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3; - c = 3 * y1 - 3 * y0; - } - if (Math.abs(a) < 1e-12) { - if (Math.abs(b) < 1e-12) { - continue; - } - t = -c / b; - if (0 < t && t < 1) { - tvalues.push(t); - } - continue; - } - b2ac = b * b - 4 * c * a; - sqrtb2ac = Math.sqrt(b2ac); - if (b2ac < 0) { - continue; - } - t1 = (-b + sqrtb2ac) / (2 * a); - if (0 < t1 && t1 < 1) { - tvalues.push(t1); - } - t2 = (-b - sqrtb2ac) / (2 * a); - if (0 < t2 && t2 < 1) { - tvalues.push(t2); - } + static #getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, t, minMax) { + if (t <= 0 || t >= 1) { + return; } - let j = tvalues.length, - mt; - const jlen = j; - while (j--) { - t = tvalues[j]; - mt = 1 - t; - bounds[0][j] = mt * mt * mt * x0 + 3 * mt * mt * t * x1 + 3 * mt * t * t * x2 + t * t * t * x3; - bounds[1][j] = mt * mt * mt * y0 + 3 * mt * mt * t * y1 + 3 * mt * t * t * y2 + t * t * t * y3; + const mt = 1 - t; + const tt = t * t; + const ttt = tt * t; + const x = mt * (mt * (mt * x0 + 3 * t * x1) + 3 * tt * x2) + ttt * x3; + const y = mt * (mt * (mt * y0 + 3 * t * y1) + 3 * tt * y2) + ttt * y3; + minMax[0] = Math.min(minMax[0], x); + minMax[1] = Math.min(minMax[1], y); + minMax[2] = Math.max(minMax[2], x); + minMax[3] = Math.max(minMax[3], y); + } + static #getExtremum(x0, x1, x2, x3, y0, y1, y2, y3, a, b, c, minMax) { + if (Math.abs(a) < 1e-12) { + if (Math.abs(b) >= 1e-12) { + this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, -c / b, minMax); + } + return; } - bounds[0][jlen] = x0; - bounds[1][jlen] = y0; - bounds[0][jlen + 1] = x3; - bounds[1][jlen + 1] = y3; - bounds[0].length = bounds[1].length = jlen + 2; - return [Math.min(...bounds[0]), Math.min(...bounds[1]), Math.max(...bounds[0]), Math.max(...bounds[1])]; + const delta = b ** 2 - 4 * c * a; + if (delta < 0) { + return; + } + const sqrtDelta = Math.sqrt(delta); + const a2 = 2 * a; + this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, (-b + sqrtDelta) / a2, minMax); + this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, (-b - sqrtDelta) / a2, minMax); + } + static bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3, minMax) { + if (minMax) { + minMax[0] = Math.min(minMax[0], x0, x3); + minMax[1] = Math.min(minMax[1], y0, y3); + minMax[2] = Math.max(minMax[2], x0, x3); + minMax[3] = Math.max(minMax[3], y0, y3); + } else { + minMax = [Math.min(x0, x3), Math.min(y0, y3), Math.max(x0, x3), Math.max(y0, y3)]; + } + 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); + 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); + return minMax; } } -exports.Util = Util; -const PDFStringTranslateTable = [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]; +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])); function stringToPDFString(str) { if (str[0] >= "\xEF") { let encoding; if (str[0] === "\xFE" && str[1] === "\xFF") { encoding = "utf-16be"; + if (str.length % 2 === 1) { + str = str.slice(0, -1); + } } else if (str[0] === "\xFF" && str[1] === "\xFE") { encoding = "utf-16le"; + if (str.length % 2 === 1) { + str = str.slice(0, -1); + } } else if (str[0] === "\xEF" && str[1] === "\xBB" && str[2] === "\xBF") { encoding = "utf-8"; } @@ -759,7 +748,11 @@ function stringToPDFString(str) { fatal: true }); const buffer = stringToBytes(str); - return decoder.decode(buffer); + const decoded = decoder.decode(buffer); + if (!decoded.includes("\x1b")) { + return decoded; + } + return decoded.replaceAll(/\x1b[^\x1b]*(?:\x1b|$)/g, ""); } catch (ex) { warn(`stringToPDFString: "${ex}".`); } @@ -767,7 +760,12 @@ function stringToPDFString(str) { } const strBuf = []; for (let i = 0, ii = str.length; i < ii; i++) { - const code = PDFStringTranslateTable[str.charCodeAt(i)]; + const charCode = str.charCodeAt(i); + if (charCode === 0x1b) { + while (++i < ii && str.charCodeAt(i) !== 0x1b) {} + continue; + } + const code = PDFStringTranslateTable[charCode]; strBuf.push(code ? String.fromCharCode(code) : str.charAt(i)); } return strBuf.join(""); @@ -778,9 +776,6 @@ function stringToUTF8String(str) { function utf8StringToString(str) { return unescape(encodeURIComponent(str)); } -function isArrayBuffer(v) { - return typeof v === "object" && v?.byteLength !== undefined; -} function isArrayEqual(arr1, arr2) { if (arr1.length !== arr2.length) { return false; @@ -796,25 +791,6 @@ function getModificationDate(date = new Date()) { 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")]; return buffer.join(""); } -class PromiseCapability { - #settled = false; - constructor() { - this.promise = new Promise((resolve, reject) => { - this.resolve = data => { - this.#settled = true; - resolve(data); - }; - this.reject = reason => { - this.#settled = true; - reject(reason); - }; - }); - } - get settled() { - return this.#settled; - } -} -exports.PromiseCapability = PromiseCapability; let NormalizeRegex = null; let NormalizationMap = null; function normalizeUnicode(str) { @@ -822,9 +798,7 @@ function normalizeUnicode(str) { 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; NormalizationMap = new Map([["ſt", "ſt"]]); } - return str.replaceAll(NormalizeRegex, (_, p1, p2) => { - return p1 ? p1.normalize("NFKC") : NormalizationMap.get(p2); - }); + return str.replaceAll(NormalizeRegex, (_, p1, p2) => p1 ? p1.normalize("NFKC") : NormalizationMap.get(p2)); } function getUuid() { if (typeof crypto !== "undefined" && typeof crypto?.randomUUID === "function") { @@ -841,505 +815,647 @@ function getUuid() { return bytesToString(buf); } const AnnotationPrefix = "pdfjs_internal_id_"; -exports.AnnotationPrefix = AnnotationPrefix; +const FontRenderOps = { + BEZIER_CURVE_TO: 0, + MOVE_TO: 1, + LINE_TO: 2, + QUADRATIC_CURVE_TO: 3, + RESTORE: 4, + SAVE: 5, + SCALE: 6, + TRANSFORM: 7, + TRANSLATE: 8 +}; -/***/ }), -/* 2 */ -/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { +;// CONCATENATED MODULE: ./src/display/base_factory.js - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.RenderTask = exports.PDFWorkerUtil = exports.PDFWorker = exports.PDFPageProxy = exports.PDFDocumentProxy = exports.PDFDocumentLoadingTask = exports.PDFDataRangeTransport = exports.LoopbackPort = exports.DefaultStandardFontDataFactory = exports.DefaultFilterFactory = exports.DefaultCanvasFactory = exports.DefaultCMapReaderFactory = void 0; -Object.defineProperty(exports, "SVGGraphics", ({ - enumerable: true, - get: function () { - return _displaySvg.SVGGraphics; +class BaseFilterFactory { + addFilter(maps) { + return "none"; } -})); -exports.build = void 0; -exports.getDocument = getDocument; -exports.version = void 0; -var _util = __w_pdfjs_require__(1); -var _annotation_storage = __w_pdfjs_require__(3); -var _display_utils = __w_pdfjs_require__(6); -var _font_loader = __w_pdfjs_require__(9); -var _displayNode_utils = __w_pdfjs_require__(10); -var _canvas = __w_pdfjs_require__(11); -var _worker_options = __w_pdfjs_require__(14); -var _message_handler = __w_pdfjs_require__(15); -var _metadata = __w_pdfjs_require__(16); -var _optional_content_config = __w_pdfjs_require__(17); -var _transport_stream = __w_pdfjs_require__(18); -var _displayFetch_stream = __w_pdfjs_require__(19); -var _displayNetwork = __w_pdfjs_require__(22); -var _displayNode_stream = __w_pdfjs_require__(23); -var _displaySvg = __w_pdfjs_require__(24); -var _xfa_text = __w_pdfjs_require__(25); -const DEFAULT_RANGE_CHUNK_SIZE = 65536; -const RENDERING_CANCELLED_TIMEOUT = 100; -const DELAYED_CLEANUP_TIMEOUT = 5000; -const DefaultCanvasFactory = _util.isNodeJS ? _displayNode_utils.NodeCanvasFactory : _display_utils.DOMCanvasFactory; -exports.DefaultCanvasFactory = DefaultCanvasFactory; -const DefaultCMapReaderFactory = _util.isNodeJS ? _displayNode_utils.NodeCMapReaderFactory : _display_utils.DOMCMapReaderFactory; -exports.DefaultCMapReaderFactory = DefaultCMapReaderFactory; -const DefaultFilterFactory = _util.isNodeJS ? _displayNode_utils.NodeFilterFactory : _display_utils.DOMFilterFactory; -exports.DefaultFilterFactory = DefaultFilterFactory; -const DefaultStandardFontDataFactory = _util.isNodeJS ? _displayNode_utils.NodeStandardFontDataFactory : _display_utils.DOMStandardFontDataFactory; -exports.DefaultStandardFontDataFactory = DefaultStandardFontDataFactory; -function getDocument(src) { - if (typeof src === "string" || src instanceof URL) { - src = { - url: src - }; - } else if ((0, _util.isArrayBuffer)(src)) { - src = { - data: src + addHCMFilter(fgColor, bgColor) { + return "none"; + } + addAlphaFilter(map) { + return "none"; + } + addLuminosityFilter(map) { + return "none"; + } + addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) { + return "none"; + } + destroy(keepHCM = false) {} +} +class BaseCanvasFactory { + #enableHWA = false; + constructor({ + enableHWA = false + } = {}) { + this.#enableHWA = enableHWA; + } + create(width, height) { + if (width <= 0 || height <= 0) { + throw new Error("Invalid canvas size"); + } + const canvas = this._createCanvas(width, height); + return { + canvas, + context: canvas.getContext("2d", { + willReadFrequently: !this.#enableHWA + }) }; } - if (typeof src !== "object") { - throw new Error("Invalid parameter in getDocument, need parameter object."); + reset(canvasAndContext, width, height) { + if (!canvasAndContext.canvas) { + throw new Error("Canvas is not specified"); + } + if (width <= 0 || height <= 0) { + throw new Error("Invalid canvas size"); + } + canvasAndContext.canvas.width = width; + canvasAndContext.canvas.height = height; } - if (!src.url && !src.data && !src.range) { - throw new Error("Invalid parameter object: need either .data, .range or .url"); + destroy(canvasAndContext) { + if (!canvasAndContext.canvas) { + throw new Error("Canvas is not specified"); + } + canvasAndContext.canvas.width = 0; + canvasAndContext.canvas.height = 0; + canvasAndContext.canvas = null; + canvasAndContext.context = null; } - const task = new PDFDocumentLoadingTask(); - const { - docId - } = task; - const url = src.url ? getUrlProp(src.url) : null; - const data = src.data ? getDataProp(src.data) : null; - const httpHeaders = src.httpHeaders || null; - const withCredentials = src.withCredentials === true; - const password = src.password ?? null; - const rangeTransport = src.range instanceof PDFDataRangeTransport ? src.range : null; - const rangeChunkSize = Number.isInteger(src.rangeChunkSize) && src.rangeChunkSize > 0 ? src.rangeChunkSize : DEFAULT_RANGE_CHUNK_SIZE; - let worker = src.worker instanceof PDFWorker ? src.worker : null; - const verbosity = src.verbosity; - const docBaseUrl = typeof src.docBaseUrl === "string" && !(0, _display_utils.isDataScheme)(src.docBaseUrl) ? src.docBaseUrl : null; - const cMapUrl = typeof src.cMapUrl === "string" ? src.cMapUrl : null; - const cMapPacked = src.cMapPacked !== false; - const CMapReaderFactory = src.CMapReaderFactory || DefaultCMapReaderFactory; - const standardFontDataUrl = typeof src.standardFontDataUrl === "string" ? src.standardFontDataUrl : null; - const StandardFontDataFactory = src.StandardFontDataFactory || DefaultStandardFontDataFactory; - const ignoreErrors = src.stopAtErrors !== true; - const maxImageSize = Number.isInteger(src.maxImageSize) && src.maxImageSize > -1 ? src.maxImageSize : -1; - const isEvalSupported = src.isEvalSupported !== false; - const isOffscreenCanvasSupported = typeof src.isOffscreenCanvasSupported === "boolean" ? src.isOffscreenCanvasSupported : !_util.isNodeJS; - const canvasMaxAreaInBytes = Number.isInteger(src.canvasMaxAreaInBytes) ? src.canvasMaxAreaInBytes : -1; - const disableFontFace = typeof src.disableFontFace === "boolean" ? src.disableFontFace : _util.isNodeJS; - const fontExtraProperties = src.fontExtraProperties === true; - const enableXfa = src.enableXfa === true; - const ownerDocument = src.ownerDocument || globalThis.document; - const disableRange = src.disableRange === true; - const disableStream = src.disableStream === true; - const disableAutoFetch = src.disableAutoFetch === true; - const pdfBug = src.pdfBug === true; - const length = rangeTransport ? rangeTransport.length : src.length ?? NaN; - const useSystemFonts = typeof src.useSystemFonts === "boolean" ? src.useSystemFonts : !_util.isNodeJS && !disableFontFace; - const useWorkerFetch = typeof src.useWorkerFetch === "boolean" ? src.useWorkerFetch : CMapReaderFactory === _display_utils.DOMCMapReaderFactory && StandardFontDataFactory === _display_utils.DOMStandardFontDataFactory && cMapUrl && standardFontDataUrl && (0, _display_utils.isValidFetchUrl)(cMapUrl, document.baseURI) && (0, _display_utils.isValidFetchUrl)(standardFontDataUrl, document.baseURI); - const canvasFactory = src.canvasFactory || new DefaultCanvasFactory({ - ownerDocument - }); - const filterFactory = src.filterFactory || new DefaultFilterFactory({ + _createCanvas(width, height) { + unreachable("Abstract method `_createCanvas` called."); + } +} +class BaseCMapReaderFactory { + constructor({ + baseUrl = null, + isCompressed = true + }) { + this.baseUrl = baseUrl; + this.isCompressed = isCompressed; + } + async fetch({ + name + }) { + if (!this.baseUrl) { + throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided."); + } + if (!name) { + throw new Error("CMap name must be specified."); + } + const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : ""); + const compressionType = this.isCompressed ? CMapCompressionType.BINARY : CMapCompressionType.NONE; + return this._fetchData(url, compressionType).catch(reason => { + throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`); + }); + } + _fetchData(url, compressionType) { + unreachable("Abstract method `_fetchData` called."); + } +} +class BaseStandardFontDataFactory { + constructor({ + baseUrl = null + }) { + this.baseUrl = baseUrl; + } + async fetch({ + filename + }) { + if (!this.baseUrl) { + throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided."); + } + if (!filename) { + throw new Error("Font filename must be specified."); + } + const url = `${this.baseUrl}${filename}`; + return this._fetchData(url).catch(reason => { + throw new Error(`Unable to load font data at: ${url}`); + }); + } + _fetchData(url) { + unreachable("Abstract method `_fetchData` called."); + } +} +class BaseSVGFactory { + create(width, height, skipDimensions = false) { + if (width <= 0 || height <= 0) { + throw new Error("Invalid SVG dimensions"); + } + const svg = this._createSVG("svg:svg"); + svg.setAttribute("version", "1.1"); + if (!skipDimensions) { + svg.setAttribute("width", `${width}px`); + svg.setAttribute("height", `${height}px`); + } + svg.setAttribute("preserveAspectRatio", "none"); + svg.setAttribute("viewBox", `0 0 ${width} ${height}`); + return svg; + } + createElement(type) { + if (typeof type !== "string") { + throw new Error("Invalid SVG element type"); + } + return this._createSVG(type); + } + _createSVG(type) { + unreachable("Abstract method `_createSVG` called."); + } +} + +;// CONCATENATED MODULE: ./src/display/display_utils.js + + +const SVG_NS = "http://www.w3.org/2000/svg"; +class PixelsPerInch { + static CSS = 96.0; + static PDF = 72.0; + static PDF_TO_CSS_UNITS = this.CSS / this.PDF; +} +class DOMFilterFactory extends BaseFilterFactory { + #baseUrl; + #_cache; + #_defs; + #docId; + #document; + #_hcmCache; + #id = 0; + constructor({ docId, - ownerDocument - }); - const styleElement = null; - (0, _util.setVerbosityLevel)(verbosity); - const transportFactory = { - canvasFactory, - filterFactory - }; - if (!useWorkerFetch) { - transportFactory.cMapReaderFactory = new CMapReaderFactory({ - baseUrl: cMapUrl, - isCompressed: cMapPacked - }); - transportFactory.standardFontDataFactory = new StandardFontDataFactory({ - baseUrl: standardFontDataUrl - }); + ownerDocument = globalThis.document + } = {}) { + super(); + this.#docId = docId; + this.#document = ownerDocument; } - if (!worker) { - const workerParams = { - verbosity, - port: _worker_options.GlobalWorkerOptions.workerPort + get #cache() { + return this.#_cache ||= new Map(); + } + get #hcmCache() { + return this.#_hcmCache ||= new Map(); + } + get #defs() { + if (!this.#_defs) { + const div = this.#document.createElement("div"); + const { + style + } = div; + style.visibility = "hidden"; + style.contain = "strict"; + style.width = style.height = 0; + style.position = "absolute"; + style.top = style.left = 0; + style.zIndex = -1; + const svg = this.#document.createElementNS(SVG_NS, "svg"); + svg.setAttribute("width", 0); + svg.setAttribute("height", 0); + this.#_defs = this.#document.createElementNS(SVG_NS, "defs"); + div.append(svg); + svg.append(this.#_defs); + this.#document.body.append(div); + } + return this.#_defs; + } + #createTables(maps) { + if (maps.length === 1) { + const mapR = maps[0]; + const buffer = new Array(256); + for (let i = 0; i < 256; i++) { + buffer[i] = mapR[i] / 255; + } + const table = buffer.join(","); + return [table, table, table]; + } + const [mapR, mapG, mapB] = maps; + const bufferR = new Array(256); + const bufferG = new Array(256); + const bufferB = new Array(256); + for (let i = 0; i < 256; i++) { + bufferR[i] = mapR[i] / 255; + bufferG[i] = mapG[i] / 255; + bufferB[i] = mapB[i] / 255; + } + return [bufferR.join(","), bufferG.join(","), bufferB.join(",")]; + } + #createUrl(id) { + if (this.#baseUrl === undefined) { + this.#baseUrl = ""; + const url = this.#document.URL; + if (url !== this.#document.baseURI) { + if (isDataScheme(url)) { + warn('#createUrl: ignore "data:"-URL for performance reasons.'); + } else { + this.#baseUrl = url.split("#", 1)[0]; + } + } + } + return `url(${this.#baseUrl}#${id})`; + } + addFilter(maps) { + if (!maps) { + return "none"; + } + let value = this.#cache.get(maps); + if (value) { + return value; + } + const [tableR, tableG, tableB] = this.#createTables(maps); + const key = maps.length === 1 ? tableR : `${tableR}${tableG}${tableB}`; + value = this.#cache.get(key); + if (value) { + this.#cache.set(maps, value); + return value; + } + const id = `g_${this.#docId}_transfer_map_${this.#id++}`; + const url = this.#createUrl(id); + this.#cache.set(maps, url); + this.#cache.set(key, url); + const filter = this.#createFilter(id); + this.#addTransferMapConversion(tableR, tableG, tableB, filter); + return url; + } + addHCMFilter(fgColor, bgColor) { + const key = `${fgColor}-${bgColor}`; + const filterName = "base"; + let info = this.#hcmCache.get(filterName); + if (info?.key === key) { + return info.url; + } + if (info) { + info.filter?.remove(); + info.key = key; + info.url = "none"; + info.filter = null; + } else { + info = { + key, + url: "none", + filter: null + }; + this.#hcmCache.set(filterName, info); + } + if (!fgColor || !bgColor) { + return info.url; + } + const fgRGB = this.#getRGB(fgColor); + fgColor = Util.makeHexColor(...fgRGB); + const bgRGB = this.#getRGB(bgColor); + bgColor = Util.makeHexColor(...bgRGB); + this.#defs.style.color = ""; + if (fgColor === "#000000" && bgColor === "#ffffff" || fgColor === bgColor) { + return info.url; + } + const map = new Array(256); + for (let i = 0; i <= 255; i++) { + const x = i / 255; + map[i] = x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4; + } + const table = map.join(","); + const id = `g_${this.#docId}_hcm_filter`; + const filter = info.filter = this.#createFilter(id); + this.#addTransferMapConversion(table, table, table, filter); + this.#addGrayConversion(filter); + const getSteps = (c, n) => { + const start = fgRGB[c] / 255; + const end = bgRGB[c] / 255; + const arr = new Array(n + 1); + for (let i = 0; i <= n; i++) { + arr[i] = start + i / n * (end - start); + } + return arr.join(","); }; - worker = workerParams.port ? PDFWorker.fromPort(workerParams) : new PDFWorker(workerParams); - task._worker = worker; + this.#addTransferMapConversion(getSteps(0, 5), getSteps(1, 5), getSteps(2, 5), filter); + info.url = this.#createUrl(id); + return info.url; } - const fetchDocParams = { - docId, - apiVersion: '3.11.174', - data, - password, - disableAutoFetch, - rangeChunkSize, - length, - docBaseUrl, - enableXfa, - evaluatorOptions: { - maxImageSize, - disableFontFace, - ignoreErrors, - isEvalSupported, - isOffscreenCanvasSupported, - canvasMaxAreaInBytes, - fontExtraProperties, - useSystemFonts, - cMapUrl: useWorkerFetch ? cMapUrl : null, - standardFontDataUrl: useWorkerFetch ? standardFontDataUrl : null + addAlphaFilter(map) { + let value = this.#cache.get(map); + if (value) { + return value; } - }; - const transportParams = { - ignoreErrors, - isEvalSupported, - disableFontFace, - fontExtraProperties, - enableXfa, - ownerDocument, - disableAutoFetch, - pdfBug, - styleElement - }; - worker.promise.then(function () { - if (task.destroyed) { - throw new Error("Loading aborted"); + const [tableA] = this.#createTables([map]); + const key = `alpha_${tableA}`; + value = this.#cache.get(key); + if (value) { + this.#cache.set(map, value); + return value; } - const workerIdPromise = _fetchDocument(worker, fetchDocParams); - const networkStreamPromise = new Promise(function (resolve) { - let networkStream; - if (rangeTransport) { - networkStream = new _transport_stream.PDFDataTransportStream({ - length, - initialData: rangeTransport.initialData, - progressiveDone: rangeTransport.progressiveDone, - contentDispositionFilename: rangeTransport.contentDispositionFilename, - disableRange, - disableStream - }, rangeTransport); - } else if (!data) { - const createPDFNetworkStream = params => { - if (_util.isNodeJS) { - return new _displayNode_stream.PDFNodeStream(params); - } - return (0, _display_utils.isValidFetchUrl)(params.url) ? new _displayFetch_stream.PDFFetchStream(params) : new _displayNetwork.PDFNetworkStream(params); - }; - networkStream = createPDFNetworkStream({ - url, - length, - httpHeaders, - withCredentials, - rangeChunkSize, - disableRange, - disableStream - }); - } - resolve(networkStream); - }); - return Promise.all([workerIdPromise, networkStreamPromise]).then(function ([workerId, networkStream]) { - if (task.destroyed) { - throw new Error("Loading aborted"); - } - const messageHandler = new _message_handler.MessageHandler(docId, workerId, worker.port); - const transport = new WorkerTransport(messageHandler, task, networkStream, transportParams, transportFactory); - task._transport = transport; - messageHandler.send("Ready", null); - }); - }).catch(task._capability.reject); - return task; -} -async function _fetchDocument(worker, source) { - if (worker.destroyed) { - throw new Error("Worker was destroyed"); + const id = `g_${this.#docId}_alpha_map_${this.#id++}`; + const url = this.#createUrl(id); + this.#cache.set(map, url); + this.#cache.set(key, url); + const filter = this.#createFilter(id); + this.#addTransferMapAlphaConversion(tableA, filter); + return url; } - const workerId = await worker.messageHandler.sendWithPromise("GetDocRequest", source, source.data ? [source.data.buffer] : null); - if (worker.destroyed) { - throw new Error("Worker was destroyed"); - } - return workerId; -} -function getUrlProp(val) { - if (val instanceof URL) { - return val.href; - } - try { - return new URL(val, window.location).href; - } catch { - if (_util.isNodeJS && typeof val === "string") { - return val; + addLuminosityFilter(map) { + let value = this.#cache.get(map || "luminosity"); + if (value) { + return value; } - } - throw new Error("Invalid PDF url data: " + "either string or URL-object is expected in the url property."); -} -function getDataProp(val) { - if (_util.isNodeJS && typeof Buffer !== "undefined" && val instanceof Buffer) { - throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`."); - } - if (val instanceof Uint8Array && val.byteLength === val.buffer.byteLength) { - return val; - } - if (typeof val === "string") { - return (0, _util.stringToBytes)(val); - } - if (typeof val === "object" && !isNaN(val?.length) || (0, _util.isArrayBuffer)(val)) { - return new Uint8Array(val); - } - throw new Error("Invalid PDF binary data: either TypedArray, " + "string, or array-like object is expected in the data property."); -} -class PDFDocumentLoadingTask { - static #docId = 0; - constructor() { - this._capability = new _util.PromiseCapability(); - this._transport = null; - this._worker = null; - this.docId = `d${PDFDocumentLoadingTask.#docId++}`; - this.destroyed = false; - this.onPassword = null; - this.onProgress = null; - } - get promise() { - return this._capability.promise; - } - async destroy() { - this.destroyed = true; - try { - if (this._worker?.port) { - this._worker._pendingDestroy = true; - } - await this._transport?.destroy(); - } catch (ex) { - if (this._worker?.port) { - delete this._worker._pendingDestroy; - } - throw ex; + let tableA, key; + if (map) { + [tableA] = this.#createTables([map]); + key = `luminosity_${tableA}`; + } else { + key = "luminosity"; } - this._transport = null; - if (this._worker) { - this._worker.destroy(); - this._worker = null; + value = this.#cache.get(key); + if (value) { + this.#cache.set(map, value); + return value; } - } -} -exports.PDFDocumentLoadingTask = PDFDocumentLoadingTask; -class PDFDataRangeTransport { - constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) { - this.length = length; - this.initialData = initialData; - this.progressiveDone = progressiveDone; - this.contentDispositionFilename = contentDispositionFilename; - this._rangeListeners = []; - this._progressListeners = []; - this._progressiveReadListeners = []; - this._progressiveDoneListeners = []; - this._readyCapability = new _util.PromiseCapability(); - } - addRangeListener(listener) { - this._rangeListeners.push(listener); - } - addProgressListener(listener) { - this._progressListeners.push(listener); - } - addProgressiveReadListener(listener) { - this._progressiveReadListeners.push(listener); - } - addProgressiveDoneListener(listener) { - this._progressiveDoneListeners.push(listener); - } - onDataRange(begin, chunk) { - for (const listener of this._rangeListeners) { - listener(begin, chunk); + const id = `g_${this.#docId}_luminosity_map_${this.#id++}`; + const url = this.#createUrl(id); + this.#cache.set(map, url); + this.#cache.set(key, url); + const filter = this.#createFilter(id); + this.#addLuminosityConversion(filter); + if (map) { + this.#addTransferMapAlphaConversion(tableA, filter); } + return url; } - onDataProgress(loaded, total) { - this._readyCapability.promise.then(() => { - for (const listener of this._progressListeners) { - listener(loaded, total); + addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) { + const key = `${fgColor}-${bgColor}-${newFgColor}-${newBgColor}`; + let info = this.#hcmCache.get(filterName); + if (info?.key === key) { + return info.url; + } + if (info) { + info.filter?.remove(); + info.key = key; + info.url = "none"; + info.filter = null; + } else { + info = { + key, + url: "none", + filter: null + }; + this.#hcmCache.set(filterName, info); + } + if (!fgColor || !bgColor) { + return info.url; + } + const [fgRGB, bgRGB] = [fgColor, bgColor].map(this.#getRGB.bind(this)); + let fgGray = Math.round(0.2126 * fgRGB[0] + 0.7152 * fgRGB[1] + 0.0722 * fgRGB[2]); + let bgGray = Math.round(0.2126 * bgRGB[0] + 0.7152 * bgRGB[1] + 0.0722 * bgRGB[2]); + let [newFgRGB, newBgRGB] = [newFgColor, newBgColor].map(this.#getRGB.bind(this)); + if (bgGray < fgGray) { + [fgGray, bgGray, newFgRGB, newBgRGB] = [bgGray, fgGray, newBgRGB, newFgRGB]; + } + this.#defs.style.color = ""; + const getSteps = (fg, bg, n) => { + const arr = new Array(256); + const step = (bgGray - fgGray) / n; + const newStart = fg / 255; + const newStep = (bg - fg) / (255 * n); + let prev = 0; + for (let i = 0; i <= n; i++) { + const k = Math.round(fgGray + i * step); + const value = newStart + i * newStep; + for (let j = prev; j <= k; j++) { + arr[j] = value; + } + prev = k + 1; } - }); - } - onDataProgressiveRead(chunk) { - this._readyCapability.promise.then(() => { - for (const listener of this._progressiveReadListeners) { - listener(chunk); + for (let i = prev; i < 256; i++) { + arr[i] = arr[prev - 1]; } - }); + return arr.join(","); + }; + const id = `g_${this.#docId}_hcm_${filterName}_filter`; + const filter = info.filter = this.#createFilter(id); + this.#addGrayConversion(filter); + this.#addTransferMapConversion(getSteps(newFgRGB[0], newBgRGB[0], 5), getSteps(newFgRGB[1], newBgRGB[1], 5), getSteps(newFgRGB[2], newBgRGB[2], 5), filter); + info.url = this.#createUrl(id); + return info.url; } - onDataProgressiveDone() { - this._readyCapability.promise.then(() => { - for (const listener of this._progressiveDoneListeners) { - listener(); - } - }); + destroy(keepHCM = false) { + if (keepHCM && this.#hcmCache.size !== 0) { + return; + } + if (this.#_defs) { + this.#_defs.parentNode.parentNode.remove(); + this.#_defs = null; + } + if (this.#_cache) { + this.#_cache.clear(); + this.#_cache = null; + } + this.#id = 0; } - transportReady() { - this._readyCapability.resolve(); + #addLuminosityConversion(filter) { + const feColorMatrix = this.#document.createElementNS(SVG_NS, "feColorMatrix"); + feColorMatrix.setAttribute("type", "matrix"); + 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"); + filter.append(feColorMatrix); } - requestDataRange(begin, end) { - (0, _util.unreachable)("Abstract method PDFDataRangeTransport.requestDataRange"); + #addGrayConversion(filter) { + const feColorMatrix = this.#document.createElementNS(SVG_NS, "feColorMatrix"); + feColorMatrix.setAttribute("type", "matrix"); + 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"); + filter.append(feColorMatrix); } - abort() {} -} -exports.PDFDataRangeTransport = PDFDataRangeTransport; -class PDFDocumentProxy { - constructor(pdfInfo, transport) { - this._pdfInfo = pdfInfo; - this._transport = transport; - Object.defineProperty(this, "getJavaScript", { - value: () => { - (0, _display_utils.deprecated)("`PDFDocumentProxy.getJavaScript`, " + "please use `PDFDocumentProxy.getJSActions` instead."); - return this.getJSActions().then(js => { - if (!js) { - return js; - } - const jsArr = []; - for (const name in js) { - jsArr.push(...js[name]); - } - return jsArr; - }); - } - }); + #createFilter(id) { + const filter = this.#document.createElementNS(SVG_NS, "filter"); + filter.setAttribute("color-interpolation-filters", "sRGB"); + filter.setAttribute("id", id); + this.#defs.append(filter); + return filter; } - get annotationStorage() { - return this._transport.annotationStorage; + #appendFeFunc(feComponentTransfer, func, table) { + const feFunc = this.#document.createElementNS(SVG_NS, func); + feFunc.setAttribute("type", "discrete"); + feFunc.setAttribute("tableValues", table); + feComponentTransfer.append(feFunc); } - get filterFactory() { - return this._transport.filterFactory; + #addTransferMapConversion(rTable, gTable, bTable, filter) { + const feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer"); + filter.append(feComponentTransfer); + this.#appendFeFunc(feComponentTransfer, "feFuncR", rTable); + this.#appendFeFunc(feComponentTransfer, "feFuncG", gTable); + this.#appendFeFunc(feComponentTransfer, "feFuncB", bTable); } - get numPages() { - return this._pdfInfo.numPages; + #addTransferMapAlphaConversion(aTable, filter) { + const feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer"); + filter.append(feComponentTransfer); + this.#appendFeFunc(feComponentTransfer, "feFuncA", aTable); } - get fingerprints() { - return this._pdfInfo.fingerprints; - } - get isPureXfa() { - return (0, _util.shadow)(this, "isPureXfa", !!this._transport._htmlForXfa); - } - get allXfaHtml() { - return this._transport._htmlForXfa; - } - getPage(pageNumber) { - return this._transport.getPage(pageNumber); - } - getPageIndex(ref) { - return this._transport.getPageIndex(ref); - } - getDestinations() { - return this._transport.getDestinations(); - } - getDestination(id) { - return this._transport.getDestination(id); - } - getPageLabels() { - return this._transport.getPageLabels(); - } - getPageLayout() { - return this._transport.getPageLayout(); - } - getPageMode() { - return this._transport.getPageMode(); - } - getViewerPreferences() { - return this._transport.getViewerPreferences(); - } - getOpenAction() { - return this._transport.getOpenAction(); - } - getAttachments() { - return this._transport.getAttachments(); - } - getJSActions() { - return this._transport.getDocJSActions(); - } - getOutline() { - return this._transport.getOutline(); - } - getOptionalContentConfig() { - return this._transport.getOptionalContentConfig(); - } - getPermissions() { - return this._transport.getPermissions(); - } - getMetadata() { - return this._transport.getMetadata(); - } - getMarkInfo() { - return this._transport.getMarkInfo(); - } - getData() { - return this._transport.getData(); - } - saveDocument() { - return this._transport.saveDocument(); - } - getDownloadInfo() { - return this._transport.downloadInfoCapability.promise; - } - cleanup(keepLoadedFonts = false) { - return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa); - } - destroy() { - return this.loadingTask.destroy(); - } - get loadingParams() { - return this._transport.loadingParams; - } - get loadingTask() { - return this._transport.loadingTask; - } - getFieldObjects() { - return this._transport.getFieldObjects(); - } - hasJSActions() { - return this._transport.hasJSActions(); - } - getCalculationOrderIds() { - return this._transport.getCalculationOrderIds(); + #getRGB(color) { + this.#defs.style.color = color; + return getRGB(getComputedStyle(this.#defs).getPropertyValue("color")); } } -exports.PDFDocumentProxy = PDFDocumentProxy; -class PDFPageProxy { - #delayedCleanupTimeout = null; - #pendingCleanup = false; - constructor(pageIndex, pageInfo, transport, pdfBug = false) { - this._pageIndex = pageIndex; - this._pageInfo = pageInfo; - this._transport = transport; - this._stats = pdfBug ? new _display_utils.StatTimer() : null; - this._pdfBug = pdfBug; - this.commonObjs = transport.commonObjs; - this.objs = new PDFObjects(); - this._maybeCleanupAfterRender = false; - this._intentStates = new Map(); - this.destroyed = false; +class DOMCanvasFactory extends BaseCanvasFactory { + constructor({ + ownerDocument = globalThis.document, + enableHWA = false + } = {}) { + super({ + enableHWA + }); + this._document = ownerDocument; } - get pageNumber() { - return this._pageIndex + 1; + _createCanvas(width, height) { + const canvas = this._document.createElement("canvas"); + canvas.width = width; + canvas.height = height; + return canvas; } - get rotate() { - return this._pageInfo.rotate; +} +async function fetchData(url, type = "text") { + if (isValidFetchUrl(url, document.baseURI)) { + const response = await fetch(url); + if (!response.ok) { + throw new Error(response.statusText); + } + switch (type) { + case "arraybuffer": + return response.arrayBuffer(); + case "blob": + return response.blob(); + case "json": + return response.json(); + } + return response.text(); } - get ref() { - return this._pageInfo.ref; + return new Promise((resolve, reject) => { + const request = new XMLHttpRequest(); + request.open("GET", url, true); + request.responseType = type; + request.onreadystatechange = () => { + if (request.readyState !== XMLHttpRequest.DONE) { + return; + } + if (request.status === 200 || request.status === 0) { + switch (type) { + case "arraybuffer": + case "blob": + case "json": + resolve(request.response); + return; + } + resolve(request.responseText); + return; + } + reject(new Error(request.statusText)); + }; + request.send(null); + }); +} +class DOMCMapReaderFactory extends BaseCMapReaderFactory { + _fetchData(url, compressionType) { + return fetchData(url, this.isCompressed ? "arraybuffer" : "text").then(data => ({ + cMapData: data instanceof ArrayBuffer ? new Uint8Array(data) : stringToBytes(data), + compressionType + })); } - get userUnit() { - return this._pageInfo.userUnit; +} +class DOMStandardFontDataFactory extends BaseStandardFontDataFactory { + _fetchData(url) { + return fetchData(url, "arraybuffer").then(data => new Uint8Array(data)); } - get view() { - return this._pageInfo.view; +} +class DOMSVGFactory extends BaseSVGFactory { + _createSVG(type) { + return document.createElementNS(SVG_NS, type); } - getViewport({ +} +class PageViewport { + constructor({ + viewBox, scale, - rotation = this.rotate, + rotation, offsetX = 0, offsetY = 0, dontFlip = false + }) { + this.viewBox = viewBox; + this.scale = scale; + this.rotation = rotation; + this.offsetX = offsetX; + this.offsetY = offsetY; + const centerX = (viewBox[2] + viewBox[0]) / 2; + const centerY = (viewBox[3] + viewBox[1]) / 2; + let rotateA, rotateB, rotateC, rotateD; + rotation %= 360; + if (rotation < 0) { + rotation += 360; + } + switch (rotation) { + case 180: + rotateA = -1; + rotateB = 0; + rotateC = 0; + rotateD = 1; + break; + case 90: + rotateA = 0; + rotateB = 1; + rotateC = 1; + rotateD = 0; + break; + case 270: + rotateA = 0; + rotateB = -1; + rotateC = -1; + rotateD = 0; + break; + case 0: + rotateA = 1; + rotateB = 0; + rotateC = 0; + rotateD = -1; + break; + default: + throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees."); + } + if (dontFlip) { + rotateC = -rotateC; + rotateD = -rotateD; + } + let offsetCanvasX, offsetCanvasY; + let width, height; + if (rotateA === 0) { + offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX; + offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY; + width = (viewBox[3] - viewBox[1]) * scale; + height = (viewBox[2] - viewBox[0]) * scale; + } else { + offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX; + offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY; + width = (viewBox[2] - viewBox[0]) * scale; + height = (viewBox[3] - viewBox[1]) * scale; + } + this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY]; + this.width = width; + this.height = height; + } + get rawDims() { + const { + viewBox + } = this; + return shadow(this, "rawDims", { + pageWidth: viewBox[2] - viewBox[0], + pageHeight: viewBox[3] - viewBox[1], + pageX: viewBox[0], + pageY: viewBox[1] + }); + } + clone({ + scale = this.scale, + rotation = this.rotation, + offsetX = this.offsetX, + offsetY = this.offsetY, + dontFlip = false } = {}) { - return new _display_utils.PageViewport({ - viewBox: this.view, + return new PageViewport({ + viewBox: this.viewBox.slice(), scale, rotation, offsetX, @@ -1347,2486 +1463,442 @@ class PDFPageProxy { dontFlip }); } - getAnnotations({ - intent = "display" - } = {}) { - const intentArgs = this._transport.getRenderingIntent(intent); - return this._transport.getAnnotations(this._pageIndex, intentArgs.renderingIntent); + convertToViewportPoint(x, y) { + return Util.applyTransform([x, y], this.transform); } - getJSActions() { - return this._transport.getPageJSActions(this._pageIndex); + convertToViewportRectangle(rect) { + const topLeft = Util.applyTransform([rect[0], rect[1]], this.transform); + const bottomRight = Util.applyTransform([rect[2], rect[3]], this.transform); + return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]]; } - get filterFactory() { - return this._transport.filterFactory; + convertToPdfPoint(x, y) { + return Util.applyInverseTransform([x, y], this.transform); } - get isPureXfa() { - return (0, _util.shadow)(this, "isPureXfa", !!this._transport._htmlForXfa); +} +class RenderingCancelledException extends BaseException { + constructor(msg, extraDelay = 0) { + super(msg, "RenderingCancelledException"); + this.extraDelay = extraDelay; } - async getXfa() { - return this._transport._htmlForXfa?.children[this._pageIndex] || null; +} +function isDataScheme(url) { + const ii = url.length; + let i = 0; + while (i < ii && url[i].trim() === "") { + i++; } - render({ - canvasContext, - viewport, - intent = "display", - annotationMode = _util.AnnotationMode.ENABLE, - transform = null, - background = null, - optionalContentConfigPromise = null, - annotationCanvasMap = null, - pageColors = null, - printAnnotationStorage = null - }) { - this._stats?.time("Overall"); - const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage); - this.#pendingCleanup = false; - this.#abortDelayedCleanup(); - if (!optionalContentConfigPromise) { - optionalContentConfigPromise = this._transport.getOptionalContentConfig(); + return url.substring(i, i + 5).toLowerCase() === "data:"; +} +function isPdfFile(filename) { + return typeof filename === "string" && /\.pdf$/i.test(filename); +} +function getFilenameFromUrl(url) { + [url] = url.split(/[#?]/, 1); + return url.substring(url.lastIndexOf("/") + 1); +} +function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") { + if (typeof url !== "string") { + return defaultFilename; + } + if (isDataScheme(url)) { + warn('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'); + return defaultFilename; + } + const reURI = /^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/; + const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i; + const splitURI = reURI.exec(url); + let suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]); + if (suggestedFilename) { + suggestedFilename = suggestedFilename[0]; + if (suggestedFilename.includes("%")) { + try { + suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0]; + } catch {} } - let intentState = this._intentStates.get(intentArgs.cacheKey); - if (!intentState) { - intentState = Object.create(null); - this._intentStates.set(intentArgs.cacheKey, intentState); + } + return suggestedFilename || defaultFilename; +} +class StatTimer { + started = Object.create(null); + times = []; + time(name) { + if (name in this.started) { + warn(`Timer is already running for ${name}`); } - if (intentState.streamReaderCancelTimeout) { - clearTimeout(intentState.streamReaderCancelTimeout); - intentState.streamReaderCancelTimeout = null; + this.started[name] = Date.now(); + } + timeEnd(name) { + if (!(name in this.started)) { + warn(`Timer has not been started for ${name}`); } - const intentPrint = !!(intentArgs.renderingIntent & _util.RenderingIntentFlag.PRINT); - if (!intentState.displayReadyCapability) { - intentState.displayReadyCapability = new _util.PromiseCapability(); - intentState.operatorList = { - fnArray: [], - argsArray: [], - lastChunk: false, - separateAnnots: null - }; - this._stats?.time("Page Request"); - this._pumpOperatorList(intentArgs); - } - const complete = error => { - intentState.renderTasks.delete(internalRenderTask); - if (this._maybeCleanupAfterRender || intentPrint) { - this.#pendingCleanup = true; - } - this.#tryCleanup(!intentPrint); - if (error) { - internalRenderTask.capability.reject(error); - this._abortOperatorList({ - intentState, - reason: error instanceof Error ? error : new Error(error) - }); - } else { - internalRenderTask.capability.resolve(); - } - this._stats?.timeEnd("Rendering"); - this._stats?.timeEnd("Overall"); - }; - const internalRenderTask = new InternalRenderTask({ - callback: complete, - params: { - canvasContext, - viewport, - transform, - background - }, - objs: this.objs, - commonObjs: this.commonObjs, - annotationCanvasMap, - operatorList: intentState.operatorList, - pageIndex: this._pageIndex, - canvasFactory: this._transport.canvasFactory, - filterFactory: this._transport.filterFactory, - useRequestAnimationFrame: !intentPrint, - pdfBug: this._pdfBug, - pageColors + this.times.push({ + name, + start: this.started[name], + end: Date.now() }); - (intentState.renderTasks ||= new Set()).add(internalRenderTask); - const renderTask = internalRenderTask.task; - Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => { - if (this.destroyed) { - complete(); - return; - } - this._stats?.time("Rendering"); - internalRenderTask.initializeGraphics({ - transparency, - optionalContentConfig - }); - internalRenderTask.operatorListChanged(); - }).catch(complete); - return renderTask; + delete this.started[name]; } - getOperatorList({ - intent = "display", - annotationMode = _util.AnnotationMode.ENABLE, - printAnnotationStorage = null - } = {}) { - function operatorListChanged() { - if (intentState.operatorList.lastChunk) { - intentState.opListReadCapability.resolve(intentState.operatorList); - intentState.renderTasks.delete(opListTask); - } - } - const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, true); - let intentState = this._intentStates.get(intentArgs.cacheKey); - if (!intentState) { - intentState = Object.create(null); - this._intentStates.set(intentArgs.cacheKey, intentState); - } - let opListTask; - if (!intentState.opListReadCapability) { - opListTask = Object.create(null); - opListTask.operatorListChanged = operatorListChanged; - intentState.opListReadCapability = new _util.PromiseCapability(); - (intentState.renderTasks ||= new Set()).add(opListTask); - intentState.operatorList = { - fnArray: [], - argsArray: [], - lastChunk: false, - separateAnnots: null - }; - this._stats?.time("Page Request"); - this._pumpOperatorList(intentArgs); - } - return intentState.opListReadCapability.promise; - } - streamTextContent({ - includeMarkedContent = false, - disableNormalization = false - } = {}) { - const TEXT_CONTENT_CHUNK_SIZE = 100; - return this._transport.messageHandler.sendWithStream("GetTextContent", { - pageIndex: this._pageIndex, - includeMarkedContent: includeMarkedContent === true, - disableNormalization: disableNormalization === true - }, { - highWaterMark: TEXT_CONTENT_CHUNK_SIZE, - size(textContent) { - return textContent.items.length; - } - }); - } - getTextContent(params = {}) { - if (this._transport._htmlForXfa) { - return this.getXfa().then(xfa => { - return _xfa_text.XfaText.textContent(xfa); - }); - } - const readableStream = this.streamTextContent(params); - return new Promise(function (resolve, reject) { - function pump() { - reader.read().then(function ({ - value, - done - }) { - if (done) { - resolve(textContent); - return; - } - Object.assign(textContent.styles, value.styles); - textContent.items.push(...value.items); - pump(); - }, reject); - } - const reader = readableStream.getReader(); - const textContent = { - items: [], - styles: Object.create(null) - }; - pump(); - }); - } - getStructTree() { - return this._transport.getStructTree(this._pageIndex); - } - _destroy() { - this.destroyed = true; - const waitOn = []; - for (const intentState of this._intentStates.values()) { - this._abortOperatorList({ - intentState, - reason: new Error("Page was destroyed."), - force: true - }); - if (intentState.opListReadCapability) { - continue; - } - for (const internalRenderTask of intentState.renderTasks) { - waitOn.push(internalRenderTask.completed); - internalRenderTask.cancel(); - } - } - this.objs.clear(); - this.#pendingCleanup = false; - this.#abortDelayedCleanup(); - return Promise.all(waitOn); - } - cleanup(resetStats = false) { - this.#pendingCleanup = true; - const success = this.#tryCleanup(false); - if (resetStats && success) { - this._stats &&= new _display_utils.StatTimer(); - } - return success; - } - #tryCleanup(delayed = false) { - this.#abortDelayedCleanup(); - if (!this.#pendingCleanup || this.destroyed) { - return false; - } - if (delayed) { - this.#delayedCleanupTimeout = setTimeout(() => { - this.#delayedCleanupTimeout = null; - this.#tryCleanup(false); - }, DELAYED_CLEANUP_TIMEOUT); - return false; + toString() { + const outBuf = []; + let longest = 0; + for (const { + name + } of this.times) { + longest = Math.max(name.length, longest); } for (const { - renderTasks, - operatorList - } of this._intentStates.values()) { - if (renderTasks.size > 0 || !operatorList.lastChunk) { - return false; - } + name, + start, + end + } of this.times) { + outBuf.push(`${name.padEnd(longest)} ${end - start}ms\n`); } - this._intentStates.clear(); - this.objs.clear(); - this.#pendingCleanup = false; - return true; + return outBuf.join(""); } - #abortDelayedCleanup() { - if (this.#delayedCleanupTimeout) { - clearTimeout(this.#delayedCleanupTimeout); - this.#delayedCleanupTimeout = null; - } - } - _startRenderPage(transparency, cacheKey) { - const intentState = this._intentStates.get(cacheKey); - if (!intentState) { - return; - } - this._stats?.timeEnd("Page Request"); - intentState.displayReadyCapability?.resolve(transparency); - } - _renderPageChunk(operatorListChunk, intentState) { - for (let i = 0, ii = operatorListChunk.length; i < ii; i++) { - intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]); - intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]); - } - intentState.operatorList.lastChunk = operatorListChunk.lastChunk; - intentState.operatorList.separateAnnots = operatorListChunk.separateAnnots; - for (const internalRenderTask of intentState.renderTasks) { - internalRenderTask.operatorListChanged(); - } - if (operatorListChunk.lastChunk) { - this.#tryCleanup(true); - } - } - _pumpOperatorList({ - renderingIntent, - cacheKey, - annotationStorageSerializable - }) { +} +function isValidFetchUrl(url, baseUrl) { + try { const { - map, - transfers - } = annotationStorageSerializable; - const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", { - pageIndex: this._pageIndex, - intent: renderingIntent, - cacheKey, - annotationStorage: map - }, transfers); - const reader = readableStream.getReader(); - const intentState = this._intentStates.get(cacheKey); - intentState.streamReader = reader; - const pump = () => { - reader.read().then(({ - value, - done - }) => { - if (done) { - intentState.streamReader = null; - return; - } - if (this._transport.destroyed) { - return; - } - this._renderPageChunk(value, intentState); - pump(); - }, reason => { - intentState.streamReader = null; - if (this._transport.destroyed) { - return; - } - if (intentState.operatorList) { - intentState.operatorList.lastChunk = true; - for (const internalRenderTask of intentState.renderTasks) { - internalRenderTask.operatorListChanged(); - } - this.#tryCleanup(true); - } - if (intentState.displayReadyCapability) { - intentState.displayReadyCapability.reject(reason); - } else if (intentState.opListReadCapability) { - intentState.opListReadCapability.reject(reason); - } else { - throw reason; - } - }); - }; - pump(); - } - _abortOperatorList({ - intentState, - reason, - force = false - }) { - if (!intentState.streamReader) { - return; - } - if (intentState.streamReaderCancelTimeout) { - clearTimeout(intentState.streamReaderCancelTimeout); - intentState.streamReaderCancelTimeout = null; - } - if (!force) { - if (intentState.renderTasks.size > 0) { - return; - } - if (reason instanceof _display_utils.RenderingCancelledException) { - let delay = RENDERING_CANCELLED_TIMEOUT; - if (reason.extraDelay > 0 && reason.extraDelay < 1000) { - delay += reason.extraDelay; - } - intentState.streamReaderCancelTimeout = setTimeout(() => { - intentState.streamReaderCancelTimeout = null; - this._abortOperatorList({ - intentState, - reason, - force: true - }); - }, delay); - return; - } - } - intentState.streamReader.cancel(new _util.AbortException(reason.message)).catch(() => {}); - intentState.streamReader = null; - if (this._transport.destroyed) { - return; - } - for (const [curCacheKey, curIntentState] of this._intentStates) { - if (curIntentState === intentState) { - this._intentStates.delete(curCacheKey); - break; - } - } - this.cleanup(); - } - get stats() { - return this._stats; - } -} -exports.PDFPageProxy = PDFPageProxy; -class LoopbackPort { - #listeners = new Set(); - #deferred = Promise.resolve(); - postMessage(obj, transfer) { - const event = { - data: structuredClone(obj, transfer ? { - transfer - } : null) - }; - this.#deferred.then(() => { - for (const listener of this.#listeners) { - listener.call(this, event); - } - }); - } - addEventListener(name, listener) { - this.#listeners.add(listener); - } - removeEventListener(name, listener) { - this.#listeners.delete(listener); - } - terminate() { - this.#listeners.clear(); - } -} -exports.LoopbackPort = LoopbackPort; -const PDFWorkerUtil = { - isWorkerDisabled: false, - fallbackWorkerSrc: null, - fakeWorkerId: 0 -}; -exports.PDFWorkerUtil = PDFWorkerUtil; -{ - if (_util.isNodeJS && typeof require === "function") { - PDFWorkerUtil.isWorkerDisabled = true; - PDFWorkerUtil.fallbackWorkerSrc = "./pdf.worker.js"; - } else if (typeof document === "object") { - const pdfjsFilePath = document?.currentScript?.src; - if (pdfjsFilePath) { - PDFWorkerUtil.fallbackWorkerSrc = pdfjsFilePath.replace(/(\.(?:min\.)?js)(\?.*)?$/i, ".worker$1$2"); - } - } - PDFWorkerUtil.isSameOrigin = function (baseUrl, otherUrl) { - let base; - try { - base = new URL(baseUrl); - if (!base.origin || base.origin === "null") { - return false; - } - } catch { - return false; - } - const other = new URL(otherUrl, base); - return base.origin === other.origin; - }; - PDFWorkerUtil.createCDNWrapper = function (url) { - const wrapper = `importScripts("${url}");`; - return URL.createObjectURL(new Blob([wrapper])); - }; -} -class PDFWorker { - static #workerPorts; - constructor({ - name = null, - port = null, - verbosity = (0, _util.getVerbosityLevel)() - } = {}) { - this.name = name; - this.destroyed = false; - this.verbosity = verbosity; - this._readyCapability = new _util.PromiseCapability(); - this._port = null; - this._webWorker = null; - this._messageHandler = null; - if (port) { - if (PDFWorker.#workerPorts?.has(port)) { - throw new Error("Cannot use more than one PDFWorker per port."); - } - (PDFWorker.#workerPorts ||= new WeakMap()).set(port, this); - this._initializeFromPort(port); - return; - } - this._initialize(); - } - get promise() { - return this._readyCapability.promise; - } - get port() { - return this._port; - } - get messageHandler() { - return this._messageHandler; - } - _initializeFromPort(port) { - this._port = port; - this._messageHandler = new _message_handler.MessageHandler("main", "worker", port); - this._messageHandler.on("ready", function () {}); - this._readyCapability.resolve(); - this._messageHandler.send("configure", { - verbosity: this.verbosity - }); - } - _initialize() { - if (!PDFWorkerUtil.isWorkerDisabled && !PDFWorker._mainThreadWorkerMessageHandler) { - let { - workerSrc - } = PDFWorker; - try { - if (!PDFWorkerUtil.isSameOrigin(window.location.href, workerSrc)) { - workerSrc = PDFWorkerUtil.createCDNWrapper(new URL(workerSrc, window.location).href); - } - const worker = new Worker(workerSrc); - const messageHandler = new _message_handler.MessageHandler("main", "worker", worker); - const terminateEarly = () => { - worker.removeEventListener("error", onWorkerError); - messageHandler.destroy(); - worker.terminate(); - if (this.destroyed) { - this._readyCapability.reject(new Error("Worker was destroyed")); - } else { - this._setupFakeWorker(); - } - }; - const onWorkerError = () => { - if (!this._webWorker) { - terminateEarly(); - } - }; - worker.addEventListener("error", onWorkerError); - messageHandler.on("test", data => { - worker.removeEventListener("error", onWorkerError); - if (this.destroyed) { - terminateEarly(); - return; - } - if (data) { - this._messageHandler = messageHandler; - this._port = worker; - this._webWorker = worker; - this._readyCapability.resolve(); - messageHandler.send("configure", { - verbosity: this.verbosity - }); - } else { - this._setupFakeWorker(); - messageHandler.destroy(); - worker.terminate(); - } - }); - messageHandler.on("ready", data => { - worker.removeEventListener("error", onWorkerError); - if (this.destroyed) { - terminateEarly(); - return; - } - try { - sendTest(); - } catch { - this._setupFakeWorker(); - } - }); - const sendTest = () => { - const testObj = new Uint8Array(); - messageHandler.send("test", testObj, [testObj.buffer]); - }; - sendTest(); - return; - } catch { - (0, _util.info)("The worker has been disabled."); - } - } - this._setupFakeWorker(); - } - _setupFakeWorker() { - if (!PDFWorkerUtil.isWorkerDisabled) { - (0, _util.warn)("Setting up fake worker."); - PDFWorkerUtil.isWorkerDisabled = true; - } - PDFWorker._setupFakeWorkerGlobal.then(WorkerMessageHandler => { - if (this.destroyed) { - this._readyCapability.reject(new Error("Worker was destroyed")); - return; - } - const port = new LoopbackPort(); - this._port = port; - const id = `fake${PDFWorkerUtil.fakeWorkerId++}`; - const workerHandler = new _message_handler.MessageHandler(id + "_worker", id, port); - WorkerMessageHandler.setup(workerHandler, port); - const messageHandler = new _message_handler.MessageHandler(id, id + "_worker", port); - this._messageHandler = messageHandler; - this._readyCapability.resolve(); - messageHandler.send("configure", { - verbosity: this.verbosity - }); - }).catch(reason => { - this._readyCapability.reject(new Error(`Setting up fake worker failed: "${reason.message}".`)); - }); - } - destroy() { - this.destroyed = true; - if (this._webWorker) { - this._webWorker.terminate(); - this._webWorker = null; - } - PDFWorker.#workerPorts?.delete(this._port); - this._port = null; - if (this._messageHandler) { - this._messageHandler.destroy(); - this._messageHandler = null; - } - } - static fromPort(params) { - if (!params?.port) { - throw new Error("PDFWorker.fromPort - invalid method signature."); - } - const cachedPort = this.#workerPorts?.get(params.port); - if (cachedPort) { - if (cachedPort._pendingDestroy) { - throw new Error("PDFWorker.fromPort - the worker is being destroyed.\n" + "Please remember to await `PDFDocumentLoadingTask.destroy()`-calls."); - } - return cachedPort; - } - return new PDFWorker(params); - } - static get workerSrc() { - if (_worker_options.GlobalWorkerOptions.workerSrc) { - return _worker_options.GlobalWorkerOptions.workerSrc; - } - if (PDFWorkerUtil.fallbackWorkerSrc !== null) { - if (!_util.isNodeJS) { - (0, _display_utils.deprecated)('No "GlobalWorkerOptions.workerSrc" specified.'); - } - return PDFWorkerUtil.fallbackWorkerSrc; - } - throw new Error('No "GlobalWorkerOptions.workerSrc" specified.'); - } - static get _mainThreadWorkerMessageHandler() { - try { - return globalThis.pdfjsWorker?.WorkerMessageHandler || null; - } catch { - return null; - } - } - static get _setupFakeWorkerGlobal() { - const loader = async () => { - const mainWorkerMessageHandler = this._mainThreadWorkerMessageHandler; - if (mainWorkerMessageHandler) { - return mainWorkerMessageHandler; - } - if (_util.isNodeJS && typeof require === "function") { - const worker = eval("require")(this.workerSrc); - return worker.WorkerMessageHandler; - } - await (0, _display_utils.loadScript)(this.workerSrc); - return window.pdfjsWorker.WorkerMessageHandler; - }; - return (0, _util.shadow)(this, "_setupFakeWorkerGlobal", loader()); - } -} -exports.PDFWorker = PDFWorker; -class WorkerTransport { - #methodPromises = new Map(); - #pageCache = new Map(); - #pagePromises = new Map(); - #passwordCapability = null; - constructor(messageHandler, loadingTask, networkStream, params, factory) { - this.messageHandler = messageHandler; - this.loadingTask = loadingTask; - this.commonObjs = new PDFObjects(); - this.fontLoader = new _font_loader.FontLoader({ - ownerDocument: params.ownerDocument, - styleElement: params.styleElement - }); - this._params = params; - this.canvasFactory = factory.canvasFactory; - this.filterFactory = factory.filterFactory; - this.cMapReaderFactory = factory.cMapReaderFactory; - this.standardFontDataFactory = factory.standardFontDataFactory; - this.destroyed = false; - this.destroyCapability = null; - this._networkStream = networkStream; - this._fullReader = null; - this._lastProgress = null; - this.downloadInfoCapability = new _util.PromiseCapability(); - this.setupMessageHandler(); - } - #cacheSimpleMethod(name, data = null) { - const cachedPromise = this.#methodPromises.get(name); - if (cachedPromise) { - return cachedPromise; - } - const promise = this.messageHandler.sendWithPromise(name, data); - this.#methodPromises.set(name, promise); - return promise; - } - get annotationStorage() { - return (0, _util.shadow)(this, "annotationStorage", new _annotation_storage.AnnotationStorage()); - } - getRenderingIntent(intent, annotationMode = _util.AnnotationMode.ENABLE, printAnnotationStorage = null, isOpList = false) { - let renderingIntent = _util.RenderingIntentFlag.DISPLAY; - let annotationStorageSerializable = _annotation_storage.SerializableEmpty; - switch (intent) { - case "any": - renderingIntent = _util.RenderingIntentFlag.ANY; - break; - case "display": - break; - case "print": - renderingIntent = _util.RenderingIntentFlag.PRINT; - break; - default: - (0, _util.warn)(`getRenderingIntent - invalid intent: ${intent}`); - } - switch (annotationMode) { - case _util.AnnotationMode.DISABLE: - renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_DISABLE; - break; - case _util.AnnotationMode.ENABLE: - break; - case _util.AnnotationMode.ENABLE_FORMS: - renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_FORMS; - break; - case _util.AnnotationMode.ENABLE_STORAGE: - renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_STORAGE; - const annotationStorage = renderingIntent & _util.RenderingIntentFlag.PRINT && printAnnotationStorage instanceof _annotation_storage.PrintAnnotationStorage ? printAnnotationStorage : this.annotationStorage; - annotationStorageSerializable = annotationStorage.serializable; - break; - default: - (0, _util.warn)(`getRenderingIntent - invalid annotationMode: ${annotationMode}`); - } - if (isOpList) { - renderingIntent += _util.RenderingIntentFlag.OPLIST; - } - return { - renderingIntent, - cacheKey: `${renderingIntent}_${annotationStorageSerializable.hash}`, - annotationStorageSerializable - }; - } - destroy() { - if (this.destroyCapability) { - return this.destroyCapability.promise; - } - this.destroyed = true; - this.destroyCapability = new _util.PromiseCapability(); - this.#passwordCapability?.reject(new Error("Worker was destroyed during onPassword callback")); - const waitOn = []; - for (const page of this.#pageCache.values()) { - waitOn.push(page._destroy()); - } - this.#pageCache.clear(); - this.#pagePromises.clear(); - if (this.hasOwnProperty("annotationStorage")) { - this.annotationStorage.resetModified(); - } - const terminated = this.messageHandler.sendWithPromise("Terminate", null); - waitOn.push(terminated); - Promise.all(waitOn).then(() => { - this.commonObjs.clear(); - this.fontLoader.clear(); - this.#methodPromises.clear(); - this.filterFactory.destroy(); - this._networkStream?.cancelAllRequests(new _util.AbortException("Worker was terminated.")); - if (this.messageHandler) { - this.messageHandler.destroy(); - this.messageHandler = null; - } - this.destroyCapability.resolve(); - }, this.destroyCapability.reject); - return this.destroyCapability.promise; - } - setupMessageHandler() { - const { - messageHandler, - loadingTask - } = this; - messageHandler.on("GetReader", (data, sink) => { - (0, _util.assert)(this._networkStream, "GetReader - no `IPDFStream` instance available."); - this._fullReader = this._networkStream.getFullReader(); - this._fullReader.onProgress = evt => { - this._lastProgress = { - loaded: evt.loaded, - total: evt.total - }; - }; - sink.onPull = () => { - this._fullReader.read().then(function ({ - value, - done - }) { - if (done) { - sink.close(); - return; - } - (0, _util.assert)(value instanceof ArrayBuffer, "GetReader - expected an ArrayBuffer."); - sink.enqueue(new Uint8Array(value), 1, [value]); - }).catch(reason => { - sink.error(reason); - }); - }; - sink.onCancel = reason => { - this._fullReader.cancel(reason); - sink.ready.catch(readyReason => { - if (this.destroyed) { - return; - } - throw readyReason; - }); - }; - }); - messageHandler.on("ReaderHeadersReady", data => { - const headersCapability = new _util.PromiseCapability(); - const fullReader = this._fullReader; - fullReader.headersReady.then(() => { - if (!fullReader.isStreamingSupported || !fullReader.isRangeSupported) { - if (this._lastProgress) { - loadingTask.onProgress?.(this._lastProgress); - } - fullReader.onProgress = evt => { - loadingTask.onProgress?.({ - loaded: evt.loaded, - total: evt.total - }); - }; - } - headersCapability.resolve({ - isStreamingSupported: fullReader.isStreamingSupported, - isRangeSupported: fullReader.isRangeSupported, - contentLength: fullReader.contentLength - }); - }, headersCapability.reject); - return headersCapability.promise; - }); - messageHandler.on("GetRangeReader", (data, sink) => { - (0, _util.assert)(this._networkStream, "GetRangeReader - no `IPDFStream` instance available."); - const rangeReader = this._networkStream.getRangeReader(data.begin, data.end); - if (!rangeReader) { - sink.close(); - return; - } - sink.onPull = () => { - rangeReader.read().then(function ({ - value, - done - }) { - if (done) { - sink.close(); - return; - } - (0, _util.assert)(value instanceof ArrayBuffer, "GetRangeReader - expected an ArrayBuffer."); - sink.enqueue(new Uint8Array(value), 1, [value]); - }).catch(reason => { - sink.error(reason); - }); - }; - sink.onCancel = reason => { - rangeReader.cancel(reason); - sink.ready.catch(readyReason => { - if (this.destroyed) { - return; - } - throw readyReason; - }); - }; - }); - messageHandler.on("GetDoc", ({ - pdfInfo - }) => { - this._numPages = pdfInfo.numPages; - this._htmlForXfa = pdfInfo.htmlForXfa; - delete pdfInfo.htmlForXfa; - loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this)); - }); - messageHandler.on("DocException", function (ex) { - let reason; - switch (ex.name) { - case "PasswordException": - reason = new _util.PasswordException(ex.message, ex.code); - break; - case "InvalidPDFException": - reason = new _util.InvalidPDFException(ex.message); - break; - case "MissingPDFException": - reason = new _util.MissingPDFException(ex.message); - break; - case "UnexpectedResponseException": - reason = new _util.UnexpectedResponseException(ex.message, ex.status); - break; - case "UnknownErrorException": - reason = new _util.UnknownErrorException(ex.message, ex.details); - break; - default: - (0, _util.unreachable)("DocException - expected a valid Error."); - } - loadingTask._capability.reject(reason); - }); - messageHandler.on("PasswordRequest", exception => { - this.#passwordCapability = new _util.PromiseCapability(); - if (loadingTask.onPassword) { - const updatePassword = password => { - if (password instanceof Error) { - this.#passwordCapability.reject(password); - } else { - this.#passwordCapability.resolve({ - password - }); - } - }; - try { - loadingTask.onPassword(updatePassword, exception.code); - } catch (ex) { - this.#passwordCapability.reject(ex); - } - } else { - this.#passwordCapability.reject(new _util.PasswordException(exception.message, exception.code)); - } - return this.#passwordCapability.promise; - }); - messageHandler.on("DataLoaded", data => { - loadingTask.onProgress?.({ - loaded: data.length, - total: data.length - }); - this.downloadInfoCapability.resolve(data); - }); - messageHandler.on("StartRenderPage", data => { - if (this.destroyed) { - return; - } - const page = this.#pageCache.get(data.pageIndex); - page._startRenderPage(data.transparency, data.cacheKey); - }); - messageHandler.on("commonobj", ([id, type, exportedData]) => { - if (this.destroyed) { - return; - } - if (this.commonObjs.has(id)) { - return; - } - switch (type) { - case "Font": - const params = this._params; - if ("error" in exportedData) { - const exportedError = exportedData.error; - (0, _util.warn)(`Error during font loading: ${exportedError}`); - this.commonObjs.resolve(id, exportedError); - break; - } - const inspectFont = params.pdfBug && globalThis.FontInspector?.enabled ? (font, url) => globalThis.FontInspector.fontAdded(font, url) : null; - const font = new _font_loader.FontFaceObject(exportedData, { - isEvalSupported: params.isEvalSupported, - disableFontFace: params.disableFontFace, - ignoreErrors: params.ignoreErrors, - inspectFont - }); - this.fontLoader.bind(font).catch(reason => { - return messageHandler.sendWithPromise("FontFallback", { - id - }); - }).finally(() => { - if (!params.fontExtraProperties && font.data) { - font.data = null; - } - this.commonObjs.resolve(id, font); - }); - break; - case "FontPath": - case "Image": - case "Pattern": - this.commonObjs.resolve(id, exportedData); - break; - default: - throw new Error(`Got unknown common object type ${type}`); - } - }); - messageHandler.on("obj", ([id, pageIndex, type, imageData]) => { - if (this.destroyed) { - return; - } - const pageProxy = this.#pageCache.get(pageIndex); - if (pageProxy.objs.has(id)) { - return; - } - switch (type) { - case "Image": - pageProxy.objs.resolve(id, imageData); - if (imageData) { - let length; - if (imageData.bitmap) { - const { - width, - height - } = imageData; - length = width * height * 4; - } else { - length = imageData.data?.length || 0; - } - if (length > _util.MAX_IMAGE_SIZE_TO_CACHE) { - pageProxy._maybeCleanupAfterRender = true; - } - } - break; - case "Pattern": - pageProxy.objs.resolve(id, imageData); - break; - default: - throw new Error(`Got unknown object type ${type}`); - } - }); - messageHandler.on("DocProgress", data => { - if (this.destroyed) { - return; - } - loadingTask.onProgress?.({ - loaded: data.loaded, - total: data.total - }); - }); - messageHandler.on("FetchBuiltInCMap", data => { - if (this.destroyed) { - return Promise.reject(new Error("Worker was destroyed.")); - } - if (!this.cMapReaderFactory) { - return Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.")); - } - return this.cMapReaderFactory.fetch(data); - }); - messageHandler.on("FetchStandardFontData", data => { - if (this.destroyed) { - return Promise.reject(new Error("Worker was destroyed.")); - } - if (!this.standardFontDataFactory) { - return Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.")); - } - return this.standardFontDataFactory.fetch(data); - }); - } - getData() { - return this.messageHandler.sendWithPromise("GetData", null); - } - saveDocument() { - if (this.annotationStorage.size <= 0) { - (0, _util.warn)("saveDocument called while `annotationStorage` is empty, " + "please use the getData-method instead."); - } - const { - map, - transfers - } = this.annotationStorage.serializable; - return this.messageHandler.sendWithPromise("SaveDocument", { - isPureXfa: !!this._htmlForXfa, - numPages: this._numPages, - annotationStorage: map, - filename: this._fullReader?.filename ?? null - }, transfers).finally(() => { - this.annotationStorage.resetModified(); - }); - } - getPage(pageNumber) { - if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this._numPages) { - return Promise.reject(new Error("Invalid page request.")); - } - const pageIndex = pageNumber - 1, - cachedPromise = this.#pagePromises.get(pageIndex); - if (cachedPromise) { - return cachedPromise; - } - const promise = this.messageHandler.sendWithPromise("GetPage", { - pageIndex - }).then(pageInfo => { - if (this.destroyed) { - throw new Error("Transport destroyed"); - } - const page = new PDFPageProxy(pageIndex, pageInfo, this, this._params.pdfBug); - this.#pageCache.set(pageIndex, page); - return page; - }); - this.#pagePromises.set(pageIndex, promise); - return promise; - } - getPageIndex(ref) { - if (typeof ref !== "object" || ref === null || !Number.isInteger(ref.num) || ref.num < 0 || !Number.isInteger(ref.gen) || ref.gen < 0) { - return Promise.reject(new Error("Invalid pageIndex request.")); - } - return this.messageHandler.sendWithPromise("GetPageIndex", { - num: ref.num, - gen: ref.gen - }); - } - getAnnotations(pageIndex, intent) { - return this.messageHandler.sendWithPromise("GetAnnotations", { - pageIndex, - intent - }); - } - getFieldObjects() { - return this.#cacheSimpleMethod("GetFieldObjects"); - } - hasJSActions() { - return this.#cacheSimpleMethod("HasJSActions"); - } - getCalculationOrderIds() { - return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null); - } - getDestinations() { - return this.messageHandler.sendWithPromise("GetDestinations", null); - } - getDestination(id) { - if (typeof id !== "string") { - return Promise.reject(new Error("Invalid destination request.")); - } - return this.messageHandler.sendWithPromise("GetDestination", { - id - }); - } - getPageLabels() { - return this.messageHandler.sendWithPromise("GetPageLabels", null); - } - getPageLayout() { - return this.messageHandler.sendWithPromise("GetPageLayout", null); - } - getPageMode() { - return this.messageHandler.sendWithPromise("GetPageMode", null); - } - getViewerPreferences() { - return this.messageHandler.sendWithPromise("GetViewerPreferences", null); - } - getOpenAction() { - return this.messageHandler.sendWithPromise("GetOpenAction", null); - } - getAttachments() { - return this.messageHandler.sendWithPromise("GetAttachments", null); - } - getDocJSActions() { - return this.#cacheSimpleMethod("GetDocJSActions"); - } - getPageJSActions(pageIndex) { - return this.messageHandler.sendWithPromise("GetPageJSActions", { - pageIndex - }); - } - getStructTree(pageIndex) { - return this.messageHandler.sendWithPromise("GetStructTree", { - pageIndex - }); - } - getOutline() { - return this.messageHandler.sendWithPromise("GetOutline", null); - } - getOptionalContentConfig() { - return this.messageHandler.sendWithPromise("GetOptionalContentConfig", null).then(results => { - return new _optional_content_config.OptionalContentConfig(results); - }); - } - getPermissions() { - return this.messageHandler.sendWithPromise("GetPermissions", null); - } - getMetadata() { - const name = "GetMetadata", - cachedPromise = this.#methodPromises.get(name); - if (cachedPromise) { - return cachedPromise; - } - const promise = this.messageHandler.sendWithPromise(name, null).then(results => { - return { - info: results[0], - metadata: results[1] ? new _metadata.Metadata(results[1]) : null, - contentDispositionFilename: this._fullReader?.filename ?? null, - contentLength: this._fullReader?.contentLength ?? null - }; - }); - this.#methodPromises.set(name, promise); - return promise; - } - getMarkInfo() { - return this.messageHandler.sendWithPromise("GetMarkInfo", null); - } - async startCleanup(keepLoadedFonts = false) { - if (this.destroyed) { - return; - } - await this.messageHandler.sendWithPromise("Cleanup", null); - for (const page of this.#pageCache.values()) { - const cleanupSuccessful = page.cleanup(); - if (!cleanupSuccessful) { - throw new Error(`startCleanup: Page ${page.pageNumber} is currently rendering.`); - } - } - this.commonObjs.clear(); - if (!keepLoadedFonts) { - this.fontLoader.clear(); - } - this.#methodPromises.clear(); - this.filterFactory.destroy(true); - } - get loadingParams() { - const { - disableAutoFetch, - enableXfa - } = this._params; - return (0, _util.shadow)(this, "loadingParams", { - disableAutoFetch, - enableXfa - }); - } -} -class PDFObjects { - #objs = Object.create(null); - #ensureObj(objId) { - return this.#objs[objId] ||= { - capability: new _util.PromiseCapability(), - data: null - }; - } - get(objId, callback = null) { - if (callback) { - const obj = this.#ensureObj(objId); - obj.capability.promise.then(() => callback(obj.data)); - return null; - } - const obj = this.#objs[objId]; - if (!obj?.capability.settled) { - throw new Error(`Requesting object that isn't resolved yet ${objId}.`); - } - return obj.data; - } - has(objId) { - const obj = this.#objs[objId]; - return obj?.capability.settled || false; - } - resolve(objId, data = null) { - const obj = this.#ensureObj(objId); - obj.data = data; - obj.capability.resolve(); - } - clear() { - for (const objId in this.#objs) { - const { - data - } = this.#objs[objId]; - data?.bitmap?.close(); - } - this.#objs = Object.create(null); - } -} -class RenderTask { - #internalRenderTask = null; - constructor(internalRenderTask) { - this.#internalRenderTask = internalRenderTask; - this.onContinue = null; - } - get promise() { - return this.#internalRenderTask.capability.promise; - } - cancel(extraDelay = 0) { - this.#internalRenderTask.cancel(null, extraDelay); - } - get separateAnnots() { - const { - separateAnnots - } = this.#internalRenderTask.operatorList; - if (!separateAnnots) { - return false; - } - const { - annotationCanvasMap - } = this.#internalRenderTask; - return separateAnnots.form || separateAnnots.canvas && annotationCanvasMap?.size > 0; - } -} -exports.RenderTask = RenderTask; -class InternalRenderTask { - static #canvasInUse = new WeakSet(); - constructor({ - callback, - params, - objs, - commonObjs, - annotationCanvasMap, - operatorList, - pageIndex, - canvasFactory, - filterFactory, - useRequestAnimationFrame = false, - pdfBug = false, - pageColors = null - }) { - this.callback = callback; - this.params = params; - this.objs = objs; - this.commonObjs = commonObjs; - this.annotationCanvasMap = annotationCanvasMap; - this.operatorListIdx = null; - this.operatorList = operatorList; - this._pageIndex = pageIndex; - this.canvasFactory = canvasFactory; - this.filterFactory = filterFactory; - this._pdfBug = pdfBug; - this.pageColors = pageColors; - this.running = false; - this.graphicsReadyCallback = null; - this.graphicsReady = false; - this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== "undefined"; - this.cancelled = false; - this.capability = new _util.PromiseCapability(); - this.task = new RenderTask(this); - this._cancelBound = this.cancel.bind(this); - this._continueBound = this._continue.bind(this); - this._scheduleNextBound = this._scheduleNext.bind(this); - this._nextBound = this._next.bind(this); - this._canvas = params.canvasContext.canvas; - } - get completed() { - return this.capability.promise.catch(function () {}); - } - initializeGraphics({ - transparency = false, - optionalContentConfig - }) { - if (this.cancelled) { - return; - } - if (this._canvas) { - if (InternalRenderTask.#canvasInUse.has(this._canvas)) { - throw new Error("Cannot use the same canvas during multiple render() operations. " + "Use different canvas or ensure previous operations were " + "cancelled or completed."); - } - InternalRenderTask.#canvasInUse.add(this._canvas); - } - if (this._pdfBug && globalThis.StepperManager?.enabled) { - this.stepper = globalThis.StepperManager.create(this._pageIndex); - this.stepper.init(this.operatorList); - this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint(); - } - const { - canvasContext, - viewport, - transform, - background - } = this.params; - this.gfx = new _canvas.CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, { - optionalContentConfig - }, this.annotationCanvasMap, this.pageColors); - this.gfx.beginDrawing({ - transform, - viewport, - transparency, - background - }); - this.operatorListIdx = 0; - this.graphicsReady = true; - this.graphicsReadyCallback?.(); - } - cancel(error = null, extraDelay = 0) { - this.running = false; - this.cancelled = true; - this.gfx?.endDrawing(); - InternalRenderTask.#canvasInUse.delete(this._canvas); - this.callback(error || new _display_utils.RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, extraDelay)); - } - operatorListChanged() { - if (!this.graphicsReady) { - this.graphicsReadyCallback ||= this._continueBound; - return; - } - this.stepper?.updateOperatorList(this.operatorList); - if (this.running) { - return; - } - this._continue(); - } - _continue() { - this.running = true; - if (this.cancelled) { - return; - } - if (this.task.onContinue) { - this.task.onContinue(this._scheduleNextBound); - } else { - this._scheduleNext(); - } - } - _scheduleNext() { - if (this._useRequestAnimationFrame) { - window.requestAnimationFrame(() => { - this._nextBound().catch(this._cancelBound); - }); - } else { - Promise.resolve().then(this._nextBound).catch(this._cancelBound); - } - } - async _next() { - if (this.cancelled) { - return; - } - this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper); - if (this.operatorListIdx === this.operatorList.argsArray.length) { - this.running = false; - if (this.operatorList.lastChunk) { - this.gfx.endDrawing(); - InternalRenderTask.#canvasInUse.delete(this._canvas); - this.callback(); - } - } - } -} -const version = '3.11.174'; -exports.version = version; -const build = 'ce8716743'; -exports.build = build; - -/***/ }), -/* 3 */ -/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.SerializableEmpty = exports.PrintAnnotationStorage = exports.AnnotationStorage = void 0; -var _util = __w_pdfjs_require__(1); -var _editor = __w_pdfjs_require__(4); -var _murmurhash = __w_pdfjs_require__(8); -const SerializableEmpty = Object.freeze({ - map: null, - hash: "", - transfers: undefined -}); -exports.SerializableEmpty = SerializableEmpty; -class AnnotationStorage { - #modified = false; - #storage = new Map(); - constructor() { - this.onSetModified = null; - this.onResetModified = null; - this.onAnnotationEditor = null; - } - getValue(key, defaultValue) { - const value = this.#storage.get(key); - if (value === undefined) { - return defaultValue; - } - return Object.assign(defaultValue, value); - } - getRawValue(key) { - return this.#storage.get(key); - } - remove(key) { - this.#storage.delete(key); - if (this.#storage.size === 0) { - this.resetModified(); - } - if (typeof this.onAnnotationEditor === "function") { - for (const value of this.#storage.values()) { - if (value instanceof _editor.AnnotationEditor) { - return; - } - } - this.onAnnotationEditor(null); - } - } - setValue(key, value) { - const obj = this.#storage.get(key); - let modified = false; - if (obj !== undefined) { - for (const [entry, val] of Object.entries(value)) { - if (obj[entry] !== val) { - modified = true; - obj[entry] = val; - } - } - } else { - modified = true; - this.#storage.set(key, value); - } - if (modified) { - this.#setModified(); - } - if (value instanceof _editor.AnnotationEditor && typeof this.onAnnotationEditor === "function") { - this.onAnnotationEditor(value.constructor._type); - } - } - has(key) { - return this.#storage.has(key); - } - getAll() { - return this.#storage.size > 0 ? (0, _util.objectFromMap)(this.#storage) : null; - } - setAll(obj) { - for (const [key, val] of Object.entries(obj)) { - this.setValue(key, val); - } - } - get size() { - return this.#storage.size; - } - #setModified() { - if (!this.#modified) { - this.#modified = true; - if (typeof this.onSetModified === "function") { - this.onSetModified(); - } - } - } - resetModified() { - if (this.#modified) { - this.#modified = false; - if (typeof this.onResetModified === "function") { - this.onResetModified(); - } - } - } - get print() { - return new PrintAnnotationStorage(this); - } - get serializable() { - if (this.#storage.size === 0) { - return SerializableEmpty; - } - const map = new Map(), - hash = new _murmurhash.MurmurHash3_64(), - transfers = []; - const context = Object.create(null); - let hasBitmap = false; - for (const [key, val] of this.#storage) { - const serialized = val instanceof _editor.AnnotationEditor ? val.serialize(false, context) : val; - if (serialized) { - map.set(key, serialized); - hash.update(`${key}:${JSON.stringify(serialized)}`); - hasBitmap ||= !!serialized.bitmap; - } - } - if (hasBitmap) { - for (const value of map.values()) { - if (value.bitmap) { - transfers.push(value.bitmap); - } - } - } - return map.size > 0 ? { - map, - hash: hash.hexdigest(), - transfers - } : SerializableEmpty; - } -} -exports.AnnotationStorage = AnnotationStorage; -class PrintAnnotationStorage extends AnnotationStorage { - #serializable; - constructor(parent) { - super(); - const { - map, - hash, - transfers - } = parent.serializable; - const clone = structuredClone(map, transfers ? { - transfer: transfers - } : null); - this.#serializable = { - map: clone, - hash, - transfers - }; - } - get print() { - (0, _util.unreachable)("Should not call PrintAnnotationStorage.print"); - } - get serializable() { - return this.#serializable; - } -} -exports.PrintAnnotationStorage = PrintAnnotationStorage; - -/***/ }), -/* 4 */ -/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.AnnotationEditor = void 0; -var _tools = __w_pdfjs_require__(5); -var _util = __w_pdfjs_require__(1); -var _display_utils = __w_pdfjs_require__(6); -class AnnotationEditor { - #altText = ""; - #altTextDecorative = false; - #altTextButton = null; - #altTextTooltip = null; - #altTextTooltipTimeout = null; - #keepAspectRatio = false; - #resizersDiv = null; - #boundFocusin = this.focusin.bind(this); - #boundFocusout = this.focusout.bind(this); - #hasBeenClicked = false; - #isEditing = false; - #isInEditMode = false; - _initialOptions = Object.create(null); - _uiManager = null; - _focusEventsAllowed = true; - _l10nPromise = null; - #isDraggable = false; - #zIndex = AnnotationEditor._zIndex++; - static _borderLineWidth = -1; - static _colorManager = new _tools.ColorManager(); - static _zIndex = 1; - static SMALL_EDITOR_SIZE = 0; - constructor(parameters) { - if (this.constructor === AnnotationEditor) { - (0, _util.unreachable)("Cannot initialize AnnotationEditor."); - } - this.parent = parameters.parent; - this.id = parameters.id; - this.width = this.height = null; - this.pageIndex = parameters.parent.pageIndex; - this.name = parameters.name; - this.div = null; - this._uiManager = parameters.uiManager; - this.annotationElementId = null; - this._willKeepAspectRatio = false; - this._initialOptions.isCentered = parameters.isCentered; - this._structTreeParentId = null; - const { - rotation, - rawDims: { - pageWidth, - pageHeight, - pageX, - pageY - } - } = this.parent.viewport; - this.rotation = rotation; - this.pageRotation = (360 + rotation - this._uiManager.viewParameters.rotation) % 360; - this.pageDimensions = [pageWidth, pageHeight]; - this.pageTranslation = [pageX, pageY]; - const [width, height] = this.parentDimensions; - this.x = parameters.x / width; - this.y = parameters.y / height; - this.isAttachedToDOM = false; - this.deleted = false; - } - get editorType() { - return Object.getPrototypeOf(this).constructor._type; - } - static get _defaultLineColor() { - return (0, _util.shadow)(this, "_defaultLineColor", this._colorManager.getHexCode("CanvasText")); - } - static deleteAnnotationElement(editor) { - const fakeEditor = new FakeEditor({ - id: editor.parent.getNextId(), - parent: editor.parent, - uiManager: editor._uiManager - }); - fakeEditor.annotationElementId = editor.annotationElementId; - fakeEditor.deleted = true; - fakeEditor._uiManager.addToAnnotationStorage(fakeEditor); - } - static initialize(l10n, options = null) { - AnnotationEditor._l10nPromise ||= new Map(["editor_alt_text_button_label", "editor_alt_text_edit_button_label", "editor_alt_text_decorative_tooltip"].map(str => [str, l10n.get(str)])); - if (options?.strings) { - for (const str of options.strings) { - AnnotationEditor._l10nPromise.set(str, l10n.get(str)); - } - } - if (AnnotationEditor._borderLineWidth !== -1) { - return; - } - const style = getComputedStyle(document.documentElement); - AnnotationEditor._borderLineWidth = parseFloat(style.getPropertyValue("--outline-width")) || 0; - } - static updateDefaultParams(_type, _value) {} - static get defaultPropertiesToUpdate() { - return []; - } - static isHandlingMimeForPasting(mime) { + protocol + } = baseUrl ? new URL(url, baseUrl) : new URL(url); + return protocol === "http:" || protocol === "https:"; + } catch { return false; } - static paste(item, parent) { - (0, _util.unreachable)("Not implemented"); - } - get propertiesToUpdate() { - return []; - } - get _isDraggable() { - return this.#isDraggable; - } - set _isDraggable(value) { - this.#isDraggable = value; - this.div?.classList.toggle("draggable", value); - } - center() { - const [pageWidth, pageHeight] = this.pageDimensions; - switch (this.parentRotation) { - case 90: - this.x -= this.height * pageHeight / (pageWidth * 2); - this.y += this.width * pageWidth / (pageHeight * 2); - break; - case 180: - this.x += this.width / 2; - this.y += this.height / 2; - break; - case 270: - this.x += this.height * pageHeight / (pageWidth * 2); - this.y -= this.width * pageWidth / (pageHeight * 2); - break; - default: - this.x -= this.width / 2; - this.y -= this.height / 2; - break; +} +function noContextMenu(e) { + e.preventDefault(); +} +function deprecated(details) { + console.log("Deprecated API usage: " + details); +} +let pdfDateStringRegex; +class PDFDateString { + static toDateObject(input) { + if (!input || typeof input !== "string") { + return null; } - this.fixAndSetPosition(); - } - addCommands(params) { - this._uiManager.addCommands(params); - } - get currentLayer() { - return this._uiManager.currentLayer; - } - setInBackground() { - this.div.style.zIndex = 0; - } - setInForeground() { - this.div.style.zIndex = this.#zIndex; - } - setParent(parent) { - if (parent !== null) { - this.pageIndex = parent.pageIndex; - this.pageDimensions = parent.pageDimensions; + pdfDateStringRegex ||= new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?"); + const matches = pdfDateStringRegex.exec(input); + if (!matches) { + return null; } - this.parent = parent; - } - focusin(event) { - if (!this._focusEventsAllowed) { - return; - } - if (!this.#hasBeenClicked) { - this.parent.setSelected(this); - } else { - this.#hasBeenClicked = false; + const year = parseInt(matches[1], 10); + let month = parseInt(matches[2], 10); + month = month >= 1 && month <= 12 ? month - 1 : 0; + let day = parseInt(matches[3], 10); + day = day >= 1 && day <= 31 ? day : 1; + let hour = parseInt(matches[4], 10); + hour = hour >= 0 && hour <= 23 ? hour : 0; + let minute = parseInt(matches[5], 10); + minute = minute >= 0 && minute <= 59 ? minute : 0; + let second = parseInt(matches[6], 10); + second = second >= 0 && second <= 59 ? second : 0; + const universalTimeRelation = matches[7] || "Z"; + let offsetHour = parseInt(matches[8], 10); + offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0; + let offsetMinute = parseInt(matches[9], 10) || 0; + offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0; + if (universalTimeRelation === "-") { + hour += offsetHour; + minute += offsetMinute; + } else if (universalTimeRelation === "+") { + hour -= offsetHour; + minute -= offsetMinute; } + return new Date(Date.UTC(year, month, day, hour, minute, second)); } - focusout(event) { - if (!this._focusEventsAllowed) { - return; - } - if (!this.isAttachedToDOM) { - return; - } - const target = event.relatedTarget; - if (target?.closest(`#${this.id}`)) { - return; - } - event.preventDefault(); - if (!this.parent?.isMultipleSelection) { - this.commitOrRemove(); - } +} +function getXfaPageViewport(xfaPage, { + scale = 1, + rotation = 0 +}) { + const { + width, + height + } = xfaPage.attributes.style; + const viewBox = [0, 0, parseInt(width), parseInt(height)]; + return new PageViewport({ + viewBox, + scale, + rotation + }); +} +function getRGB(color) { + if (color.startsWith("#")) { + const colorRGB = parseInt(color.slice(1), 16); + return [(colorRGB & 0xff0000) >> 16, (colorRGB & 0x00ff00) >> 8, colorRGB & 0x0000ff]; } - commitOrRemove() { - if (this.isEmpty()) { - this.remove(); - } else { - this.commit(); - } + if (color.startsWith("rgb(")) { + return color.slice(4, -1).split(",").map(x => parseInt(x)); } - commit() { - this.addToAnnotationStorage(); + if (color.startsWith("rgba(")) { + return color.slice(5, -1).split(",").map(x => parseInt(x)).slice(0, 3); } - addToAnnotationStorage() { - this._uiManager.addToAnnotationStorage(this); + warn(`Not a valid color format: "${color}"`); + return [0, 0, 0]; +} +function getColorValues(colors) { + const span = document.createElement("span"); + span.style.visibility = "hidden"; + document.body.append(span); + for (const name of colors.keys()) { + span.style.color = name; + const computedColor = window.getComputedStyle(span).color; + colors.set(name, getRGB(computedColor)); } - setAt(x, y, tx, ty) { - const [width, height] = this.parentDimensions; - [tx, ty] = this.screenToPageTranslation(tx, ty); - this.x = (x + tx) / width; - this.y = (y + ty) / height; - this.fixAndSetPosition(); - } - #translate([width, height], x, y) { - [x, y] = this.screenToPageTranslation(x, y); - this.x += x / width; - this.y += y / height; - this.fixAndSetPosition(); - } - translate(x, y) { - this.#translate(this.parentDimensions, x, y); - } - translateInPage(x, y) { - this.#translate(this.pageDimensions, x, y); - this.div.scrollIntoView({ - block: "nearest" - }); - } - drag(tx, ty) { - const [parentWidth, parentHeight] = this.parentDimensions; - this.x += tx / parentWidth; - this.y += ty / parentHeight; - if (this.parent && (this.x < 0 || this.x > 1 || this.y < 0 || this.y > 1)) { - const { - x, - y - } = this.div.getBoundingClientRect(); - if (this.parent.findNewParent(this, x, y)) { - this.x -= Math.floor(this.x); - this.y -= Math.floor(this.y); - } - } - let { - x, - y - } = this; - const [bx, by] = this.#getBaseTranslation(); - x += bx; - y += by; - this.div.style.left = `${(100 * x).toFixed(2)}%`; - this.div.style.top = `${(100 * y).toFixed(2)}%`; - this.div.scrollIntoView({ - block: "nearest" - }); - } - #getBaseTranslation() { - const [parentWidth, parentHeight] = this.parentDimensions; + span.remove(); +} +function getCurrentTransform(ctx) { + const { + a, + b, + c, + d, + e, + f + } = ctx.getTransform(); + return [a, b, c, d, e, f]; +} +function getCurrentTransformInverse(ctx) { + const { + a, + b, + c, + d, + e, + f + } = ctx.getTransform().invertSelf(); + return [a, b, c, d, e, f]; +} +function setLayerDimensions(div, viewport, mustFlip = false, mustRotate = true) { + if (viewport instanceof PageViewport) { const { - _borderLineWidth - } = AnnotationEditor; - const x = _borderLineWidth / parentWidth; - const y = _borderLineWidth / parentHeight; - switch (this.rotation) { - case 90: - return [-x, y]; - case 180: - return [x, y]; - case 270: - return [x, -y]; - default: - return [-x, -y]; - } - } - fixAndSetPosition() { - const [pageWidth, pageHeight] = this.pageDimensions; - let { - x, - y, - width, - height - } = this; - width *= pageWidth; - height *= pageHeight; - x *= pageWidth; - y *= pageHeight; - switch (this.rotation) { - case 0: - x = Math.max(0, Math.min(pageWidth - width, x)); - y = Math.max(0, Math.min(pageHeight - height, y)); - break; - case 90: - x = Math.max(0, Math.min(pageWidth - height, x)); - y = Math.min(pageHeight, Math.max(width, y)); - break; - case 180: - x = Math.min(pageWidth, Math.max(width, x)); - y = Math.min(pageHeight, Math.max(height, y)); - break; - case 270: - x = Math.min(pageWidth, Math.max(height, x)); - y = Math.max(0, Math.min(pageHeight - width, y)); - break; - } - this.x = x /= pageWidth; - this.y = y /= pageHeight; - const [bx, by] = this.#getBaseTranslation(); - x += bx; - y += by; + pageWidth, + pageHeight + } = viewport.rawDims; const { style - } = this.div; - style.left = `${(100 * x).toFixed(2)}%`; - style.top = `${(100 * y).toFixed(2)}%`; - this.moveInDOM(); - } - static #rotatePoint(x, y, angle) { - switch (angle) { - case 90: - return [y, -x]; - case 180: - return [-x, -y]; - case 270: - return [-y, x]; - default: - return [x, y]; - } - } - screenToPageTranslation(x, y) { - return AnnotationEditor.#rotatePoint(x, y, this.parentRotation); - } - pageTranslationToScreen(x, y) { - return AnnotationEditor.#rotatePoint(x, y, 360 - this.parentRotation); - } - #getRotationMatrix(rotation) { - switch (rotation) { - case 90: - { - const [pageWidth, pageHeight] = this.pageDimensions; - return [0, -pageWidth / pageHeight, pageHeight / pageWidth, 0]; - } - case 180: - return [-1, 0, 0, -1]; - case 270: - { - const [pageWidth, pageHeight] = this.pageDimensions; - return [0, pageWidth / pageHeight, -pageHeight / pageWidth, 0]; - } - default: - return [1, 0, 0, 1]; - } - } - get parentScale() { - return this._uiManager.viewParameters.realScale; - } - get parentRotation() { - return (this._uiManager.viewParameters.rotation + this.pageRotation) % 360; - } - get parentDimensions() { - const { - parentScale, - pageDimensions: [pageWidth, pageHeight] - } = this; - const scaledWidth = pageWidth * parentScale; - const scaledHeight = pageHeight * parentScale; - return _util.FeatureTest.isCSSRoundSupported ? [Math.round(scaledWidth), Math.round(scaledHeight)] : [scaledWidth, scaledHeight]; - } - setDims(width, height) { - const [parentWidth, parentHeight] = this.parentDimensions; - this.div.style.width = `${(100 * width / parentWidth).toFixed(2)}%`; - if (!this.#keepAspectRatio) { - this.div.style.height = `${(100 * height / parentHeight).toFixed(2)}%`; - } - this.#altTextButton?.classList.toggle("small", width < AnnotationEditor.SMALL_EDITOR_SIZE || height < AnnotationEditor.SMALL_EDITOR_SIZE); - } - fixDims() { - const { - style - } = this.div; - const { - height, - width - } = style; - const widthPercent = width.endsWith("%"); - const heightPercent = !this.#keepAspectRatio && height.endsWith("%"); - if (widthPercent && heightPercent) { - return; - } - const [parentWidth, parentHeight] = this.parentDimensions; - if (!widthPercent) { - style.width = `${(100 * parseFloat(width) / parentWidth).toFixed(2)}%`; - } - if (!this.#keepAspectRatio && !heightPercent) { - style.height = `${(100 * parseFloat(height) / parentHeight).toFixed(2)}%`; - } - } - getInitialTranslation() { - return [0, 0]; - } - #createResizers() { - if (this.#resizersDiv) { - return; - } - this.#resizersDiv = document.createElement("div"); - this.#resizersDiv.classList.add("resizers"); - const classes = ["topLeft", "topRight", "bottomRight", "bottomLeft"]; - if (!this._willKeepAspectRatio) { - classes.push("topMiddle", "middleRight", "bottomMiddle", "middleLeft"); - } - for (const name of classes) { - const div = document.createElement("div"); - this.#resizersDiv.append(div); - div.classList.add("resizer", name); - div.addEventListener("pointerdown", this.#resizerPointerdown.bind(this, name)); - div.addEventListener("contextmenu", _display_utils.noContextMenu); - } - this.div.prepend(this.#resizersDiv); - } - #resizerPointerdown(name, event) { - event.preventDefault(); - const { - isMac - } = _util.FeatureTest.platform; - if (event.button !== 0 || event.ctrlKey && isMac) { - return; - } - const boundResizerPointermove = this.#resizerPointermove.bind(this, name); - const savedDraggable = this._isDraggable; - this._isDraggable = false; - const pointerMoveOptions = { - passive: true, - capture: true - }; - window.addEventListener("pointermove", boundResizerPointermove, pointerMoveOptions); - const savedX = this.x; - const savedY = this.y; - const savedWidth = this.width; - const savedHeight = this.height; - const savedParentCursor = this.parent.div.style.cursor; - const savedCursor = this.div.style.cursor; - this.div.style.cursor = this.parent.div.style.cursor = window.getComputedStyle(event.target).cursor; - const pointerUpCallback = () => { - this._isDraggable = savedDraggable; - window.removeEventListener("pointerup", pointerUpCallback); - window.removeEventListener("blur", pointerUpCallback); - window.removeEventListener("pointermove", boundResizerPointermove, pointerMoveOptions); - this.parent.div.style.cursor = savedParentCursor; - this.div.style.cursor = savedCursor; - const newX = this.x; - const newY = this.y; - const newWidth = this.width; - const newHeight = this.height; - if (newX === savedX && newY === savedY && newWidth === savedWidth && newHeight === savedHeight) { - return; - } - this.addCommands({ - cmd: () => { - this.width = newWidth; - this.height = newHeight; - this.x = newX; - this.y = newY; - const [parentWidth, parentHeight] = this.parentDimensions; - this.setDims(parentWidth * newWidth, parentHeight * newHeight); - this.fixAndSetPosition(); - }, - undo: () => { - this.width = savedWidth; - this.height = savedHeight; - this.x = savedX; - this.y = savedY; - const [parentWidth, parentHeight] = this.parentDimensions; - this.setDims(parentWidth * savedWidth, parentHeight * savedHeight); - this.fixAndSetPosition(); - }, - mustExec: true - }); - }; - window.addEventListener("pointerup", pointerUpCallback); - window.addEventListener("blur", pointerUpCallback); - } - #resizerPointermove(name, event) { - const [parentWidth, parentHeight] = this.parentDimensions; - const savedX = this.x; - const savedY = this.y; - const savedWidth = this.width; - const savedHeight = this.height; - const minWidth = AnnotationEditor.MIN_SIZE / parentWidth; - const minHeight = AnnotationEditor.MIN_SIZE / parentHeight; - const round = x => Math.round(x * 10000) / 10000; - const rotationMatrix = this.#getRotationMatrix(this.rotation); - const transf = (x, y) => [rotationMatrix[0] * x + rotationMatrix[2] * y, rotationMatrix[1] * x + rotationMatrix[3] * y]; - const invRotationMatrix = this.#getRotationMatrix(360 - this.rotation); - const invTransf = (x, y) => [invRotationMatrix[0] * x + invRotationMatrix[2] * y, invRotationMatrix[1] * x + invRotationMatrix[3] * y]; - let getPoint; - let getOpposite; - let isDiagonal = false; - let isHorizontal = false; - switch (name) { - case "topLeft": - isDiagonal = true; - getPoint = (w, h) => [0, 0]; - getOpposite = (w, h) => [w, h]; - break; - case "topMiddle": - getPoint = (w, h) => [w / 2, 0]; - getOpposite = (w, h) => [w / 2, h]; - break; - case "topRight": - isDiagonal = true; - getPoint = (w, h) => [w, 0]; - getOpposite = (w, h) => [0, h]; - break; - case "middleRight": - isHorizontal = true; - getPoint = (w, h) => [w, h / 2]; - getOpposite = (w, h) => [0, h / 2]; - break; - case "bottomRight": - isDiagonal = true; - getPoint = (w, h) => [w, h]; - getOpposite = (w, h) => [0, 0]; - break; - case "bottomMiddle": - getPoint = (w, h) => [w / 2, h]; - getOpposite = (w, h) => [w / 2, 0]; - break; - case "bottomLeft": - isDiagonal = true; - getPoint = (w, h) => [0, h]; - getOpposite = (w, h) => [w, 0]; - break; - case "middleLeft": - isHorizontal = true; - getPoint = (w, h) => [0, h / 2]; - getOpposite = (w, h) => [w, h / 2]; - break; - } - const point = getPoint(savedWidth, savedHeight); - const oppositePoint = getOpposite(savedWidth, savedHeight); - let transfOppositePoint = transf(...oppositePoint); - const oppositeX = round(savedX + transfOppositePoint[0]); - const oppositeY = round(savedY + transfOppositePoint[1]); - let ratioX = 1; - let ratioY = 1; - let [deltaX, deltaY] = this.screenToPageTranslation(event.movementX, event.movementY); - [deltaX, deltaY] = invTransf(deltaX / parentWidth, deltaY / parentHeight); - if (isDiagonal) { - const oldDiag = Math.hypot(savedWidth, savedHeight); - 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); - } else if (isHorizontal) { - ratioX = Math.max(minWidth, Math.min(1, Math.abs(oppositePoint[0] - point[0] - deltaX))) / savedWidth; + } = div; + const useRound = util_FeatureTest.isCSSRoundSupported; + const w = `var(--scale-factor) * ${pageWidth}px`, + h = `var(--scale-factor) * ${pageHeight}px`; + const widthStr = useRound ? `round(${w}, 1px)` : `calc(${w})`, + heightStr = useRound ? `round(${h}, 1px)` : `calc(${h})`; + if (!mustFlip || viewport.rotation % 180 === 0) { + style.width = widthStr; + style.height = heightStr; } else { - ratioY = Math.max(minHeight, Math.min(1, Math.abs(oppositePoint[1] - point[1] - deltaY))) / savedHeight; + style.width = heightStr; + style.height = widthStr; } - const newWidth = round(savedWidth * ratioX); - const newHeight = round(savedHeight * ratioY); - transfOppositePoint = transf(...getOpposite(newWidth, newHeight)); - const newX = oppositeX - transfOppositePoint[0]; - const newY = oppositeY - transfOppositePoint[1]; - this.width = newWidth; - this.height = newHeight; - this.x = newX; - this.y = newY; - this.setDims(parentWidth * newWidth, parentHeight * newHeight); - this.fixAndSetPosition(); } - async addAltTextButton() { - if (this.#altTextButton) { - return; - } - const altText = this.#altTextButton = document.createElement("button"); - altText.className = "altText"; - const msg = await AnnotationEditor._l10nPromise.get("editor_alt_text_button_label"); - altText.textContent = msg; - altText.setAttribute("aria-label", msg); - altText.tabIndex = "0"; - altText.addEventListener("contextmenu", _display_utils.noContextMenu); - altText.addEventListener("pointerdown", event => event.stopPropagation()); - altText.addEventListener("click", event => { - event.preventDefault(); - this._uiManager.editAltText(this); - }, { - capture: true + if (mustRotate) { + div.setAttribute("data-main-rotation", viewport.rotation); + } +} + +;// CONCATENATED MODULE: ./src/display/editor/toolbar.js + +class EditorToolbar { + #toolbar = null; + #colorPicker = null; + #editor; + #buttons = null; + #altText = null; + static #l10nRemove = null; + constructor(editor) { + this.#editor = editor; + EditorToolbar.#l10nRemove ||= Object.freeze({ + freetext: "pdfjs-editor-remove-freetext-button", + highlight: "pdfjs-editor-remove-highlight-button", + ink: "pdfjs-editor-remove-ink-button", + stamp: "pdfjs-editor-remove-stamp-button" }); - altText.addEventListener("keydown", event => { - if (event.target === altText && event.key === "Enter") { - event.preventDefault(); - this._uiManager.editAltText(this); - } - }); - this.#setAltTextButtonState(); - this.div.append(altText); - if (!AnnotationEditor.SMALL_EDITOR_SIZE) { - const PERCENT = 40; - AnnotationEditor.SMALL_EDITOR_SIZE = Math.min(128, Math.round(altText.getBoundingClientRect().width * (1 + PERCENT / 100))); - } - } - async #setAltTextButtonState() { - const button = this.#altTextButton; - if (!button) { - return; - } - if (!this.#altText && !this.#altTextDecorative) { - button.classList.remove("done"); - this.#altTextTooltip?.remove(); - return; - } - AnnotationEditor._l10nPromise.get("editor_alt_text_edit_button_label").then(msg => { - button.setAttribute("aria-label", msg); - }); - let tooltip = this.#altTextTooltip; - if (!tooltip) { - this.#altTextTooltip = tooltip = document.createElement("span"); - tooltip.className = "tooltip"; - tooltip.setAttribute("role", "tooltip"); - const id = tooltip.id = `alt-text-tooltip-${this.id}`; - button.setAttribute("aria-describedby", id); - const DELAY_TO_SHOW_TOOLTIP = 100; - button.addEventListener("mouseenter", () => { - this.#altTextTooltipTimeout = setTimeout(() => { - this.#altTextTooltipTimeout = null; - this.#altTextTooltip.classList.add("show"); - this._uiManager._eventBus.dispatch("reporttelemetry", { - source: this, - details: { - type: "editing", - subtype: this.editorType, - data: { - action: "alt_text_tooltip" - } - } - }); - }, DELAY_TO_SHOW_TOOLTIP); - }); - button.addEventListener("mouseleave", () => { - clearTimeout(this.#altTextTooltipTimeout); - this.#altTextTooltipTimeout = null; - this.#altTextTooltip?.classList.remove("show"); - }); - } - button.classList.add("done"); - tooltip.innerText = this.#altTextDecorative ? await AnnotationEditor._l10nPromise.get("editor_alt_text_decorative_tooltip") : this.#altText; - if (!tooltip.parentNode) { - button.append(tooltip); - } - } - getClientDimensions() { - return this.div.getBoundingClientRect(); - } - get altTextData() { - return { - altText: this.#altText, - decorative: this.#altTextDecorative - }; - } - set altTextData({ - altText, - decorative - }) { - if (this.#altText === altText && this.#altTextDecorative === decorative) { - return; - } - this.#altText = altText; - this.#altTextDecorative = decorative; - this.#setAltTextButtonState(); } render() { - this.div = document.createElement("div"); - this.div.setAttribute("data-editor-rotation", (360 - this.rotation) % 360); - this.div.className = this.name; - this.div.setAttribute("id", this.id); - this.div.setAttribute("tabIndex", 0); - this.setInForeground(); - this.div.addEventListener("focusin", this.#boundFocusin); - this.div.addEventListener("focusout", this.#boundFocusout); - const [parentWidth, parentHeight] = this.parentDimensions; - if (this.parentRotation % 180 !== 0) { - this.div.style.maxWidth = `${(100 * parentHeight / parentWidth).toFixed(2)}%`; - this.div.style.maxHeight = `${(100 * parentWidth / parentHeight).toFixed(2)}%`; - } - const [tx, ty] = this.getInitialTranslation(); - this.translate(tx, ty); - (0, _tools.bindEvents)(this, this.div, ["pointerdown"]); - return this.div; - } - pointerdown(event) { - const { - isMac - } = _util.FeatureTest.platform; - if (event.button !== 0 || event.ctrlKey && isMac) { - event.preventDefault(); - return; - } - this.#hasBeenClicked = true; - this.#setUpDragSession(event); - } - #setUpDragSession(event) { - if (!this._isDraggable) { - return; - } - const isSelected = this._uiManager.isSelected(this); - this._uiManager.setUpDragSession(); - let pointerMoveOptions, pointerMoveCallback; - if (isSelected) { - pointerMoveOptions = { - passive: true, - capture: true - }; - pointerMoveCallback = e => { - const [tx, ty] = this.screenToPageTranslation(e.movementX, e.movementY); - this._uiManager.dragSelectedEditors(tx, ty); - }; - window.addEventListener("pointermove", pointerMoveCallback, pointerMoveOptions); - } - const pointerUpCallback = () => { - window.removeEventListener("pointerup", pointerUpCallback); - window.removeEventListener("blur", pointerUpCallback); - if (isSelected) { - window.removeEventListener("pointermove", pointerMoveCallback, pointerMoveOptions); - } - this.#hasBeenClicked = false; - if (!this._uiManager.endDragSession()) { - const { - isMac - } = _util.FeatureTest.platform; - if (event.ctrlKey && !isMac || event.shiftKey || event.metaKey && isMac) { - this.parent.toggleSelected(this); - } else { - this.parent.setSelected(this); - } - } - }; - window.addEventListener("pointerup", pointerUpCallback); - window.addEventListener("blur", pointerUpCallback); - } - moveInDOM() { - this.parent?.moveEditorInDOM(this); - } - _setParentAndPosition(parent, x, y) { - parent.changeParent(this); - this.x = x; - this.y = y; - this.fixAndSetPosition(); - } - getRect(tx, ty) { - const scale = this.parentScale; - const [pageWidth, pageHeight] = this.pageDimensions; - const [pageX, pageY] = this.pageTranslation; - const shiftX = tx / scale; - const shiftY = ty / scale; - const x = this.x * pageWidth; - const y = this.y * pageHeight; - const width = this.width * pageWidth; - const height = this.height * pageHeight; - switch (this.rotation) { - case 0: - return [x + shiftX + pageX, pageHeight - y - shiftY - height + pageY, x + shiftX + width + pageX, pageHeight - y - shiftY + pageY]; - case 90: - return [x + shiftY + pageX, pageHeight - y + shiftX + pageY, x + shiftY + height + pageX, pageHeight - y + shiftX + width + pageY]; - case 180: - return [x - shiftX - width + pageX, pageHeight - y + shiftY + pageY, x - shiftX + pageX, pageHeight - y + shiftY + height + pageY]; - case 270: - return [x - shiftY - height + pageX, pageHeight - y - shiftX - width + pageY, x - shiftY + pageX, pageHeight - y - shiftX + pageY]; - default: - throw new Error("Invalid rotation"); - } - } - getRectInCurrentCoords(rect, pageHeight) { - const [x1, y1, x2, y2] = rect; - const width = x2 - x1; - const height = y2 - y1; - switch (this.rotation) { - case 0: - return [x1, pageHeight - y2, width, height]; - case 90: - return [x1, pageHeight - y1, height, width]; - case 180: - return [x2, pageHeight - y1, width, height]; - case 270: - return [x2, pageHeight - y2, height, width]; - default: - throw new Error("Invalid rotation"); - } - } - onceAdded() {} - isEmpty() { - return false; - } - enableEditMode() { - this.#isInEditMode = true; - } - disableEditMode() { - this.#isInEditMode = false; - } - isInEditMode() { - return this.#isInEditMode; - } - shouldGetKeyboardEvents() { - return false; - } - needsToBeRebuilt() { - return this.div && !this.isAttachedToDOM; - } - rebuild() { - this.div?.addEventListener("focusin", this.#boundFocusin); - this.div?.addEventListener("focusout", this.#boundFocusout); - } - serialize(isForCopying = false, context = null) { - (0, _util.unreachable)("An editor must be serializable"); - } - static deserialize(data, parent, uiManager) { - const editor = new this.prototype.constructor({ - parent, - id: parent.getNextId(), - uiManager + const editToolbar = this.#toolbar = document.createElement("div"); + editToolbar.className = "editToolbar"; + editToolbar.setAttribute("role", "toolbar"); + const signal = this.#editor._uiManager._signal; + editToolbar.addEventListener("contextmenu", noContextMenu, { + signal }); - editor.rotation = data.rotation; - const [pageWidth, pageHeight] = editor.pageDimensions; - const [x, y, width, height] = editor.getRectInCurrentCoords(data.rect, pageHeight); - editor.x = x / pageWidth; - editor.y = y / pageHeight; - editor.width = width / pageWidth; - editor.height = height / pageHeight; - return editor; + editToolbar.addEventListener("pointerdown", EditorToolbar.#pointerDown, { + signal + }); + const buttons = this.#buttons = document.createElement("div"); + buttons.className = "buttons"; + editToolbar.append(buttons); + const position = this.#editor.toolbarPosition; + if (position) { + const { + style + } = editToolbar; + const x = this.#editor._uiManager.direction === "ltr" ? 1 - position[0] : position[0]; + style.insetInlineEnd = `${100 * x}%`; + style.top = `calc(${100 * position[1]}% + var(--editor-toolbar-vert-offset))`; + } + this.#addDeleteButton(); + return editToolbar; + } + static #pointerDown(e) { + e.stopPropagation(); + } + #focusIn(e) { + this.#editor._focusEventsAllowed = false; + e.preventDefault(); + e.stopPropagation(); + } + #focusOut(e) { + this.#editor._focusEventsAllowed = true; + e.preventDefault(); + e.stopPropagation(); + } + #addListenersToElement(element) { + const signal = this.#editor._uiManager._signal; + element.addEventListener("focusin", this.#focusIn.bind(this), { + capture: true, + signal + }); + element.addEventListener("focusout", this.#focusOut.bind(this), { + capture: true, + signal + }); + element.addEventListener("contextmenu", noContextMenu, { + signal + }); + } + hide() { + this.#toolbar.classList.add("hidden"); + this.#colorPicker?.hideDropdown(); + } + show() { + this.#toolbar.classList.remove("hidden"); + this.#altText?.shown(); + } + #addDeleteButton() { + const { + editorType, + _uiManager + } = this.#editor; + const button = document.createElement("button"); + button.className = "delete"; + button.tabIndex = 0; + button.setAttribute("data-l10n-id", EditorToolbar.#l10nRemove[editorType]); + this.#addListenersToElement(button); + button.addEventListener("click", e => { + _uiManager.delete(); + }, { + signal: _uiManager._signal + }); + this.#buttons.append(button); + } + get #divider() { + const divider = document.createElement("div"); + divider.className = "divider"; + return divider; + } + async addAltText(altText) { + const button = await altText.render(); + this.#addListenersToElement(button); + this.#buttons.prepend(button, this.#divider); + this.#altText = altText; + } + addColorPicker(colorPicker) { + this.#colorPicker = colorPicker; + const button = colorPicker.renderButton(); + this.#addListenersToElement(button); + this.#buttons.prepend(button, this.#divider); } remove() { - this.div.removeEventListener("focusin", this.#boundFocusin); - this.div.removeEventListener("focusout", this.#boundFocusout); - if (!this.isEmpty()) { - this.commit(); + this.#toolbar.remove(); + this.#colorPicker?.destroy(); + this.#colorPicker = null; + } +} +class HighlightToolbar { + #buttons = null; + #toolbar = null; + #uiManager; + constructor(uiManager) { + this.#uiManager = uiManager; + } + #render() { + const editToolbar = this.#toolbar = document.createElement("div"); + editToolbar.className = "editToolbar"; + editToolbar.setAttribute("role", "toolbar"); + editToolbar.addEventListener("contextmenu", noContextMenu, { + signal: this.#uiManager._signal + }); + const buttons = this.#buttons = document.createElement("div"); + buttons.className = "buttons"; + editToolbar.append(buttons); + this.#addHighlightButton(); + return editToolbar; + } + #getLastPoint(boxes, isLTR) { + let lastY = 0; + let lastX = 0; + for (const box of boxes) { + const y = box.y + box.height; + if (y < lastY) { + continue; + } + const x = box.x + (isLTR ? box.width : 0); + if (y > lastY) { + lastX = x; + lastY = y; + continue; + } + if (isLTR) { + if (x > lastX) { + lastX = x; + } + } else if (x < lastX) { + lastX = x; + } } - if (this.parent) { - this.parent.remove(this); - } else { - this._uiManager.removeEditor(this); - } - this.#altTextButton?.remove(); - this.#altTextButton = null; - this.#altTextTooltip = null; + return [isLTR ? 1 - lastX : lastX, lastY]; } - get isResizable() { - return false; - } - makeResizable() { - if (this.isResizable) { - this.#createResizers(); - this.#resizersDiv.classList.remove("hidden"); - } - } - select() { - this.makeResizable(); - this.div?.classList.add("selectedEditor"); - } - unselect() { - this.#resizersDiv?.classList.add("hidden"); - this.div?.classList.remove("selectedEditor"); - if (this.div?.contains(document.activeElement)) { - this._uiManager.currentLayer.div.focus(); - } - } - updateParams(type, value) {} - disableEditing() { - if (this.#altTextButton) { - this.#altTextButton.hidden = true; - } - } - enableEditing() { - if (this.#altTextButton) { - this.#altTextButton.hidden = false; - } - } - enterInEditMode() {} - get contentDiv() { - return this.div; - } - get isEditing() { - return this.#isEditing; - } - set isEditing(value) { - this.#isEditing = value; - if (!this.parent) { - return; - } - if (value) { - this.parent.setSelected(this); - this.parent.setActiveEditor(this); - } else { - this.parent.setActiveEditor(null); - } - } - setAspectRatio(width, height) { - this.#keepAspectRatio = true; - const aspectRatio = width / height; + show(parent, boxes, isLTR) { + const [x, y] = this.#getLastPoint(boxes, isLTR); const { style - } = this.div; - style.aspectRatio = aspectRatio; - style.height = "auto"; + } = this.#toolbar ||= this.#render(); + parent.append(this.#toolbar); + style.insetInlineEnd = `${100 * x}%`; + style.top = `calc(${100 * y}% + var(--editor-toolbar-vert-offset))`; } - static get MIN_SIZE() { - return 16; + hide() { + this.#toolbar.remove(); } -} -exports.AnnotationEditor = AnnotationEditor; -class FakeEditor extends AnnotationEditor { - constructor(params) { - super(params); - this.annotationElementId = params.annotationElementId; - this.deleted = true; - } - serialize() { - return { - id: this.annotationElementId, - deleted: true, - pageIndex: this.pageIndex - }; + #addHighlightButton() { + const button = document.createElement("button"); + button.className = "highlightButton"; + button.tabIndex = 0; + button.setAttribute("data-l10n-id", `pdfjs-highlight-floating-button1`); + const span = document.createElement("span"); + button.append(span); + span.className = "visuallyHidden"; + span.setAttribute("data-l10n-id", "pdfjs-highlight-floating-button-label"); + const signal = this.#uiManager._signal; + button.addEventListener("contextmenu", noContextMenu, { + signal + }); + button.addEventListener("click", () => { + this.#uiManager.highlightSelection("floating_button"); + }, { + signal + }); + this.#buttons.append(button); } } -/***/ }), -/* 5 */ -/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { +;// CONCATENATED MODULE: ./src/display/editor/tools.js -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.KeyboardManager = exports.CommandManager = exports.ColorManager = exports.AnnotationEditorUIManager = void 0; -exports.bindEvents = bindEvents; -exports.opacityToHex = opacityToHex; -var _util = __w_pdfjs_require__(1); -var _display_utils = __w_pdfjs_require__(6); function bindEvents(obj, element, names) { for (const name of names) { element.addEventListener(name, obj[name].bind(obj)); @@ -3837,25 +1909,27 @@ function opacityToHex(opacity) { } class IdManager { #id = 0; - getId() { - return `${_util.AnnotationEditorPrefix}${this.#id++}`; + get id() { + return `${AnnotationEditorPrefix}${this.#id++}`; } } class ImageManager { - #baseId = (0, _util.getUuid)(); + #baseId = getUuid(); #id = 0; #cache = null; static get _isSVGFittingCanvas() { const svg = `data:image/svg+xml;charset=UTF-8,`; const canvas = new OffscreenCanvas(1, 3); - const ctx = canvas.getContext("2d"); + const ctx = canvas.getContext("2d", { + willReadFrequently: true + }); const image = new Image(); image.src = svg; const promise = image.decode().then(() => { ctx.drawImage(image, 0, 0, 1, 1, 0, 0, 1, 3); return new Uint32Array(ctx.getImageData(0, 0, 1, 1).data.buffer)[0] === 0; }); - return (0, _util.shadow)(this, "_isSVGFittingCanvas", promise); + return shadow(this, "_isSVGFittingCanvas", promise); } async #get(key, rawData) { this.#cache ||= new Map(); @@ -3877,11 +1951,7 @@ class ImageManager { let image; if (typeof rawData === "string") { data.url = rawData; - const response = await fetch(rawData); - if (!response.ok) { - throw new Error(response.statusText); - } - image = await response.blob(); + image = await fetchData(rawData, "blob"); } else { image = data.file = rawData; } @@ -3978,6 +2048,7 @@ class CommandManager { add({ cmd, undo, + post, mustExec, type = NaN, overwriteIfSameType = false, @@ -3992,6 +2063,7 @@ class CommandManager { const save = { cmd, undo, + post, type }; if (this.#position === -1) { @@ -4025,7 +2097,12 @@ class CommandManager { return; } this.#locked = true; - this.#commands[this.#position].undo(); + const { + undo, + post + } = this.#commands[this.#position]; + undo(); + post?.(); this.#locked = false; this.#position -= 1; } @@ -4033,7 +2110,12 @@ class CommandManager { if (this.#position < this.#commands.length - 1) { this.#position += 1; this.#locked = true; - this.#commands[this.#position].cmd(); + const { + cmd, + post + } = this.#commands[this.#position]; + cmd(); + post?.(); this.#locked = false; } } @@ -4047,7 +2129,6 @@ class CommandManager { this.#commands = null; } } -exports.CommandManager = CommandManager; class KeyboardManager { constructor(callbacks) { this.buffer = []; @@ -4055,7 +2136,7 @@ class KeyboardManager { this.allKeys = new Set(); const { isMac - } = _util.FeatureTest.platform; + } = util_FeatureTest.platform; for (const [keys, callback, options = {}] of callbacks) { for (const key of keys) { const isMacKey = key.startsWith("mac+"); @@ -4112,23 +2193,22 @@ class KeyboardManager { if (checker && !checker(self, event)) { return; } - callback.bind(self, ...args)(); + callback.bind(self, ...args, event)(); if (!bubbles) { event.stopPropagation(); event.preventDefault(); } } } -exports.KeyboardManager = KeyboardManager; class ColorManager { static _colorsMapping = new Map([["CanvasText", [0, 0, 0]], ["Canvas", [255, 255, 255]]]); get _colors() { const colors = new Map([["CanvasText", null], ["Canvas", null]]); - (0, _display_utils.getColorValues)(colors); - return (0, _util.shadow)(this, "_colors", colors); + getColorValues(colors); + return shadow(this, "_colors", colors); } convert(color) { - const rgb = (0, _display_utils.getRGB)(color); + const rgb = getRGB(color); if (!window.matchMedia("(forced-colors: active)").matches) { return rgb; } @@ -4144,46 +2224,52 @@ class ColorManager { if (!rgb) { return name; } - return _util.Util.makeHexColor(...rgb); + return Util.makeHexColor(...rgb); } } -exports.ColorManager = ColorManager; class AnnotationEditorUIManager { + #abortController = new AbortController(); #activeEditor = null; #allEditors = new Map(); #allLayers = new Map(); #altTextManager = null; #annotationStorage = null; + #changedExistingAnnotations = null; #commandManager = new CommandManager(); + #copyPasteAC = null; #currentPageIndex = 0; #deletedAnnotationsElementIds = new Set(); #draggingEditors = null; #editorTypes = null; #editorsToRescale = new Set(); + #enableHighlightFloatingButton = false; + #enableUpdatedAddImage = false; + #enableNewAltTextWhenAddingImage = false; #filterFactory = null; + #focusMainContainerTimeoutId = null; + #focusManagerAC = null; + #highlightColors = null; + #highlightWhenShiftUp = false; + #highlightToolbar = null; #idManager = new IdManager(); #isEnabled = false; #isWaiting = false; + #keyboardManagerAC = null; #lastActiveElement = null; - #mode = _util.AnnotationEditorType.NONE; + #mainHighlightColorPicker = null; + #mlManager = null; + #mode = AnnotationEditorType.NONE; #selectedEditors = new Set(); + #selectedTextNode = null; #pageColors = null; - #boundBlur = this.blur.bind(this); - #boundFocus = this.focus.bind(this); - #boundCopy = this.copy.bind(this); - #boundCut = this.cut.bind(this); - #boundPaste = this.paste.bind(this); - #boundKeydown = this.keydown.bind(this); - #boundOnEditingAction = this.onEditingAction.bind(this); - #boundOnPageChanging = this.onPageChanging.bind(this); - #boundOnScaleChanging = this.onScaleChanging.bind(this); - #boundOnRotationChanging = this.onRotationChanging.bind(this); + #showAllStates = null; #previousStates = { isEditing: false, isEmpty: true, hasSomethingToUndo: false, hasSomethingToRedo: false, - hasSelectedEditor: false + hasSelectedEditor: false, + hasSelectedText: false }; #translation = [0, 0]; #translationTimeoutId = null; @@ -4193,15 +2279,37 @@ class AnnotationEditorUIManager { static TRANSLATE_BIG = 10; static get _keyboardManager() { const proto = AnnotationEditorUIManager.prototype; - const arrowChecker = self => { - const { - activeElement - } = document; - return activeElement && self.#container.contains(activeElement) && self.hasSomethingToControl(); + const arrowChecker = self => self.#container.contains(document.activeElement) && document.activeElement.tagName !== "BUTTON" && self.hasSomethingToControl(); + const textInputChecker = (_self, { + target: el + }) => { + if (el instanceof HTMLInputElement) { + const { + type + } = el; + return type !== "text" && type !== "number"; + } + return true; }; const small = this.TRANSLATE_SMALL; const big = this.TRANSLATE_BIG; - return (0, _util.shadow)(this, "_keyboardManager", new KeyboardManager([[["ctrl+a", "mac+meta+a"], proto.selectAll], [["ctrl+z", "mac+meta+z"], proto.undo], [["ctrl+y", "ctrl+shift+z", "mac+meta+shift+z", "ctrl+shift+Z", "mac+meta+shift+Z"], proto.redo], [["Backspace", "alt+Backspace", "ctrl+Backspace", "shift+Backspace", "mac+Backspace", "mac+alt+Backspace", "mac+ctrl+Backspace", "Delete", "ctrl+Delete", "shift+Delete", "mac+Delete"], proto.delete], [["Escape", "mac+Escape"], proto.unselectAll], [["ArrowLeft", "mac+ArrowLeft"], proto.translateSelectedEditors, { + return shadow(this, "_keyboardManager", new KeyboardManager([[["ctrl+a", "mac+meta+a"], proto.selectAll, { + checker: textInputChecker + }], [["ctrl+z", "mac+meta+z"], proto.undo, { + checker: textInputChecker + }], [["ctrl+y", "ctrl+shift+z", "mac+meta+shift+z", "ctrl+shift+Z", "mac+meta+shift+Z"], proto.redo, { + checker: textInputChecker + }], [["Backspace", "alt+Backspace", "ctrl+Backspace", "shift+Backspace", "mac+Backspace", "mac+alt+Backspace", "mac+ctrl+Backspace", "Delete", "ctrl+Delete", "shift+Delete", "mac+Delete"], proto.delete, { + checker: textInputChecker + }], [["Enter", "mac+Enter"], proto.addNewEditorFromKeyboard, { + checker: (self, { + target: el + }) => !(el instanceof HTMLButtonElement) && self.#container.contains(el) && !self.isEnterHandled + }], [[" ", "mac+ "], proto.addNewEditorFromKeyboard, { + checker: (self, { + target: el + }) => !(el instanceof HTMLButtonElement) && self.#container.contains(document.activeElement) + }], [["Escape", "mac+Escape"], proto.unselectAll], [["ArrowLeft", "mac+ArrowLeft"], proto.translateSelectedEditors, { args: [-small, 0], checker: arrowChecker }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], proto.translateSelectedEditors, { @@ -4227,30 +2335,51 @@ class AnnotationEditorUIManager { checker: arrowChecker }]])); } - constructor(container, viewer, altTextManager, eventBus, pdfDocument, pageColors) { + constructor(container, viewer, altTextManager, eventBus, pdfDocument, pageColors, highlightColors, enableHighlightFloatingButton, enableUpdatedAddImage, enableNewAltTextWhenAddingImage, mlManager) { + const signal = this._signal = this.#abortController.signal; this.#container = container; this.#viewer = viewer; this.#altTextManager = altTextManager; this._eventBus = eventBus; - this._eventBus._on("editingaction", this.#boundOnEditingAction); - this._eventBus._on("pagechanging", this.#boundOnPageChanging); - this._eventBus._on("scalechanging", this.#boundOnScaleChanging); - this._eventBus._on("rotationchanging", this.#boundOnRotationChanging); + eventBus._on("editingaction", this.onEditingAction.bind(this), { + signal + }); + eventBus._on("pagechanging", this.onPageChanging.bind(this), { + signal + }); + eventBus._on("scalechanging", this.onScaleChanging.bind(this), { + signal + }); + eventBus._on("rotationchanging", this.onRotationChanging.bind(this), { + signal + }); + eventBus._on("setpreference", this.onSetPreference.bind(this), { + signal + }); + eventBus._on("switchannotationeditorparams", evt => this.updateParams(evt.type, evt.value), { + signal + }); + this.#addSelectionListener(); + this.#addDragAndDropListeners(); + this.#addKeyboardManager(); this.#annotationStorage = pdfDocument.annotationStorage; this.#filterFactory = pdfDocument.filterFactory; this.#pageColors = pageColors; + this.#highlightColors = highlightColors || null; + this.#enableHighlightFloatingButton = enableHighlightFloatingButton; + this.#enableUpdatedAddImage = enableUpdatedAddImage; + this.#enableNewAltTextWhenAddingImage = enableNewAltTextWhenAddingImage; + this.#mlManager = mlManager || null; this.viewParameters = { - realScale: _display_utils.PixelsPerInch.PDF_TO_CSS_UNITS, + realScale: PixelsPerInch.PDF_TO_CSS_UNITS, rotation: 0 }; + this.isShiftKeyDown = false; } destroy() { - this.#removeKeyboardManager(); - this.#removeFocusManager(); - this._eventBus._off("editingaction", this.#boundOnEditingAction); - this._eventBus._off("pagechanging", this.#boundOnPageChanging); - this._eventBus._off("scalechanging", this.#boundOnScaleChanging); - this._eventBus._off("rotationchanging", this.#boundOnRotationChanging); + this.#abortController?.abort(); + this.#abortController = null; + this._signal = null; for (const layer of this.#allLayers.values()) { layer.destroy(); } @@ -4260,16 +2389,74 @@ class AnnotationEditorUIManager { this.#activeEditor = null; this.#selectedEditors.clear(); this.#commandManager.destroy(); - this.#altTextManager.destroy(); + this.#altTextManager?.destroy(); + this.#highlightToolbar?.hide(); + this.#highlightToolbar = null; + if (this.#focusMainContainerTimeoutId) { + clearTimeout(this.#focusMainContainerTimeoutId); + this.#focusMainContainerTimeoutId = null; + } + if (this.#translationTimeoutId) { + clearTimeout(this.#translationTimeoutId); + this.#translationTimeoutId = null; + } + } + combinedSignal(ac) { + return AbortSignal.any([this._signal, ac.signal]); + } + get mlManager() { + return this.#mlManager; + } + get useNewAltTextFlow() { + return this.#enableUpdatedAddImage; + } + get useNewAltTextWhenAddingImage() { + return this.#enableNewAltTextWhenAddingImage; } get hcmFilter() { - return (0, _util.shadow)(this, "hcmFilter", this.#pageColors ? this.#filterFactory.addHCMFilter(this.#pageColors.foreground, this.#pageColors.background) : "none"); + return shadow(this, "hcmFilter", this.#pageColors ? this.#filterFactory.addHCMFilter(this.#pageColors.foreground, this.#pageColors.background) : "none"); } get direction() { - return (0, _util.shadow)(this, "direction", getComputedStyle(this.#container).direction); + return shadow(this, "direction", getComputedStyle(this.#container).direction); } - editAltText(editor) { - this.#altTextManager?.editAltText(this, editor); + get highlightColors() { + return shadow(this, "highlightColors", this.#highlightColors ? new Map(this.#highlightColors.split(",").map(pair => pair.split("=").map(x => x.trim()))) : null); + } + get highlightColorNames() { + return shadow(this, "highlightColorNames", this.highlightColors ? new Map(Array.from(this.highlightColors, e => e.reverse())) : null); + } + setMainHighlightColorPicker(colorPicker) { + this.#mainHighlightColorPicker = colorPicker; + } + editAltText(editor, firstTime = false) { + this.#altTextManager?.editAltText(this, editor, firstTime); + } + switchToMode(mode, callback) { + this._eventBus.on("annotationeditormodechanged", callback, { + once: true, + signal: this._signal + }); + this._eventBus.dispatch("showannotationeditorui", { + source: this, + mode + }); + } + setPreference(name, value) { + this._eventBus.dispatch("setpreference", { + source: this, + name, + value + }); + } + onSetPreference({ + name, + value + }) { + switch (name) { + case "enableNewAltTextWhenAddingImage": + this.#enableNewAltTextWhenAddingImage = value; + break; + } } onPageChanging({ pageNumber @@ -4306,7 +2493,7 @@ class AnnotationEditorUIManager { scale }) { this.commitOrRemove(); - this.viewParameters.realScale = scale * _display_utils.PixelsPerInch.PDF_TO_CSS_UNITS; + this.viewParameters.realScale = scale * PixelsPerInch.PDF_TO_CSS_UNITS; for (const editor of this.#editorsToRescale) { editor.onScaleChanging(); } @@ -4317,20 +2504,188 @@ class AnnotationEditorUIManager { this.commitOrRemove(); this.viewParameters.rotation = pagesRotation; } + #getAnchorElementForSelection({ + anchorNode + }) { + return anchorNode.nodeType === Node.TEXT_NODE ? anchorNode.parentElement : anchorNode; + } + #getLayerForTextLayer(textLayer) { + const { + currentLayer + } = this; + if (currentLayer.hasTextLayer(textLayer)) { + return currentLayer; + } + for (const layer of this.#allLayers.values()) { + if (layer.hasTextLayer(textLayer)) { + return layer; + } + } + return null; + } + highlightSelection(methodOfCreation = "") { + const selection = document.getSelection(); + if (!selection || selection.isCollapsed) { + return; + } + const { + anchorNode, + anchorOffset, + focusNode, + focusOffset + } = selection; + const text = selection.toString(); + const anchorElement = this.#getAnchorElementForSelection(selection); + const textLayer = anchorElement.closest(".textLayer"); + const boxes = this.getSelectionBoxes(textLayer); + if (!boxes) { + return; + } + selection.empty(); + const layer = this.#getLayerForTextLayer(textLayer); + const isNoneMode = this.#mode === AnnotationEditorType.NONE; + const callback = () => { + layer?.createAndAddNewEditor({ + x: 0, + y: 0 + }, false, { + methodOfCreation, + boxes, + anchorNode, + anchorOffset, + focusNode, + focusOffset, + text + }); + if (isNoneMode) { + this.showAllEditors("highlight", true, true); + } + }; + if (isNoneMode) { + this.switchToMode(AnnotationEditorType.HIGHLIGHT, callback); + return; + } + callback(); + } + #displayHighlightToolbar() { + const selection = document.getSelection(); + if (!selection || selection.isCollapsed) { + return; + } + const anchorElement = this.#getAnchorElementForSelection(selection); + const textLayer = anchorElement.closest(".textLayer"); + const boxes = this.getSelectionBoxes(textLayer); + if (!boxes) { + return; + } + this.#highlightToolbar ||= new HighlightToolbar(this); + this.#highlightToolbar.show(textLayer, boxes, this.direction === "ltr"); + } addToAnnotationStorage(editor) { if (!editor.isEmpty() && this.#annotationStorage && !this.#annotationStorage.has(editor.id)) { this.#annotationStorage.setValue(editor.id, editor); } } + #selectionChange() { + const selection = document.getSelection(); + if (!selection || selection.isCollapsed) { + if (this.#selectedTextNode) { + this.#highlightToolbar?.hide(); + this.#selectedTextNode = null; + this.#dispatchUpdateStates({ + hasSelectedText: false + }); + } + return; + } + const { + anchorNode + } = selection; + if (anchorNode === this.#selectedTextNode) { + return; + } + const anchorElement = this.#getAnchorElementForSelection(selection); + const textLayer = anchorElement.closest(".textLayer"); + if (!textLayer) { + if (this.#selectedTextNode) { + this.#highlightToolbar?.hide(); + this.#selectedTextNode = null; + this.#dispatchUpdateStates({ + hasSelectedText: false + }); + } + return; + } + this.#highlightToolbar?.hide(); + this.#selectedTextNode = anchorNode; + this.#dispatchUpdateStates({ + hasSelectedText: true + }); + if (this.#mode !== AnnotationEditorType.HIGHLIGHT && this.#mode !== AnnotationEditorType.NONE) { + return; + } + if (this.#mode === AnnotationEditorType.HIGHLIGHT) { + this.showAllEditors("highlight", true, true); + } + this.#highlightWhenShiftUp = this.isShiftKeyDown; + if (!this.isShiftKeyDown) { + const activeLayer = this.#mode === AnnotationEditorType.HIGHLIGHT ? this.#getLayerForTextLayer(textLayer) : null; + activeLayer?.toggleDrawing(); + const ac = new AbortController(); + const signal = this.combinedSignal(ac); + const pointerup = e => { + if (e.type === "pointerup" && e.button !== 0) { + return; + } + ac.abort(); + activeLayer?.toggleDrawing(true); + if (e.type === "pointerup") { + this.#onSelectEnd("main_toolbar"); + } + }; + window.addEventListener("pointerup", pointerup, { + signal + }); + window.addEventListener("blur", pointerup, { + signal + }); + } + } + #onSelectEnd(methodOfCreation = "") { + if (this.#mode === AnnotationEditorType.HIGHLIGHT) { + this.highlightSelection(methodOfCreation); + } else if (this.#enableHighlightFloatingButton) { + this.#displayHighlightToolbar(); + } + } + #addSelectionListener() { + document.addEventListener("selectionchange", this.#selectionChange.bind(this), { + signal: this._signal + }); + } #addFocusManager() { - window.addEventListener("focus", this.#boundFocus); - window.addEventListener("blur", this.#boundBlur); + if (this.#focusManagerAC) { + return; + } + this.#focusManagerAC = new AbortController(); + const signal = this.combinedSignal(this.#focusManagerAC); + window.addEventListener("focus", this.focus.bind(this), { + signal + }); + window.addEventListener("blur", this.blur.bind(this), { + signal + }); } #removeFocusManager() { - window.removeEventListener("focus", this.#boundFocus); - window.removeEventListener("blur", this.#boundBlur); + this.#focusManagerAC?.abort(); + this.#focusManagerAC = null; } blur() { + this.isShiftKeyDown = false; + if (this.#highlightWhenShiftUp) { + this.#highlightWhenShiftUp = false; + this.#onSelectEnd("main_toolbar"); + } if (!this.hasSelection) { return; } @@ -4354,29 +2709,56 @@ class AnnotationEditorUIManager { lastActiveElement.addEventListener("focusin", () => { lastEditor._focusEventsAllowed = true; }, { - once: true + once: true, + signal: this._signal }); lastActiveElement.focus(); } #addKeyboardManager() { - window.addEventListener("keydown", this.#boundKeydown, { - capture: true + if (this.#keyboardManagerAC) { + return; + } + this.#keyboardManagerAC = new AbortController(); + const signal = this.combinedSignal(this.#keyboardManagerAC); + window.addEventListener("keydown", this.keydown.bind(this), { + signal + }); + window.addEventListener("keyup", this.keyup.bind(this), { + signal }); } #removeKeyboardManager() { - window.removeEventListener("keydown", this.#boundKeydown, { - capture: true - }); + this.#keyboardManagerAC?.abort(); + this.#keyboardManagerAC = null; } #addCopyPasteListeners() { - document.addEventListener("copy", this.#boundCopy); - document.addEventListener("cut", this.#boundCut); - document.addEventListener("paste", this.#boundPaste); + if (this.#copyPasteAC) { + return; + } + this.#copyPasteAC = new AbortController(); + const signal = this.combinedSignal(this.#copyPasteAC); + document.addEventListener("copy", this.copy.bind(this), { + signal + }); + document.addEventListener("cut", this.cut.bind(this), { + signal + }); + document.addEventListener("paste", this.paste.bind(this), { + signal + }); } #removeCopyPasteListeners() { - document.removeEventListener("copy", this.#boundCopy); - document.removeEventListener("cut", this.#boundCut); - document.removeEventListener("paste", this.#boundPaste); + this.#copyPasteAC?.abort(); + this.#copyPasteAC = null; + } + #addDragAndDropListeners() { + const signal = this._signal; + document.addEventListener("dragover", this.dragOver.bind(this), { + signal + }); + document.addEventListener("drop", this.drop.bind(this), { + signal + }); } addEditListeners() { this.#addKeyboardManager(); @@ -4386,6 +2768,30 @@ class AnnotationEditorUIManager { this.#removeKeyboardManager(); this.#removeCopyPasteListeners(); } + dragOver(event) { + for (const { + type + } of event.dataTransfer.items) { + for (const editorType of this.#editorTypes) { + if (editorType.isHandlingMimeForPasting(type)) { + event.dataTransfer.dropEffect = "copy"; + event.preventDefault(); + return; + } + } + } + } + drop(event) { + for (const item of event.dataTransfer.items) { + for (const editorType of this.#editorTypes) { + if (editorType.isHandlingMimeForPasting(item.type)) { + editorType.paste(item, this.currentLayer); + event.preventDefault(); + return; + } + } + } + } copy(event) { event.preventDefault(); this.#activeEditor?.commitOrRemove(); @@ -4428,7 +2834,7 @@ class AnnotationEditorUIManager { try { data = JSON.parse(data); } catch (ex) { - (0, _util.warn)(`paste: "${ex.message}".`); + warn(`paste: "${ex.message}".`); return; } if (!Array.isArray(data)) { @@ -4462,17 +2868,39 @@ class AnnotationEditorUIManager { mustExec: true }); } catch (ex) { - (0, _util.warn)(`paste: "${ex.message}".`); + warn(`paste: "${ex.message}".`); } } keydown(event) { - if (!this.getActive()?.shouldGetKeyboardEvents()) { + if (!this.isShiftKeyDown && event.key === "Shift") { + this.isShiftKeyDown = true; + } + if (this.#mode !== AnnotationEditorType.NONE && !this.isEditorHandlingKeyboard) { AnnotationEditorUIManager._keyboardManager.exec(this, event); } } - onEditingAction(details) { - if (["undo", "redo", "delete", "selectAll"].includes(details.name)) { - this[details.name](); + keyup(event) { + if (this.isShiftKeyDown && event.key === "Shift") { + this.isShiftKeyDown = false; + if (this.#highlightWhenShiftUp) { + this.#highlightWhenShiftUp = false; + this.#onSelectEnd("main_toolbar"); + } + } + } + onEditingAction({ + name + }) { + switch (name) { + case "undo": + case "redo": + case "delete": + case "selectAll": + this[name](); + break; + case "highlightSelection": + this.highlightSelection("context_menu"); + break; } } #dispatchUpdateStates(details) { @@ -4482,6 +2910,9 @@ class AnnotationEditorUIManager { source: this, details: Object.assign(this.#previousStates, details) }); + if (this.#mode === AnnotationEditorType.HIGHLIGHT && details.hasSelectedEditor === false) { + this.#dispatchUpdateUI([[AnnotationEditorParamsType.HIGHLIGHT_FREE, true]]); + } } } #dispatchUpdateUI(details) { @@ -4493,10 +2924,9 @@ class AnnotationEditorUIManager { setEditingState(isEditing) { if (isEditing) { this.#addFocusManager(); - this.#addKeyboardManager(); this.#addCopyPasteListeners(); this.#dispatchUpdateStates({ - isEditing: this.#mode !== _util.AnnotationEditorType.NONE, + isEditing: this.#mode !== AnnotationEditorType.NONE, isEmpty: this.#isEmpty(), hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(), hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(), @@ -4504,7 +2934,6 @@ class AnnotationEditorUIManager { }); } else { this.#removeFocusManager(); - this.#removeKeyboardManager(); this.#removeCopyPasteListeners(); this.#dispatchUpdateStates({ isEditing: false @@ -4522,7 +2951,7 @@ class AnnotationEditorUIManager { } } getId() { - return this.#idManager.getId(); + return this.#idManager.id; } get currentLayer() { return this.#allLayers.get(this.#currentPageIndex); @@ -4544,12 +2973,12 @@ class AnnotationEditorUIManager { removeLayer(layer) { this.#allLayers.delete(layer.pageIndex); } - updateMode(mode, editId = null) { + updateMode(mode, editId = null, isFromKeyboard = false) { if (this.#mode === mode) { return; } this.#mode = mode; - if (mode === _util.AnnotationEditorType.NONE) { + if (mode === AnnotationEditorType.NONE) { this.setEditingState(false); this.#disableAll(); return; @@ -4560,6 +2989,10 @@ class AnnotationEditorUIManager { for (const layer of this.#allLayers.values()) { layer.updateMode(mode); } + if (!editId && isFromKeyboard) { + this.addNewEditorFromKeyboard(); + return; + } if (!editId) { return; } @@ -4571,6 +3004,11 @@ class AnnotationEditorUIManager { } } } + addNewEditorFromKeyboard() { + if (this.currentLayer.canCreateNewEmptyEditor()) { + this.currentLayer.addNewEditor(); + } + } updateToolbar(mode) { if (mode === this.#mode) { return; @@ -4584,9 +3022,27 @@ class AnnotationEditorUIManager { if (!this.#editorTypes) { return; } - if (type === _util.AnnotationEditorParamsType.CREATE) { - this.currentLayer.addNewEditor(type); - return; + switch (type) { + case AnnotationEditorParamsType.CREATE: + this.currentLayer.addNewEditor(); + return; + case AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR: + this.#mainHighlightColorPicker?.updateColor(value); + break; + case AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL: + this._eventBus.dispatch("reporttelemetry", { + source: this, + details: { + type: "editing", + data: { + type: "highlight", + action: "toggle_visibility" + } + } + }); + (this.#showAllStates ||= new Map()).set(type, value); + this.showAllEditors("highlight", value); + break; } for (const editor of this.#selectedEditors) { editor.updateParams(type, value); @@ -4595,6 +3051,17 @@ class AnnotationEditorUIManager { editorType.updateDefaultParams(type, value); } } + showAllEditors(type, visible, updateButton = false) { + for (const editor of this.#allEditors.values()) { + if (editor.editorType === type) { + editor.show(visible); + } + } + const state = this.#showAllStates?.get(AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL) ?? true; + if (state !== visible) { + this.#dispatchUpdateUI([[AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL, visible]]); + } + } enableWaiting(mustWait = false) { if (this.#isWaiting === mustWait) { return; @@ -4615,6 +3082,9 @@ class AnnotationEditorUIManager { for (const layer of this.#allLayers.values()) { layer.enable(); } + for (const editor of this.#allEditors.values()) { + editor.enable(); + } } } #disableAll() { @@ -4624,6 +3094,9 @@ class AnnotationEditorUIManager { for (const layer of this.#allLayers.values()) { layer.disable(); } + for (const editor of this.#allEditors.values()) { + editor.disable(); + } } } getEditors(pageIndex) { @@ -4642,6 +3115,15 @@ class AnnotationEditorUIManager { this.#allEditors.set(editor.id, editor); } removeEditor(editor) { + if (editor.div.contains(document.activeElement)) { + if (this.#focusMainContainerTimeoutId) { + clearTimeout(this.#focusMainContainerTimeoutId); + } + this.#focusMainContainerTimeoutId = setTimeout(() => { + this.focusMainContainer(); + this.#focusMainContainerTimeoutId = null; + }, 0); + } this.#allEditors.delete(editor.id); this.unselect(editor); if (!editor.annotationElementId || !this.#deletedAnnotationsElementIds.has(editor.annotationElementId)) { @@ -4650,6 +3132,7 @@ class AnnotationEditorUIManager { } addDeletedAnnotationElement(editor) { this.#deletedAnnotationsElementIds.add(editor.annotationElementId); + this.addChangedExistingAnnotation(editor); editor.deleted = true; } isDeletedAnnotationElement(annotationElementId) { @@ -4657,6 +3140,7 @@ class AnnotationEditorUIManager { } removeDeletedAnnotationElement(editor) { this.#deletedAnnotationsElementIds.delete(editor.annotationElementId); + this.removeChangedExistingAnnotation(editor); editor.deleted = false; } #addEditorToLayer(editor) { @@ -4665,6 +3149,7 @@ class AnnotationEditorUIManager { layer.addOrRebuild(editor); } else { this.addEditor(editor); + this.addToAnnotationStorage(editor); } } setActiveEditor(editor) { @@ -4676,6 +3161,16 @@ class AnnotationEditorUIManager { this.#dispatchUpdateUI(editor.propertiesToUpdate); } } + get #lastSelectedEditor() { + let ed = null; + for (ed of this.#selectedEditors) {} + return ed; + } + updateUI(editor) { + if (this.#lastSelectedEditor === editor) { + this.#dispatchUpdateUI(editor.propertiesToUpdate); + } + } toggleSelected(editor) { if (this.#selectedEditors.has(editor)) { this.#selectedEditors.delete(editor); @@ -4709,6 +3204,9 @@ class AnnotationEditorUIManager { isSelected(editor) { return this.#selectedEditors.has(editor); } + get firstSelectedEditor() { + return this.#selectedEditors.values().next().value; + } unselect(editor) { editor.unselect(); this.#selectedEditors.delete(editor); @@ -4719,6 +3217,9 @@ class AnnotationEditorUIManager { get hasSelection() { return this.#selectedEditors.size !== 0; } + get isEnterHandled() { + return this.#selectedEditors.size === 1 && this.firstSelectedEditor.isEnterHandled; + } undo() { this.#commandManager.undo(); this.#dispatchUpdateStates({ @@ -4783,6 +3284,9 @@ class AnnotationEditorUIManager { return this.#activeEditor || this.hasSelection; } #selectEditors(editors) { + for (const editor of this.#selectedEditors) { + editor.unselect(); + } this.#selectedEditors.clear(); for (const editor of editors) { if (editor.isEmpty()) { @@ -4792,7 +3296,7 @@ class AnnotationEditorUIManager { editor.select(); } this.#dispatchUpdateStates({ - hasSelectedEditor: true + hasSelectedEditor: this.hasSelection }); } selectAll() { @@ -4804,7 +3308,9 @@ class AnnotationEditorUIManager { unselectAll() { if (this.#activeEditor) { this.#activeEditor.commitOrRemove(); - return; + if (this.#mode !== AnnotationEditorType.NONE) { + return; + } } if (!this.hasSelection) { return; @@ -4953,6 +3459,9 @@ class AnnotationEditorUIManager { editor.parent.addOrRebuild(editor); } } + get isEditorHandlingKeyboard() { + return this.getActive()?.shouldGetKeyboardEvents() || this.#selectedEditors.size === 1 && this.firstSelectedEditor.shouldGetKeyboardEvents(); + } isActive(editor) { return this.#activeEditor === editor; } @@ -4963,864 +3472,1555 @@ class AnnotationEditorUIManager { return this.#mode; } get imageManager() { - return (0, _util.shadow)(this, "imageManager", new ImageManager()); + return shadow(this, "imageManager", new ImageManager()); } -} -exports.AnnotationEditorUIManager = AnnotationEditorUIManager; - -/***/ }), -/* 6 */ -/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.StatTimer = exports.RenderingCancelledException = exports.PixelsPerInch = exports.PageViewport = exports.PDFDateString = exports.DOMStandardFontDataFactory = exports.DOMSVGFactory = exports.DOMFilterFactory = exports.DOMCanvasFactory = exports.DOMCMapReaderFactory = void 0; -exports.deprecated = deprecated; -exports.getColorValues = getColorValues; -exports.getCurrentTransform = getCurrentTransform; -exports.getCurrentTransformInverse = getCurrentTransformInverse; -exports.getFilenameFromUrl = getFilenameFromUrl; -exports.getPdfFilenameFromUrl = getPdfFilenameFromUrl; -exports.getRGB = getRGB; -exports.getXfaPageViewport = getXfaPageViewport; -exports.isDataScheme = isDataScheme; -exports.isPdfFile = isPdfFile; -exports.isValidFetchUrl = isValidFetchUrl; -exports.loadScript = loadScript; -exports.noContextMenu = noContextMenu; -exports.setLayerDimensions = setLayerDimensions; -var _base_factory = __w_pdfjs_require__(7); -var _util = __w_pdfjs_require__(1); -const SVG_NS = "http://www.w3.org/2000/svg"; -class PixelsPerInch { - static CSS = 96.0; - static PDF = 72.0; - static PDF_TO_CSS_UNITS = this.CSS / this.PDF; -} -exports.PixelsPerInch = PixelsPerInch; -class DOMFilterFactory extends _base_factory.BaseFilterFactory { - #_cache; - #_defs; - #docId; - #document; - #hcmFilter; - #hcmKey; - #hcmUrl; - #hcmHighlightFilter; - #hcmHighlightKey; - #hcmHighlightUrl; - #id = 0; - constructor({ - docId, - ownerDocument = globalThis.document - } = {}) { - super(); - this.#docId = docId; - this.#document = ownerDocument; - } - get #cache() { - return this.#_cache ||= new Map(); - } - get #defs() { - if (!this.#_defs) { - const div = this.#document.createElement("div"); - const { - style - } = div; - style.visibility = "hidden"; - style.contain = "strict"; - style.width = style.height = 0; - style.position = "absolute"; - style.top = style.left = 0; - style.zIndex = -1; - const svg = this.#document.createElementNS(SVG_NS, "svg"); - svg.setAttribute("width", 0); - svg.setAttribute("height", 0); - this.#_defs = this.#document.createElementNS(SVG_NS, "defs"); - div.append(svg); - svg.append(this.#_defs); - this.#document.body.append(div); + getSelectionBoxes(textLayer) { + if (!textLayer) { + return null; } - return this.#_defs; - } - addFilter(maps) { - if (!maps) { - return "none"; - } - let value = this.#cache.get(maps); - if (value) { - return value; - } - let tableR, tableG, tableB, key; - if (maps.length === 1) { - const mapR = maps[0]; - const buffer = new Array(256); - for (let i = 0; i < 256; i++) { - buffer[i] = mapR[i] / 255; + const selection = document.getSelection(); + for (let i = 0, ii = selection.rangeCount; i < ii; i++) { + if (!textLayer.contains(selection.getRangeAt(i).commonAncestorContainer)) { + return null; } - key = tableR = tableG = tableB = buffer.join(","); - } else { - const [mapR, mapG, mapB] = maps; - const bufferR = new Array(256); - const bufferG = new Array(256); - const bufferB = new Array(256); - for (let i = 0; i < 256; i++) { - bufferR[i] = mapR[i] / 255; - bufferG[i] = mapG[i] / 255; - bufferB[i] = mapB[i] / 255; - } - tableR = bufferR.join(","); - tableG = bufferG.join(","); - tableB = bufferB.join(","); - key = `${tableR}${tableG}${tableB}`; } - value = this.#cache.get(key); - if (value) { - this.#cache.set(maps, value); - return value; - } - const id = `g_${this.#docId}_transfer_map_${this.#id++}`; - const url = `url(#${id})`; - this.#cache.set(maps, url); - this.#cache.set(key, url); - const filter = this.#createFilter(id); - this.#addTransferMapConversion(tableR, tableG, tableB, filter); - return url; - } - addHCMFilter(fgColor, bgColor) { - const key = `${fgColor}-${bgColor}`; - if (this.#hcmKey === key) { - return this.#hcmUrl; - } - this.#hcmKey = key; - this.#hcmUrl = "none"; - this.#hcmFilter?.remove(); - if (!fgColor || !bgColor) { - return this.#hcmUrl; - } - const fgRGB = this.#getRGB(fgColor); - fgColor = _util.Util.makeHexColor(...fgRGB); - const bgRGB = this.#getRGB(bgColor); - bgColor = _util.Util.makeHexColor(...bgRGB); - this.#defs.style.color = ""; - if (fgColor === "#000000" && bgColor === "#ffffff" || fgColor === bgColor) { - return this.#hcmUrl; - } - const map = new Array(256); - for (let i = 0; i <= 255; i++) { - const x = i / 255; - map[i] = x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4; - } - const table = map.join(","); - const id = `g_${this.#docId}_hcm_filter`; - const filter = this.#hcmHighlightFilter = this.#createFilter(id); - this.#addTransferMapConversion(table, table, table, filter); - this.#addGrayConversion(filter); - const getSteps = (c, n) => { - const start = fgRGB[c] / 255; - const end = bgRGB[c] / 255; - const arr = new Array(n + 1); - for (let i = 0; i <= n; i++) { - arr[i] = start + i / n * (end - start); - } - return arr.join(","); - }; - this.#addTransferMapConversion(getSteps(0, 5), getSteps(1, 5), getSteps(2, 5), filter); - this.#hcmUrl = `url(#${id})`; - return this.#hcmUrl; - } - addHighlightHCMFilter(fgColor, bgColor, newFgColor, newBgColor) { - const key = `${fgColor}-${bgColor}-${newFgColor}-${newBgColor}`; - if (this.#hcmHighlightKey === key) { - return this.#hcmHighlightUrl; - } - this.#hcmHighlightKey = key; - this.#hcmHighlightUrl = "none"; - this.#hcmHighlightFilter?.remove(); - if (!fgColor || !bgColor) { - return this.#hcmHighlightUrl; - } - const [fgRGB, bgRGB] = [fgColor, bgColor].map(this.#getRGB.bind(this)); - let fgGray = Math.round(0.2126 * fgRGB[0] + 0.7152 * fgRGB[1] + 0.0722 * fgRGB[2]); - let bgGray = Math.round(0.2126 * bgRGB[0] + 0.7152 * bgRGB[1] + 0.0722 * bgRGB[2]); - let [newFgRGB, newBgRGB] = [newFgColor, newBgColor].map(this.#getRGB.bind(this)); - if (bgGray < fgGray) { - [fgGray, bgGray, newFgRGB, newBgRGB] = [bgGray, fgGray, newBgRGB, newFgRGB]; - } - this.#defs.style.color = ""; - const getSteps = (fg, bg, n) => { - const arr = new Array(256); - const step = (bgGray - fgGray) / n; - const newStart = fg / 255; - const newStep = (bg - fg) / (255 * n); - let prev = 0; - for (let i = 0; i <= n; i++) { - const k = Math.round(fgGray + i * step); - const value = newStart + i * newStep; - for (let j = prev; j <= k; j++) { - arr[j] = value; - } - prev = k + 1; - } - for (let i = prev; i < 256; i++) { - arr[i] = arr[prev - 1]; - } - return arr.join(","); - }; - const id = `g_${this.#docId}_hcm_highlight_filter`; - const filter = this.#hcmHighlightFilter = this.#createFilter(id); - this.#addGrayConversion(filter); - this.#addTransferMapConversion(getSteps(newFgRGB[0], newBgRGB[0], 5), getSteps(newFgRGB[1], newBgRGB[1], 5), getSteps(newFgRGB[2], newBgRGB[2], 5), filter); - this.#hcmHighlightUrl = `url(#${id})`; - return this.#hcmHighlightUrl; - } - destroy(keepHCM = false) { - if (keepHCM && (this.#hcmUrl || this.#hcmHighlightUrl)) { - return; - } - if (this.#_defs) { - this.#_defs.parentNode.parentNode.remove(); - this.#_defs = null; - } - if (this.#_cache) { - this.#_cache.clear(); - this.#_cache = null; - } - this.#id = 0; - } - #addGrayConversion(filter) { - const feColorMatrix = this.#document.createElementNS(SVG_NS, "feColorMatrix"); - feColorMatrix.setAttribute("type", "matrix"); - 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"); - filter.append(feColorMatrix); - } - #createFilter(id) { - const filter = this.#document.createElementNS(SVG_NS, "filter"); - filter.setAttribute("color-interpolation-filters", "sRGB"); - filter.setAttribute("id", id); - this.#defs.append(filter); - return filter; - } - #appendFeFunc(feComponentTransfer, func, table) { - const feFunc = this.#document.createElementNS(SVG_NS, func); - feFunc.setAttribute("type", "discrete"); - feFunc.setAttribute("tableValues", table); - feComponentTransfer.append(feFunc); - } - #addTransferMapConversion(rTable, gTable, bTable, filter) { - const feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer"); - filter.append(feComponentTransfer); - this.#appendFeFunc(feComponentTransfer, "feFuncR", rTable); - this.#appendFeFunc(feComponentTransfer, "feFuncG", gTable); - this.#appendFeFunc(feComponentTransfer, "feFuncB", bTable); - } - #getRGB(color) { - this.#defs.style.color = color; - return getRGB(getComputedStyle(this.#defs).getPropertyValue("color")); - } -} -exports.DOMFilterFactory = DOMFilterFactory; -class DOMCanvasFactory extends _base_factory.BaseCanvasFactory { - constructor({ - ownerDocument = globalThis.document - } = {}) { - super(); - this._document = ownerDocument; - } - _createCanvas(width, height) { - const canvas = this._document.createElement("canvas"); - canvas.width = width; - canvas.height = height; - return canvas; - } -} -exports.DOMCanvasFactory = DOMCanvasFactory; -async function fetchData(url, asTypedArray = false) { - if (isValidFetchUrl(url, document.baseURI)) { - const response = await fetch(url); - if (!response.ok) { - throw new Error(response.statusText); - } - return asTypedArray ? new Uint8Array(await response.arrayBuffer()) : (0, _util.stringToBytes)(await response.text()); - } - return new Promise((resolve, reject) => { - const request = new XMLHttpRequest(); - request.open("GET", url, true); - if (asTypedArray) { - request.responseType = "arraybuffer"; - } - request.onreadystatechange = () => { - if (request.readyState !== XMLHttpRequest.DONE) { - return; - } - if (request.status === 200 || request.status === 0) { - let data; - if (asTypedArray && request.response) { - data = new Uint8Array(request.response); - } else if (!asTypedArray && request.responseText) { - data = (0, _util.stringToBytes)(request.responseText); - } - if (data) { - resolve(data); - return; - } - } - reject(new Error(request.statusText)); - }; - request.send(null); - }); -} -class DOMCMapReaderFactory extends _base_factory.BaseCMapReaderFactory { - _fetchData(url, compressionType) { - return fetchData(url, this.isCompressed).then(data => { - return { - cMapData: data, - compressionType - }; - }); - } -} -exports.DOMCMapReaderFactory = DOMCMapReaderFactory; -class DOMStandardFontDataFactory extends _base_factory.BaseStandardFontDataFactory { - _fetchData(url) { - return fetchData(url, true); - } -} -exports.DOMStandardFontDataFactory = DOMStandardFontDataFactory; -class DOMSVGFactory extends _base_factory.BaseSVGFactory { - _createSVG(type) { - return document.createElementNS(SVG_NS, type); - } -} -exports.DOMSVGFactory = DOMSVGFactory; -class PageViewport { - constructor({ - viewBox, - scale, - rotation, - offsetX = 0, - offsetY = 0, - dontFlip = false - }) { - this.viewBox = viewBox; - this.scale = scale; - this.rotation = rotation; - this.offsetX = offsetX; - this.offsetY = offsetY; - const centerX = (viewBox[2] + viewBox[0]) / 2; - const centerY = (viewBox[3] + viewBox[1]) / 2; - let rotateA, rotateB, rotateC, rotateD; - rotation %= 360; - if (rotation < 0) { - rotation += 360; - } - switch (rotation) { - case 180: - rotateA = -1; - rotateB = 0; - rotateC = 0; - rotateD = 1; + const { + x: layerX, + y: layerY, + width: parentWidth, + height: parentHeight + } = textLayer.getBoundingClientRect(); + let rotator; + switch (textLayer.getAttribute("data-main-rotation")) { + case "90": + rotator = (x, y, w, h) => ({ + x: (y - layerY) / parentHeight, + y: 1 - (x + w - layerX) / parentWidth, + width: h / parentHeight, + height: w / parentWidth + }); break; - case 90: - rotateA = 0; - rotateB = 1; - rotateC = 1; - rotateD = 0; + case "180": + rotator = (x, y, w, h) => ({ + x: 1 - (x + w - layerX) / parentWidth, + y: 1 - (y + h - layerY) / parentHeight, + width: w / parentWidth, + height: h / parentHeight + }); break; - case 270: - rotateA = 0; - rotateB = -1; - rotateC = -1; - rotateD = 0; - break; - case 0: - rotateA = 1; - rotateB = 0; - rotateC = 0; - rotateD = -1; + case "270": + rotator = (x, y, w, h) => ({ + x: 1 - (y + h - layerY) / parentHeight, + y: (x - layerX) / parentWidth, + width: h / parentHeight, + height: w / parentWidth + }); break; default: - throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees."); + rotator = (x, y, w, h) => ({ + x: (x - layerX) / parentWidth, + y: (y - layerY) / parentHeight, + width: w / parentWidth, + height: h / parentHeight + }); + break; } - if (dontFlip) { - rotateC = -rotateC; - rotateD = -rotateD; + const boxes = []; + for (let i = 0, ii = selection.rangeCount; i < ii; i++) { + const range = selection.getRangeAt(i); + if (range.collapsed) { + continue; + } + for (const { + x, + y, + width, + height + } of range.getClientRects()) { + if (width === 0 || height === 0) { + continue; + } + boxes.push(rotator(x, y, width, height)); + } } - let offsetCanvasX, offsetCanvasY; - let width, height; - if (rotateA === 0) { - offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX; - offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY; - width = (viewBox[3] - viewBox[1]) * scale; - height = (viewBox[2] - viewBox[0]) * scale; + return boxes.length === 0 ? null : boxes; + } + addChangedExistingAnnotation({ + annotationElementId, + id + }) { + (this.#changedExistingAnnotations ||= new Map()).set(annotationElementId, id); + } + removeChangedExistingAnnotation({ + annotationElementId + }) { + this.#changedExistingAnnotations?.delete(annotationElementId); + } + renderAnnotationElement(annotation) { + const editorId = this.#changedExistingAnnotations?.get(annotation.data.id); + if (!editorId) { + return; + } + const editor = this.#annotationStorage.getRawValue(editorId); + if (!editor) { + return; + } + if (this.#mode === AnnotationEditorType.NONE && !editor.hasBeenModified) { + return; + } + editor.renderAnnotationElement(annotation); + } +} + +;// CONCATENATED MODULE: ./src/display/editor/alt_text.js + +class AltText { + #altText = null; + #altTextDecorative = false; + #altTextButton = null; + #altTextTooltip = null; + #altTextTooltipTimeout = null; + #altTextWasFromKeyBoard = false; + #badge = null; + #editor = null; + #guessedText = null; + #textWithDisclaimer = null; + #useNewAltTextFlow = false; + static _l10nPromise = null; + constructor(editor) { + this.#editor = editor; + this.#useNewAltTextFlow = editor._uiManager.useNewAltTextFlow; + } + static initialize(l10nPromise) { + AltText._l10nPromise ||= l10nPromise; + } + async render() { + const altText = this.#altTextButton = document.createElement("button"); + altText.className = "altText"; + let msg; + if (this.#useNewAltTextFlow) { + altText.classList.add("new"); + msg = await AltText._l10nPromise.get("pdfjs-editor-new-alt-text-missing-button-label"); } else { - offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX; - offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY; - width = (viewBox[2] - viewBox[0]) * scale; - height = (viewBox[3] - viewBox[1]) * scale; + msg = await AltText._l10nPromise.get("pdfjs-editor-alt-text-button-label"); } - this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY]; - this.width = width; - this.height = height; + altText.textContent = msg; + altText.setAttribute("aria-label", msg); + altText.tabIndex = "0"; + const signal = this.#editor._uiManager._signal; + altText.addEventListener("contextmenu", noContextMenu, { + signal + }); + altText.addEventListener("pointerdown", event => event.stopPropagation(), { + signal + }); + const onClick = event => { + event.preventDefault(); + this.#editor._uiManager.editAltText(this.#editor); + if (this.#useNewAltTextFlow) { + this.#editor._reportTelemetry({ + action: "pdfjs.image.alt_text.image_status_label_clicked", + data: { + label: this.#label + } + }); + } + }; + altText.addEventListener("click", onClick, { + capture: true, + signal + }); + altText.addEventListener("keydown", event => { + if (event.target === altText && event.key === "Enter") { + this.#altTextWasFromKeyBoard = true; + onClick(event); + } + }, { + signal + }); + await this.#setState(); + return altText; } - get rawDims() { - const { - viewBox - } = this; - return (0, _util.shadow)(this, "rawDims", { - pageWidth: viewBox[2] - viewBox[0], - pageHeight: viewBox[3] - viewBox[1], - pageX: viewBox[0], - pageY: viewBox[1] + get #label() { + return this.#altText && "added" || this.#altText === null && this.guessedText && "review" || "missing"; + } + finish() { + if (!this.#altTextButton) { + return; + } + this.#altTextButton.focus({ + focusVisible: this.#altTextWasFromKeyBoard + }); + this.#altTextWasFromKeyBoard = false; + } + isEmpty() { + if (this.#useNewAltTextFlow) { + return this.#altText === null; + } + return !this.#altText && !this.#altTextDecorative; + } + hasData() { + if (this.#useNewAltTextFlow) { + return this.#altText !== null || !!this.#guessedText; + } + return this.isEmpty(); + } + get guessedText() { + return this.#guessedText; + } + async setGuessedText(guessedText) { + if (this.#altText !== null) { + return; + } + this.#guessedText = guessedText; + this.#textWithDisclaimer = await AltText._l10nPromise.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer")({ + generatedAltText: guessedText + }); + this.#setState(); + } + toggleAltTextBadge(visibility = false) { + if (!this.#useNewAltTextFlow || this.#altText) { + this.#badge?.remove(); + this.#badge = null; + return; + } + if (!this.#badge) { + const badge = this.#badge = document.createElement("div"); + badge.className = "noAltTextBadge"; + this.#editor.div.append(badge); + } + this.#badge.classList.toggle("hidden", !visibility); + } + serialize(isForCopying) { + let altText = this.#altText; + if (!isForCopying && this.#guessedText === altText) { + altText = this.#textWithDisclaimer; + } + return { + altText, + decorative: this.#altTextDecorative, + guessedText: this.#guessedText, + textWithDisclaimer: this.#textWithDisclaimer + }; + } + get data() { + return { + altText: this.#altText, + decorative: this.#altTextDecorative + }; + } + set data({ + altText, + decorative, + guessedText, + textWithDisclaimer, + cancel = false + }) { + if (guessedText) { + this.#guessedText = guessedText; + this.#textWithDisclaimer = textWithDisclaimer; + } + if (this.#altText === altText && this.#altTextDecorative === decorative) { + return; + } + if (!cancel) { + this.#altText = altText; + this.#altTextDecorative = decorative; + } + this.#setState(); + } + toggle(enabled = false) { + if (!this.#altTextButton) { + return; + } + if (!enabled && this.#altTextTooltipTimeout) { + clearTimeout(this.#altTextTooltipTimeout); + this.#altTextTooltipTimeout = null; + } + this.#altTextButton.disabled = !enabled; + } + shown() { + this.#editor._reportTelemetry({ + action: "pdfjs.image.alt_text.image_status_label_displayed", + data: { + label: this.#label + } }); } - clone({ - scale = this.scale, - rotation = this.rotation, - offsetX = this.offsetX, - offsetY = this.offsetY, - dontFlip = false - } = {}) { - return new PageViewport({ - viewBox: this.viewBox.slice(), - scale, + destroy() { + this.#altTextButton?.remove(); + this.#altTextButton = null; + this.#altTextTooltip = null; + this.#badge?.remove(); + this.#badge = null; + } + async #setState() { + const button = this.#altTextButton; + if (!button) { + return; + } + if (this.#useNewAltTextFlow) { + const label = this.#label; + const type = label === "review" ? "to-review" : label; + button.classList.toggle("done", !!this.#altText); + AltText._l10nPromise.get(`pdfjs-editor-new-alt-text-${type}-button-label`).then(msg => { + button.setAttribute("aria-label", msg); + for (const child of button.childNodes) { + if (child.nodeType === Node.TEXT_NODE) { + child.textContent = msg; + break; + } + } + }); + if (!this.#altText) { + this.#altTextTooltip?.remove(); + return; + } + } else { + if (!this.#altText && !this.#altTextDecorative) { + button.classList.remove("done"); + this.#altTextTooltip?.remove(); + return; + } + button.classList.add("done"); + AltText._l10nPromise.get("pdfjs-editor-alt-text-edit-button-label").then(msg => { + button.setAttribute("aria-label", msg); + }); + } + let tooltip = this.#altTextTooltip; + if (!tooltip) { + this.#altTextTooltip = tooltip = document.createElement("span"); + tooltip.className = "tooltip"; + tooltip.setAttribute("role", "tooltip"); + const id = tooltip.id = `alt-text-tooltip-${this.#editor.id}`; + button.setAttribute("aria-describedby", id); + const DELAY_TO_SHOW_TOOLTIP = 100; + const signal = this.#editor._uiManager._signal; + signal.addEventListener("abort", () => { + clearTimeout(this.#altTextTooltipTimeout); + this.#altTextTooltipTimeout = null; + }, { + once: true + }); + button.addEventListener("mouseenter", () => { + this.#altTextTooltipTimeout = setTimeout(() => { + this.#altTextTooltipTimeout = null; + this.#altTextTooltip.classList.add("show"); + this.#editor._reportTelemetry({ + action: "alt_text_tooltip" + }); + }, DELAY_TO_SHOW_TOOLTIP); + }, { + signal + }); + button.addEventListener("mouseleave", () => { + if (this.#altTextTooltipTimeout) { + clearTimeout(this.#altTextTooltipTimeout); + this.#altTextTooltipTimeout = null; + } + this.#altTextTooltip?.classList.remove("show"); + }, { + signal + }); + } + tooltip.innerText = this.#altTextDecorative ? await AltText._l10nPromise.get("pdfjs-editor-alt-text-decorative-tooltip") : this.#altText; + if (!tooltip.parentNode) { + button.append(tooltip); + } + const element = this.#editor.getImageForAltText(); + element?.setAttribute("aria-describedby", tooltip.id); + } +} + +;// CONCATENATED MODULE: ./src/display/editor/editor.js + + + + + +class AnnotationEditor { + #accessibilityData = null; + #allResizerDivs = null; + #altText = null; + #disabled = false; + #keepAspectRatio = false; + #resizersDiv = null; + #savedDimensions = null; + #focusAC = null; + #focusedResizerName = ""; + #hasBeenClicked = false; + #initialPosition = null; + #isEditing = false; + #isInEditMode = false; + #isResizerEnabledForKeyboard = false; + #moveInDOMTimeout = null; + #prevDragX = 0; + #prevDragY = 0; + #telemetryTimeouts = null; + _editToolbar = null; + _initialOptions = Object.create(null); + _isVisible = true; + _uiManager = null; + _focusEventsAllowed = true; + static _l10nPromise = null; + static _l10nResizer = null; + #isDraggable = false; + #zIndex = AnnotationEditor._zIndex++; + static _borderLineWidth = -1; + static _colorManager = new ColorManager(); + static _zIndex = 1; + static _telemetryTimeout = 1000; + static get _resizerKeyboardManager() { + const resize = AnnotationEditor.prototype._resizeWithKeyboard; + const small = AnnotationEditorUIManager.TRANSLATE_SMALL; + const big = AnnotationEditorUIManager.TRANSLATE_BIG; + return shadow(this, "_resizerKeyboardManager", new KeyboardManager([[["ArrowLeft", "mac+ArrowLeft"], resize, { + args: [-small, 0] + }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], resize, { + args: [-big, 0] + }], [["ArrowRight", "mac+ArrowRight"], resize, { + args: [small, 0] + }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], resize, { + args: [big, 0] + }], [["ArrowUp", "mac+ArrowUp"], resize, { + args: [0, -small] + }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], resize, { + args: [0, -big] + }], [["ArrowDown", "mac+ArrowDown"], resize, { + args: [0, small] + }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], resize, { + args: [0, big] + }], [["Escape", "mac+Escape"], AnnotationEditor.prototype._stopResizingWithKeyboard]])); + } + constructor(parameters) { + this.parent = parameters.parent; + this.id = parameters.id; + this.width = this.height = null; + this.pageIndex = parameters.parent.pageIndex; + this.name = parameters.name; + this.div = null; + this._uiManager = parameters.uiManager; + this.annotationElementId = null; + this._willKeepAspectRatio = false; + this._initialOptions.isCentered = parameters.isCentered; + this._structTreeParentId = null; + const { rotation, - offsetX, - offsetY, - dontFlip + rawDims: { + pageWidth, + pageHeight, + pageX, + pageY + } + } = this.parent.viewport; + this.rotation = rotation; + this.pageRotation = (360 + rotation - this._uiManager.viewParameters.rotation) % 360; + this.pageDimensions = [pageWidth, pageHeight]; + this.pageTranslation = [pageX, pageY]; + const [width, height] = this.parentDimensions; + this.x = parameters.x / width; + this.y = parameters.y / height; + this.isAttachedToDOM = false; + this.deleted = false; + } + get editorType() { + return Object.getPrototypeOf(this).constructor._type; + } + static get _defaultLineColor() { + return shadow(this, "_defaultLineColor", this._colorManager.getHexCode("CanvasText")); + } + static deleteAnnotationElement(editor) { + const fakeEditor = new FakeEditor({ + id: editor.parent.getNextId(), + parent: editor.parent, + uiManager: editor._uiManager }); + fakeEditor.annotationElementId = editor.annotationElementId; + fakeEditor.deleted = true; + fakeEditor._uiManager.addToAnnotationStorage(fakeEditor); } - convertToViewportPoint(x, y) { - return _util.Util.applyTransform([x, y], this.transform); - } - convertToViewportRectangle(rect) { - const topLeft = _util.Util.applyTransform([rect[0], rect[1]], this.transform); - const bottomRight = _util.Util.applyTransform([rect[2], rect[3]], this.transform); - return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]]; - } - convertToPdfPoint(x, y) { - return _util.Util.applyInverseTransform([x, y], this.transform); - } -} -exports.PageViewport = PageViewport; -class RenderingCancelledException extends _util.BaseException { - constructor(msg, extraDelay = 0) { - super(msg, "RenderingCancelledException"); - this.extraDelay = extraDelay; - } -} -exports.RenderingCancelledException = RenderingCancelledException; -function isDataScheme(url) { - const ii = url.length; - let i = 0; - while (i < ii && url[i].trim() === "") { - i++; - } - return url.substring(i, i + 5).toLowerCase() === "data:"; -} -function isPdfFile(filename) { - return typeof filename === "string" && /\.pdf$/i.test(filename); -} -function getFilenameFromUrl(url, onlyStripPath = false) { - if (!onlyStripPath) { - [url] = url.split(/[#?]/, 1); - } - return url.substring(url.lastIndexOf("/") + 1); -} -function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") { - if (typeof url !== "string") { - return defaultFilename; - } - if (isDataScheme(url)) { - (0, _util.warn)('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'); - return defaultFilename; - } - const reURI = /^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/; - const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i; - const splitURI = reURI.exec(url); - let suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]); - if (suggestedFilename) { - suggestedFilename = suggestedFilename[0]; - if (suggestedFilename.includes("%")) { - try { - suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0]; - } catch {} - } - } - return suggestedFilename || defaultFilename; -} -class StatTimer { - started = Object.create(null); - times = []; - time(name) { - if (name in this.started) { - (0, _util.warn)(`Timer is already running for ${name}`); - } - this.started[name] = Date.now(); - } - timeEnd(name) { - if (!(name in this.started)) { - (0, _util.warn)(`Timer has not been started for ${name}`); - } - this.times.push({ - name, - start: this.started[name], - end: Date.now() + static initialize(l10n, _uiManager, options) { + AnnotationEditor._l10nResizer ||= Object.freeze({ + topLeft: "pdfjs-editor-resizer-top-left", + topMiddle: "pdfjs-editor-resizer-top-middle", + topRight: "pdfjs-editor-resizer-top-right", + middleRight: "pdfjs-editor-resizer-middle-right", + bottomRight: "pdfjs-editor-resizer-bottom-right", + bottomMiddle: "pdfjs-editor-resizer-bottom-middle", + bottomLeft: "pdfjs-editor-resizer-bottom-left", + middleLeft: "pdfjs-editor-resizer-middle-left" }); - delete this.started[name]; - } - toString() { - const outBuf = []; - let longest = 0; - for (const { - name - } of this.times) { - longest = Math.max(name.length, longest); + 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)])]); + if (options?.strings) { + for (const str of options.strings) { + AnnotationEditor._l10nPromise.set(str, l10n.get(str)); + } } - for (const { - name, - start, - end - } of this.times) { - outBuf.push(`${name.padEnd(longest)} ${end - start}ms\n`); + if (AnnotationEditor._borderLineWidth !== -1) { + return; } - return outBuf.join(""); + const style = getComputedStyle(document.documentElement); + AnnotationEditor._borderLineWidth = parseFloat(style.getPropertyValue("--outline-width")) || 0; } -} -exports.StatTimer = StatTimer; -function isValidFetchUrl(url, baseUrl) { - try { - const { - protocol - } = baseUrl ? new URL(url, baseUrl) : new URL(url); - return protocol === "http:" || protocol === "https:"; - } catch { + static updateDefaultParams(_type, _value) {} + static get defaultPropertiesToUpdate() { + return []; + } + static isHandlingMimeForPasting(mime) { return false; } -} -function noContextMenu(e) { - e.preventDefault(); -} -function loadScript(src, removeScriptElement = false) { - return new Promise((resolve, reject) => { - const script = document.createElement("script"); - script.src = src; - script.onload = function (evt) { - if (removeScriptElement) { - script.remove(); + static paste(item, parent) { + unreachable("Not implemented"); + } + get propertiesToUpdate() { + return []; + } + get _isDraggable() { + return this.#isDraggable; + } + set _isDraggable(value) { + this.#isDraggable = value; + this.div?.classList.toggle("draggable", value); + } + get isEnterHandled() { + return true; + } + center() { + const [pageWidth, pageHeight] = this.pageDimensions; + switch (this.parentRotation) { + case 90: + this.x -= this.height * pageHeight / (pageWidth * 2); + this.y += this.width * pageWidth / (pageHeight * 2); + break; + case 180: + this.x += this.width / 2; + this.y += this.height / 2; + break; + case 270: + this.x += this.height * pageHeight / (pageWidth * 2); + this.y -= this.width * pageWidth / (pageHeight * 2); + break; + default: + this.x -= this.width / 2; + this.y -= this.height / 2; + break; + } + this.fixAndSetPosition(); + } + addCommands(params) { + this._uiManager.addCommands(params); + } + get currentLayer() { + return this._uiManager.currentLayer; + } + setInBackground() { + this.div.style.zIndex = 0; + } + setInForeground() { + this.div.style.zIndex = this.#zIndex; + } + setParent(parent) { + if (parent !== null) { + this.pageIndex = parent.pageIndex; + this.pageDimensions = parent.pageDimensions; + } else { + this.#stopResizing(); + } + this.parent = parent; + } + focusin(event) { + if (!this._focusEventsAllowed) { + return; + } + if (!this.#hasBeenClicked) { + this.parent.setSelected(this); + } else { + this.#hasBeenClicked = false; + } + } + focusout(event) { + if (!this._focusEventsAllowed) { + return; + } + if (!this.isAttachedToDOM) { + return; + } + const target = event.relatedTarget; + if (target?.closest(`#${this.id}`)) { + return; + } + event.preventDefault(); + if (!this.parent?.isMultipleSelection) { + this.commitOrRemove(); + } + } + commitOrRemove() { + if (this.isEmpty()) { + this.remove(); + } else { + this.commit(); + } + } + commit() { + this.addToAnnotationStorage(); + } + addToAnnotationStorage() { + this._uiManager.addToAnnotationStorage(this); + } + setAt(x, y, tx, ty) { + const [width, height] = this.parentDimensions; + [tx, ty] = this.screenToPageTranslation(tx, ty); + this.x = (x + tx) / width; + this.y = (y + ty) / height; + this.fixAndSetPosition(); + } + #translate([width, height], x, y) { + [x, y] = this.screenToPageTranslation(x, y); + this.x += x / width; + this.y += y / height; + this.fixAndSetPosition(); + } + translate(x, y) { + this.#translate(this.parentDimensions, x, y); + } + translateInPage(x, y) { + this.#initialPosition ||= [this.x, this.y]; + this.#translate(this.pageDimensions, x, y); + this.div.scrollIntoView({ + block: "nearest" + }); + } + drag(tx, ty) { + this.#initialPosition ||= [this.x, this.y]; + const [parentWidth, parentHeight] = this.parentDimensions; + this.x += tx / parentWidth; + this.y += ty / parentHeight; + if (this.parent && (this.x < 0 || this.x > 1 || this.y < 0 || this.y > 1)) { + const { + x, + y + } = this.div.getBoundingClientRect(); + if (this.parent.findNewParent(this, x, y)) { + this.x -= Math.floor(this.x); + this.y -= Math.floor(this.y); } - resolve(evt); - }; - script.onerror = function () { - reject(new Error(`Cannot load script at: ${script.src}`)); - }; - (document.head || document.documentElement).append(script); - }); -} -function deprecated(details) { - console.log("Deprecated API usage: " + details); -} -let pdfDateStringRegex; -class PDFDateString { - static toDateObject(input) { - if (!input || typeof input !== "string") { - return null; } - pdfDateStringRegex ||= new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?"); - const matches = pdfDateStringRegex.exec(input); - if (!matches) { - return null; - } - const year = parseInt(matches[1], 10); - let month = parseInt(matches[2], 10); - month = month >= 1 && month <= 12 ? month - 1 : 0; - let day = parseInt(matches[3], 10); - day = day >= 1 && day <= 31 ? day : 1; - let hour = parseInt(matches[4], 10); - hour = hour >= 0 && hour <= 23 ? hour : 0; - let minute = parseInt(matches[5], 10); - minute = minute >= 0 && minute <= 59 ? minute : 0; - let second = parseInt(matches[6], 10); - second = second >= 0 && second <= 59 ? second : 0; - const universalTimeRelation = matches[7] || "Z"; - let offsetHour = parseInt(matches[8], 10); - offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0; - let offsetMinute = parseInt(matches[9], 10) || 0; - offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0; - if (universalTimeRelation === "-") { - hour += offsetHour; - minute += offsetMinute; - } else if (universalTimeRelation === "+") { - hour -= offsetHour; - minute -= offsetMinute; - } - return new Date(Date.UTC(year, month, day, hour, minute, second)); + let { + x, + y + } = this; + const [bx, by] = this.getBaseTranslation(); + x += bx; + y += by; + this.div.style.left = `${(100 * x).toFixed(2)}%`; + this.div.style.top = `${(100 * y).toFixed(2)}%`; + this.div.scrollIntoView({ + block: "nearest" + }); } -} -exports.PDFDateString = PDFDateString; -function getXfaPageViewport(xfaPage, { - scale = 1, - rotation = 0 -}) { - const { - width, - height - } = xfaPage.attributes.style; - const viewBox = [0, 0, parseInt(width), parseInt(height)]; - return new PageViewport({ - viewBox, - scale, - rotation - }); -} -function getRGB(color) { - if (color.startsWith("#")) { - const colorRGB = parseInt(color.slice(1), 16); - return [(colorRGB & 0xff0000) >> 16, (colorRGB & 0x00ff00) >> 8, colorRGB & 0x0000ff]; + get _hasBeenMoved() { + return !!this.#initialPosition && (this.#initialPosition[0] !== this.x || this.#initialPosition[1] !== this.y); } - if (color.startsWith("rgb(")) { - return color.slice(4, -1).split(",").map(x => parseInt(x)); - } - if (color.startsWith("rgba(")) { - return color.slice(5, -1).split(",").map(x => parseInt(x)).slice(0, 3); - } - (0, _util.warn)(`Not a valid color format: "${color}"`); - return [0, 0, 0]; -} -function getColorValues(colors) { - const span = document.createElement("span"); - span.style.visibility = "hidden"; - document.body.append(span); - for (const name of colors.keys()) { - span.style.color = name; - const computedColor = window.getComputedStyle(span).color; - colors.set(name, getRGB(computedColor)); - } - span.remove(); -} -function getCurrentTransform(ctx) { - const { - a, - b, - c, - d, - e, - f - } = ctx.getTransform(); - return [a, b, c, d, e, f]; -} -function getCurrentTransformInverse(ctx) { - const { - a, - b, - c, - d, - e, - f - } = ctx.getTransform().invertSelf(); - return [a, b, c, d, e, f]; -} -function setLayerDimensions(div, viewport, mustFlip = false, mustRotate = true) { - if (viewport instanceof PageViewport) { + getBaseTranslation() { + const [parentWidth, parentHeight] = this.parentDimensions; const { - pageWidth, - pageHeight - } = viewport.rawDims; + _borderLineWidth + } = AnnotationEditor; + const x = _borderLineWidth / parentWidth; + const y = _borderLineWidth / parentHeight; + switch (this.rotation) { + case 90: + return [-x, y]; + case 180: + return [x, y]; + case 270: + return [x, -y]; + default: + return [-x, -y]; + } + } + get _mustFixPosition() { + return true; + } + fixAndSetPosition(rotation = this.rotation) { + const [pageWidth, pageHeight] = this.pageDimensions; + let { + x, + y, + width, + height + } = this; + width *= pageWidth; + height *= pageHeight; + x *= pageWidth; + y *= pageHeight; + if (this._mustFixPosition) { + switch (rotation) { + case 0: + x = Math.max(0, Math.min(pageWidth - width, x)); + y = Math.max(0, Math.min(pageHeight - height, y)); + break; + case 90: + x = Math.max(0, Math.min(pageWidth - height, x)); + y = Math.min(pageHeight, Math.max(width, y)); + break; + case 180: + x = Math.min(pageWidth, Math.max(width, x)); + y = Math.min(pageHeight, Math.max(height, y)); + break; + case 270: + x = Math.min(pageWidth, Math.max(height, x)); + y = Math.max(0, Math.min(pageHeight - width, y)); + break; + } + } + this.x = x /= pageWidth; + this.y = y /= pageHeight; + const [bx, by] = this.getBaseTranslation(); + x += bx; + y += by; const { style - } = div; - const useRound = _util.FeatureTest.isCSSRoundSupported; - const w = `var(--scale-factor) * ${pageWidth}px`, - h = `var(--scale-factor) * ${pageHeight}px`; - const widthStr = useRound ? `round(${w}, 1px)` : `calc(${w})`, - heightStr = useRound ? `round(${h}, 1px)` : `calc(${h})`; - if (!mustFlip || viewport.rotation % 180 === 0) { - style.width = widthStr; - style.height = heightStr; + } = this.div; + style.left = `${(100 * x).toFixed(2)}%`; + style.top = `${(100 * y).toFixed(2)}%`; + this.moveInDOM(); + } + static #rotatePoint(x, y, angle) { + switch (angle) { + case 90: + return [y, -x]; + case 180: + return [-x, -y]; + case 270: + return [-y, x]; + default: + return [x, y]; + } + } + screenToPageTranslation(x, y) { + return AnnotationEditor.#rotatePoint(x, y, this.parentRotation); + } + pageTranslationToScreen(x, y) { + return AnnotationEditor.#rotatePoint(x, y, 360 - this.parentRotation); + } + #getRotationMatrix(rotation) { + switch (rotation) { + case 90: + { + const [pageWidth, pageHeight] = this.pageDimensions; + return [0, -pageWidth / pageHeight, pageHeight / pageWidth, 0]; + } + case 180: + return [-1, 0, 0, -1]; + case 270: + { + const [pageWidth, pageHeight] = this.pageDimensions; + return [0, pageWidth / pageHeight, -pageHeight / pageWidth, 0]; + } + default: + return [1, 0, 0, 1]; + } + } + get parentScale() { + return this._uiManager.viewParameters.realScale; + } + get parentRotation() { + return (this._uiManager.viewParameters.rotation + this.pageRotation) % 360; + } + get parentDimensions() { + const { + parentScale, + pageDimensions: [pageWidth, pageHeight] + } = this; + const scaledWidth = pageWidth * parentScale; + const scaledHeight = pageHeight * parentScale; + return util_FeatureTest.isCSSRoundSupported ? [Math.round(scaledWidth), Math.round(scaledHeight)] : [scaledWidth, scaledHeight]; + } + setDims(width, height) { + const [parentWidth, parentHeight] = this.parentDimensions; + this.div.style.width = `${(100 * width / parentWidth).toFixed(2)}%`; + if (!this.#keepAspectRatio) { + this.div.style.height = `${(100 * height / parentHeight).toFixed(2)}%`; + } + } + fixDims() { + const { + style + } = this.div; + const { + height, + width + } = style; + const widthPercent = width.endsWith("%"); + const heightPercent = !this.#keepAspectRatio && height.endsWith("%"); + if (widthPercent && heightPercent) { + return; + } + const [parentWidth, parentHeight] = this.parentDimensions; + if (!widthPercent) { + style.width = `${(100 * parseFloat(width) / parentWidth).toFixed(2)}%`; + } + if (!this.#keepAspectRatio && !heightPercent) { + style.height = `${(100 * parseFloat(height) / parentHeight).toFixed(2)}%`; + } + } + getInitialTranslation() { + return [0, 0]; + } + #createResizers() { + if (this.#resizersDiv) { + return; + } + this.#resizersDiv = document.createElement("div"); + this.#resizersDiv.classList.add("resizers"); + const classes = this._willKeepAspectRatio ? ["topLeft", "topRight", "bottomRight", "bottomLeft"] : ["topLeft", "topMiddle", "topRight", "middleRight", "bottomRight", "bottomMiddle", "bottomLeft", "middleLeft"]; + const signal = this._uiManager._signal; + for (const name of classes) { + const div = document.createElement("div"); + this.#resizersDiv.append(div); + div.classList.add("resizer", name); + div.setAttribute("data-resizer-name", name); + div.addEventListener("pointerdown", this.#resizerPointerdown.bind(this, name), { + signal + }); + div.addEventListener("contextmenu", noContextMenu, { + signal + }); + div.tabIndex = -1; + } + this.div.prepend(this.#resizersDiv); + } + #resizerPointerdown(name, event) { + event.preventDefault(); + const { + isMac + } = util_FeatureTest.platform; + if (event.button !== 0 || event.ctrlKey && isMac) { + return; + } + this.#altText?.toggle(false); + const savedDraggable = this._isDraggable; + this._isDraggable = false; + const ac = new AbortController(); + const signal = this._uiManager.combinedSignal(ac); + this.parent.togglePointerEvents(false); + window.addEventListener("pointermove", this.#resizerPointermove.bind(this, name), { + passive: true, + capture: true, + signal + }); + window.addEventListener("contextmenu", noContextMenu, { + signal + }); + const savedX = this.x; + const savedY = this.y; + const savedWidth = this.width; + const savedHeight = this.height; + const savedParentCursor = this.parent.div.style.cursor; + const savedCursor = this.div.style.cursor; + this.div.style.cursor = this.parent.div.style.cursor = window.getComputedStyle(event.target).cursor; + const pointerUpCallback = () => { + ac.abort(); + this.parent.togglePointerEvents(true); + this.#altText?.toggle(true); + this._isDraggable = savedDraggable; + this.parent.div.style.cursor = savedParentCursor; + this.div.style.cursor = savedCursor; + this.#addResizeToUndoStack(savedX, savedY, savedWidth, savedHeight); + }; + window.addEventListener("pointerup", pointerUpCallback, { + signal + }); + window.addEventListener("blur", pointerUpCallback, { + signal + }); + } + #addResizeToUndoStack(savedX, savedY, savedWidth, savedHeight) { + const newX = this.x; + const newY = this.y; + const newWidth = this.width; + const newHeight = this.height; + if (newX === savedX && newY === savedY && newWidth === savedWidth && newHeight === savedHeight) { + return; + } + this.addCommands({ + cmd: () => { + this.width = newWidth; + this.height = newHeight; + this.x = newX; + this.y = newY; + const [parentWidth, parentHeight] = this.parentDimensions; + this.setDims(parentWidth * newWidth, parentHeight * newHeight); + this.fixAndSetPosition(); + }, + undo: () => { + this.width = savedWidth; + this.height = savedHeight; + this.x = savedX; + this.y = savedY; + const [parentWidth, parentHeight] = this.parentDimensions; + this.setDims(parentWidth * savedWidth, parentHeight * savedHeight); + this.fixAndSetPosition(); + }, + mustExec: true + }); + } + #resizerPointermove(name, event) { + const [parentWidth, parentHeight] = this.parentDimensions; + const savedX = this.x; + const savedY = this.y; + const savedWidth = this.width; + const savedHeight = this.height; + const minWidth = AnnotationEditor.MIN_SIZE / parentWidth; + const minHeight = AnnotationEditor.MIN_SIZE / parentHeight; + const round = x => Math.round(x * 10000) / 10000; + const rotationMatrix = this.#getRotationMatrix(this.rotation); + const transf = (x, y) => [rotationMatrix[0] * x + rotationMatrix[2] * y, rotationMatrix[1] * x + rotationMatrix[3] * y]; + const invRotationMatrix = this.#getRotationMatrix(360 - this.rotation); + const invTransf = (x, y) => [invRotationMatrix[0] * x + invRotationMatrix[2] * y, invRotationMatrix[1] * x + invRotationMatrix[3] * y]; + let getPoint; + let getOpposite; + let isDiagonal = false; + let isHorizontal = false; + switch (name) { + case "topLeft": + isDiagonal = true; + getPoint = (w, h) => [0, 0]; + getOpposite = (w, h) => [w, h]; + break; + case "topMiddle": + getPoint = (w, h) => [w / 2, 0]; + getOpposite = (w, h) => [w / 2, h]; + break; + case "topRight": + isDiagonal = true; + getPoint = (w, h) => [w, 0]; + getOpposite = (w, h) => [0, h]; + break; + case "middleRight": + isHorizontal = true; + getPoint = (w, h) => [w, h / 2]; + getOpposite = (w, h) => [0, h / 2]; + break; + case "bottomRight": + isDiagonal = true; + getPoint = (w, h) => [w, h]; + getOpposite = (w, h) => [0, 0]; + break; + case "bottomMiddle": + getPoint = (w, h) => [w / 2, h]; + getOpposite = (w, h) => [w / 2, 0]; + break; + case "bottomLeft": + isDiagonal = true; + getPoint = (w, h) => [0, h]; + getOpposite = (w, h) => [w, 0]; + break; + case "middleLeft": + isHorizontal = true; + getPoint = (w, h) => [0, h / 2]; + getOpposite = (w, h) => [w, h / 2]; + break; + } + const point = getPoint(savedWidth, savedHeight); + const oppositePoint = getOpposite(savedWidth, savedHeight); + let transfOppositePoint = transf(...oppositePoint); + const oppositeX = round(savedX + transfOppositePoint[0]); + const oppositeY = round(savedY + transfOppositePoint[1]); + let ratioX = 1; + let ratioY = 1; + let [deltaX, deltaY] = this.screenToPageTranslation(event.movementX, event.movementY); + [deltaX, deltaY] = invTransf(deltaX / parentWidth, deltaY / parentHeight); + if (isDiagonal) { + const oldDiag = Math.hypot(savedWidth, savedHeight); + 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); + } else if (isHorizontal) { + ratioX = Math.max(minWidth, Math.min(1, Math.abs(oppositePoint[0] - point[0] - deltaX))) / savedWidth; } else { - style.width = heightStr; - style.height = widthStr; + ratioY = Math.max(minHeight, Math.min(1, Math.abs(oppositePoint[1] - point[1] - deltaY))) / savedHeight; + } + const newWidth = round(savedWidth * ratioX); + const newHeight = round(savedHeight * ratioY); + transfOppositePoint = transf(...getOpposite(newWidth, newHeight)); + const newX = oppositeX - transfOppositePoint[0]; + const newY = oppositeY - transfOppositePoint[1]; + this.width = newWidth; + this.height = newHeight; + this.x = newX; + this.y = newY; + this.setDims(parentWidth * newWidth, parentHeight * newHeight); + this.fixAndSetPosition(); + } + altTextFinish() { + this.#altText?.finish(); + } + async addEditToolbar() { + if (this._editToolbar || this.#isInEditMode) { + return this._editToolbar; + } + this._editToolbar = new EditorToolbar(this); + this.div.append(this._editToolbar.render()); + if (this.#altText) { + await this._editToolbar.addAltText(this.#altText); + } + return this._editToolbar; + } + removeEditToolbar() { + if (!this._editToolbar) { + return; + } + this._editToolbar.remove(); + this._editToolbar = null; + this.#altText?.destroy(); + } + getClientDimensions() { + return this.div.getBoundingClientRect(); + } + async addAltTextButton() { + if (this.#altText) { + return; + } + AltText.initialize(AnnotationEditor._l10nPromise); + this.#altText = new AltText(this); + if (this.#accessibilityData) { + this.#altText.data = this.#accessibilityData; + this.#accessibilityData = null; + } + await this.addEditToolbar(); + } + get altTextData() { + return this.#altText?.data; + } + set altTextData(data) { + if (!this.#altText) { + return; + } + this.#altText.data = data; + } + get guessedAltText() { + return this.#altText?.guessedText; + } + async setGuessedAltText(text) { + await this.#altText?.setGuessedText(text); + } + serializeAltText(isForCopying) { + return this.#altText?.serialize(isForCopying); + } + hasAltText() { + return !!this.#altText && !this.#altText.isEmpty(); + } + hasAltTextData() { + return this.#altText?.hasData() ?? false; + } + render() { + this.div = document.createElement("div"); + this.div.setAttribute("data-editor-rotation", (360 - this.rotation) % 360); + this.div.className = this.name; + this.div.setAttribute("id", this.id); + this.div.tabIndex = this.#disabled ? -1 : 0; + if (!this._isVisible) { + this.div.classList.add("hidden"); + } + this.setInForeground(); + this.#addFocusListeners(); + const [parentWidth, parentHeight] = this.parentDimensions; + if (this.parentRotation % 180 !== 0) { + this.div.style.maxWidth = `${(100 * parentHeight / parentWidth).toFixed(2)}%`; + this.div.style.maxHeight = `${(100 * parentWidth / parentHeight).toFixed(2)}%`; + } + const [tx, ty] = this.getInitialTranslation(); + this.translate(tx, ty); + bindEvents(this, this.div, ["pointerdown"]); + return this.div; + } + pointerdown(event) { + const { + isMac + } = util_FeatureTest.platform; + if (event.button !== 0 || event.ctrlKey && isMac) { + event.preventDefault(); + return; + } + this.#hasBeenClicked = true; + if (this._isDraggable) { + this.#setUpDragSession(event); + return; + } + this.#selectOnPointerEvent(event); + } + #selectOnPointerEvent(event) { + const { + isMac + } = util_FeatureTest.platform; + if (event.ctrlKey && !isMac || event.shiftKey || event.metaKey && isMac) { + this.parent.toggleSelected(this); + } else { + this.parent.setSelected(this); } } - if (mustRotate) { - div.setAttribute("data-main-rotation", viewport.rotation); + #setUpDragSession(event) { + const isSelected = this._uiManager.isSelected(this); + this._uiManager.setUpDragSession(); + const ac = new AbortController(); + const signal = this._uiManager.combinedSignal(ac); + if (isSelected) { + this.div.classList.add("moving"); + this.#prevDragX = event.clientX; + this.#prevDragY = event.clientY; + const pointerMoveCallback = e => { + const { + clientX: x, + clientY: y + } = e; + const [tx, ty] = this.screenToPageTranslation(x - this.#prevDragX, y - this.#prevDragY); + this.#prevDragX = x; + this.#prevDragY = y; + this._uiManager.dragSelectedEditors(tx, ty); + }; + window.addEventListener("pointermove", pointerMoveCallback, { + passive: true, + capture: true, + signal + }); + } + const pointerUpCallback = () => { + ac.abort(); + if (isSelected) { + this.div.classList.remove("moving"); + } + this.#hasBeenClicked = false; + if (!this._uiManager.endDragSession()) { + this.#selectOnPointerEvent(event); + } + }; + window.addEventListener("pointerup", pointerUpCallback, { + signal + }); + window.addEventListener("blur", pointerUpCallback, { + signal + }); } -} - -/***/ }), -/* 7 */ -/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.BaseStandardFontDataFactory = exports.BaseSVGFactory = exports.BaseFilterFactory = exports.BaseCanvasFactory = exports.BaseCMapReaderFactory = void 0; -var _util = __w_pdfjs_require__(1); -class BaseFilterFactory { - constructor() { - if (this.constructor === BaseFilterFactory) { - (0, _util.unreachable)("Cannot initialize BaseFilterFactory."); + moveInDOM() { + if (this.#moveInDOMTimeout) { + clearTimeout(this.#moveInDOMTimeout); + } + this.#moveInDOMTimeout = setTimeout(() => { + this.#moveInDOMTimeout = null; + this.parent?.moveEditorInDOM(this); + }, 0); + } + _setParentAndPosition(parent, x, y) { + parent.changeParent(this); + this.x = x; + this.y = y; + this.fixAndSetPosition(); + } + getRect(tx, ty, rotation = this.rotation) { + const scale = this.parentScale; + const [pageWidth, pageHeight] = this.pageDimensions; + const [pageX, pageY] = this.pageTranslation; + const shiftX = tx / scale; + const shiftY = ty / scale; + const x = this.x * pageWidth; + const y = this.y * pageHeight; + const width = this.width * pageWidth; + const height = this.height * pageHeight; + switch (rotation) { + case 0: + return [x + shiftX + pageX, pageHeight - y - shiftY - height + pageY, x + shiftX + width + pageX, pageHeight - y - shiftY + pageY]; + case 90: + return [x + shiftY + pageX, pageHeight - y + shiftX + pageY, x + shiftY + height + pageX, pageHeight - y + shiftX + width + pageY]; + case 180: + return [x - shiftX - width + pageX, pageHeight - y + shiftY + pageY, x - shiftX + pageX, pageHeight - y + shiftY + height + pageY]; + case 270: + return [x - shiftY - height + pageX, pageHeight - y - shiftX - width + pageY, x - shiftY + pageX, pageHeight - y - shiftX + pageY]; + default: + throw new Error("Invalid rotation"); } } - addFilter(maps) { - return "none"; - } - addHCMFilter(fgColor, bgColor) { - return "none"; - } - addHighlightHCMFilter(fgColor, bgColor, newFgColor, newBgColor) { - return "none"; - } - destroy(keepHCM = false) {} -} -exports.BaseFilterFactory = BaseFilterFactory; -class BaseCanvasFactory { - constructor() { - if (this.constructor === BaseCanvasFactory) { - (0, _util.unreachable)("Cannot initialize BaseCanvasFactory."); + getRectInCurrentCoords(rect, pageHeight) { + const [x1, y1, x2, y2] = rect; + const width = x2 - x1; + const height = y2 - y1; + switch (this.rotation) { + case 0: + return [x1, pageHeight - y2, width, height]; + case 90: + return [x1, pageHeight - y1, height, width]; + case 180: + return [x2, pageHeight - y1, width, height]; + case 270: + return [x2, pageHeight - y2, height, width]; + default: + throw new Error("Invalid rotation"); } } - create(width, height) { - if (width <= 0 || height <= 0) { - throw new Error("Invalid canvas size"); + onceAdded() {} + isEmpty() { + return false; + } + enableEditMode() { + this.#isInEditMode = true; + } + disableEditMode() { + this.#isInEditMode = false; + } + isInEditMode() { + return this.#isInEditMode; + } + shouldGetKeyboardEvents() { + return this.#isResizerEnabledForKeyboard; + } + needsToBeRebuilt() { + return this.div && !this.isAttachedToDOM; + } + #addFocusListeners() { + if (this.#focusAC || !this.div) { + return; } - const canvas = this._createCanvas(width, height); + this.#focusAC = new AbortController(); + const signal = this._uiManager.combinedSignal(this.#focusAC); + this.div.addEventListener("focusin", this.focusin.bind(this), { + signal + }); + this.div.addEventListener("focusout", this.focusout.bind(this), { + signal + }); + } + rebuild() { + this.#addFocusListeners(); + } + rotate(_angle) {} + serialize(isForCopying = false, context = null) { + unreachable("An editor must be serializable"); + } + static deserialize(data, parent, uiManager) { + const editor = new this.prototype.constructor({ + parent, + id: parent.getNextId(), + uiManager + }); + editor.rotation = data.rotation; + editor.#accessibilityData = data.accessibilityData; + const [pageWidth, pageHeight] = editor.pageDimensions; + const [x, y, width, height] = editor.getRectInCurrentCoords(data.rect, pageHeight); + editor.x = x / pageWidth; + editor.y = y / pageHeight; + editor.width = width / pageWidth; + editor.height = height / pageHeight; + return editor; + } + get hasBeenModified() { + return !!this.annotationElementId && (this.deleted || this.serialize() !== null); + } + remove() { + this.#focusAC?.abort(); + this.#focusAC = null; + if (!this.isEmpty()) { + this.commit(); + } + if (this.parent) { + this.parent.remove(this); + } else { + this._uiManager.removeEditor(this); + } + if (this.#moveInDOMTimeout) { + clearTimeout(this.#moveInDOMTimeout); + this.#moveInDOMTimeout = null; + } + this.#stopResizing(); + this.removeEditToolbar(); + if (this.#telemetryTimeouts) { + for (const timeout of this.#telemetryTimeouts.values()) { + clearTimeout(timeout); + } + this.#telemetryTimeouts = null; + } + this.parent = null; + } + get isResizable() { + return false; + } + makeResizable() { + if (this.isResizable) { + this.#createResizers(); + this.#resizersDiv.classList.remove("hidden"); + bindEvents(this, this.div, ["keydown"]); + } + } + get toolbarPosition() { + return null; + } + keydown(event) { + if (!this.isResizable || event.target !== this.div || event.key !== "Enter") { + return; + } + this._uiManager.setSelected(this); + this.#savedDimensions = { + savedX: this.x, + savedY: this.y, + savedWidth: this.width, + savedHeight: this.height + }; + const children = this.#resizersDiv.children; + if (!this.#allResizerDivs) { + this.#allResizerDivs = Array.from(children); + const boundResizerKeydown = this.#resizerKeydown.bind(this); + const boundResizerBlur = this.#resizerBlur.bind(this); + const signal = this._uiManager._signal; + for (const div of this.#allResizerDivs) { + const name = div.getAttribute("data-resizer-name"); + div.setAttribute("role", "spinbutton"); + div.addEventListener("keydown", boundResizerKeydown, { + signal + }); + div.addEventListener("blur", boundResizerBlur, { + signal + }); + div.addEventListener("focus", this.#resizerFocus.bind(this, name), { + signal + }); + div.setAttribute("data-l10n-id", AnnotationEditor._l10nResizer[name]); + } + } + const first = this.#allResizerDivs[0]; + let firstPosition = 0; + for (const div of children) { + if (div === first) { + break; + } + firstPosition++; + } + const nextFirstPosition = (360 - this.rotation + this.parentRotation) % 360 / 90 * (this.#allResizerDivs.length / 4); + if (nextFirstPosition !== firstPosition) { + if (nextFirstPosition < firstPosition) { + for (let i = 0; i < firstPosition - nextFirstPosition; i++) { + this.#resizersDiv.append(this.#resizersDiv.firstChild); + } + } else if (nextFirstPosition > firstPosition) { + for (let i = 0; i < nextFirstPosition - firstPosition; i++) { + this.#resizersDiv.firstChild.before(this.#resizersDiv.lastChild); + } + } + let i = 0; + for (const child of children) { + const div = this.#allResizerDivs[i++]; + const name = div.getAttribute("data-resizer-name"); + child.setAttribute("data-l10n-id", AnnotationEditor._l10nResizer[name]); + } + } + this.#setResizerTabIndex(0); + this.#isResizerEnabledForKeyboard = true; + this.#resizersDiv.firstChild.focus({ + focusVisible: true + }); + event.preventDefault(); + event.stopImmediatePropagation(); + } + #resizerKeydown(event) { + AnnotationEditor._resizerKeyboardManager.exec(this, event); + } + #resizerBlur(event) { + if (this.#isResizerEnabledForKeyboard && event.relatedTarget?.parentNode !== this.#resizersDiv) { + this.#stopResizing(); + } + } + #resizerFocus(name) { + this.#focusedResizerName = this.#isResizerEnabledForKeyboard ? name : ""; + } + #setResizerTabIndex(value) { + if (!this.#allResizerDivs) { + return; + } + for (const div of this.#allResizerDivs) { + div.tabIndex = value; + } + } + _resizeWithKeyboard(x, y) { + if (!this.#isResizerEnabledForKeyboard) { + return; + } + this.#resizerPointermove(this.#focusedResizerName, { + movementX: x, + movementY: y + }); + } + #stopResizing() { + this.#isResizerEnabledForKeyboard = false; + this.#setResizerTabIndex(-1); + if (this.#savedDimensions) { + const { + savedX, + savedY, + savedWidth, + savedHeight + } = this.#savedDimensions; + this.#addResizeToUndoStack(savedX, savedY, savedWidth, savedHeight); + this.#savedDimensions = null; + } + } + _stopResizingWithKeyboard() { + this.#stopResizing(); + this.div.focus(); + } + select() { + this.makeResizable(); + this.div?.classList.add("selectedEditor"); + if (!this._editToolbar) { + this.addEditToolbar().then(() => { + if (this.div?.classList.contains("selectedEditor")) { + this._editToolbar?.show(); + } + }); + return; + } + this._editToolbar?.show(); + this.#altText?.toggleAltTextBadge(false); + } + unselect() { + this.#resizersDiv?.classList.add("hidden"); + this.div?.classList.remove("selectedEditor"); + if (this.div?.contains(document.activeElement)) { + this._uiManager.currentLayer.div.focus({ + preventScroll: true + }); + } + this._editToolbar?.hide(); + this.#altText?.toggleAltTextBadge(true); + } + updateParams(type, value) {} + disableEditing() {} + enableEditing() {} + enterInEditMode() {} + getImageForAltText() { + return null; + } + get contentDiv() { + return this.div; + } + get isEditing() { + return this.#isEditing; + } + set isEditing(value) { + this.#isEditing = value; + if (!this.parent) { + return; + } + if (value) { + this.parent.setSelected(this); + this.parent.setActiveEditor(this); + } else { + this.parent.setActiveEditor(null); + } + } + setAspectRatio(width, height) { + this.#keepAspectRatio = true; + const aspectRatio = width / height; + const { + style + } = this.div; + style.aspectRatio = aspectRatio; + style.height = "auto"; + } + static get MIN_SIZE() { + return 16; + } + static canCreateNewEmptyEditor() { + return true; + } + get telemetryInitialData() { return { - canvas, - context: canvas.getContext("2d") + action: "added" }; } - reset(canvasAndContext, width, height) { - if (!canvasAndContext.canvas) { - throw new Error("Canvas is not specified"); - } - if (width <= 0 || height <= 0) { - throw new Error("Invalid canvas size"); - } - canvasAndContext.canvas.width = width; - canvasAndContext.canvas.height = height; + get telemetryFinalData() { + return null; } - destroy(canvasAndContext) { - if (!canvasAndContext.canvas) { - throw new Error("Canvas is not specified"); + _reportTelemetry(data, mustWait = false) { + if (mustWait) { + this.#telemetryTimeouts ||= new Map(); + const { + action + } = data; + let timeout = this.#telemetryTimeouts.get(action); + if (timeout) { + clearTimeout(timeout); + } + timeout = setTimeout(() => { + this._reportTelemetry(data); + this.#telemetryTimeouts.delete(action); + if (this.#telemetryTimeouts.size === 0) { + this.#telemetryTimeouts = null; + } + }, AnnotationEditor._telemetryTimeout); + this.#telemetryTimeouts.set(action, timeout); + return; } - canvasAndContext.canvas.width = 0; - canvasAndContext.canvas.height = 0; - canvasAndContext.canvas = null; - canvasAndContext.context = null; - } - _createCanvas(width, height) { - (0, _util.unreachable)("Abstract method `_createCanvas` called."); - } -} -exports.BaseCanvasFactory = BaseCanvasFactory; -class BaseCMapReaderFactory { - constructor({ - baseUrl = null, - isCompressed = true - }) { - if (this.constructor === BaseCMapReaderFactory) { - (0, _util.unreachable)("Cannot initialize BaseCMapReaderFactory."); - } - this.baseUrl = baseUrl; - this.isCompressed = isCompressed; - } - async fetch({ - name - }) { - if (!this.baseUrl) { - throw new Error('The CMap "baseUrl" parameter must be specified, ensure that ' + 'the "cMapUrl" and "cMapPacked" API parameters are provided.'); - } - if (!name) { - throw new Error("CMap name must be specified."); - } - const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : ""); - const compressionType = this.isCompressed ? _util.CMapCompressionType.BINARY : _util.CMapCompressionType.NONE; - return this._fetchData(url, compressionType).catch(reason => { - throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`); + data.type ||= this.editorType; + this._uiManager._eventBus.dispatch("reporttelemetry", { + source: this, + details: { + type: "editing", + data + } }); } - _fetchData(url, compressionType) { - (0, _util.unreachable)("Abstract method `_fetchData` called."); + show(visible = this._isVisible) { + this.div.classList.toggle("hidden", !visible); + this._isVisible = visible; + } + enable() { + if (this.div) { + this.div.tabIndex = 0; + } + this.#disabled = false; + } + disable() { + if (this.div) { + this.div.tabIndex = -1; + } + this.#disabled = true; + } + renderAnnotationElement(annotation) { + let content = annotation.container.querySelector(".annotationContent"); + if (!content) { + content = document.createElement("div"); + content.classList.add("annotationContent", this.editorType); + annotation.container.prepend(content); + } else if (content.nodeName === "CANVAS") { + const canvas = content; + content = document.createElement("div"); + content.classList.add("annotationContent", this.editorType); + canvas.before(content); + } + return content; + } + resetAnnotationElement(annotation) { + const { + firstChild + } = annotation.container; + if (firstChild.nodeName === "DIV" && firstChild.classList.contains("annotationContent")) { + firstChild.remove(); + } } } -exports.BaseCMapReaderFactory = BaseCMapReaderFactory; -class BaseStandardFontDataFactory { - constructor({ - baseUrl = null - }) { - if (this.constructor === BaseStandardFontDataFactory) { - (0, _util.unreachable)("Cannot initialize BaseStandardFontDataFactory."); - } - this.baseUrl = baseUrl; +class FakeEditor extends AnnotationEditor { + constructor(params) { + super(params); + this.annotationElementId = params.annotationElementId; + this.deleted = true; } - async fetch({ - filename - }) { - if (!this.baseUrl) { - throw new Error('The standard font "baseUrl" parameter must be specified, ensure that ' + 'the "standardFontDataUrl" API parameter is provided.'); - } - if (!filename) { - throw new Error("Font filename must be specified."); - } - const url = `${this.baseUrl}${filename}`; - return this._fetchData(url).catch(reason => { - throw new Error(`Unable to load font data at: ${url}`); - }); - } - _fetchData(url) { - (0, _util.unreachable)("Abstract method `_fetchData` called."); + serialize() { + return { + id: this.annotationElementId, + deleted: true, + pageIndex: this.pageIndex + }; } } -exports.BaseStandardFontDataFactory = BaseStandardFontDataFactory; -class BaseSVGFactory { - constructor() { - if (this.constructor === BaseSVGFactory) { - (0, _util.unreachable)("Cannot initialize BaseSVGFactory."); - } - } - create(width, height, skipDimensions = false) { - if (width <= 0 || height <= 0) { - throw new Error("Invalid SVG dimensions"); - } - const svg = this._createSVG("svg:svg"); - svg.setAttribute("version", "1.1"); - if (!skipDimensions) { - svg.setAttribute("width", `${width}px`); - svg.setAttribute("height", `${height}px`); - } - svg.setAttribute("preserveAspectRatio", "none"); - svg.setAttribute("viewBox", `0 0 ${width} ${height}`); - return svg; - } - createElement(type) { - if (typeof type !== "string") { - throw new Error("Invalid SVG element type"); - } - return this._createSVG(type); - } - _createSVG(type) { - (0, _util.unreachable)("Abstract method `_createSVG` called."); - } -} -exports.BaseSVGFactory = BaseSVGFactory; -/***/ }), -/* 8 */ -/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.MurmurHash3_64 = void 0; -var _util = __w_pdfjs_require__(1); +;// CONCATENATED MODULE: ./src/shared/murmurhash3.js const SEED = 0xc3d2e1f0; const MASK_HIGH = 0xffff0000; const MASK_LOW = 0xffff; @@ -5843,11 +5043,11 @@ class MurmurHash3_64 { data[length++] = code & 0xff; } } - } else if ((0, _util.isArrayBuffer)(input)) { + } else if (ArrayBuffer.isView(input)) { data = input.slice(); length = data.byteLength; } else { - throw new Error("Wrong data format in MurmurHash3_64_update. " + "Input must be a string or array."); + throw new Error("Invalid data format, must be a string or TypedArray."); } const blockCounts = length >> 2; const tailLength = length - blockCounts * 4; @@ -5912,19 +5112,224 @@ class MurmurHash3_64 { return (h1 >>> 0).toString(16).padStart(8, "0") + (h2 >>> 0).toString(16).padStart(8, "0"); } } -exports.MurmurHash3_64 = MurmurHash3_64; -/***/ }), -/* 9 */ -/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { +;// CONCATENATED MODULE: ./src/display/annotation_storage.js -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.FontLoader = exports.FontFaceObject = void 0; -var _util = __w_pdfjs_require__(1); +const SerializableEmpty = Object.freeze({ + map: null, + hash: "", + transfer: undefined +}); +class AnnotationStorage { + #modified = false; + #modifiedIds = null; + #storage = new Map(); + constructor() { + this.onSetModified = null; + this.onResetModified = null; + this.onAnnotationEditor = null; + } + getValue(key, defaultValue) { + const value = this.#storage.get(key); + if (value === undefined) { + return defaultValue; + } + return Object.assign(defaultValue, value); + } + getRawValue(key) { + return this.#storage.get(key); + } + remove(key) { + this.#storage.delete(key); + if (this.#storage.size === 0) { + this.resetModified(); + } + if (typeof this.onAnnotationEditor === "function") { + for (const value of this.#storage.values()) { + if (value instanceof AnnotationEditor) { + return; + } + } + this.onAnnotationEditor(null); + } + } + setValue(key, value) { + const obj = this.#storage.get(key); + let modified = false; + if (obj !== undefined) { + for (const [entry, val] of Object.entries(value)) { + if (obj[entry] !== val) { + modified = true; + obj[entry] = val; + } + } + } else { + modified = true; + this.#storage.set(key, value); + } + if (modified) { + this.#setModified(); + } + if (value instanceof AnnotationEditor && typeof this.onAnnotationEditor === "function") { + this.onAnnotationEditor(value.constructor._type); + } + } + has(key) { + return this.#storage.has(key); + } + getAll() { + return this.#storage.size > 0 ? objectFromMap(this.#storage) : null; + } + setAll(obj) { + for (const [key, val] of Object.entries(obj)) { + this.setValue(key, val); + } + } + get size() { + return this.#storage.size; + } + #setModified() { + if (!this.#modified) { + this.#modified = true; + if (typeof this.onSetModified === "function") { + this.onSetModified(); + } + } + } + resetModified() { + if (this.#modified) { + this.#modified = false; + if (typeof this.onResetModified === "function") { + this.onResetModified(); + } + } + } + get print() { + return new PrintAnnotationStorage(this); + } + get serializable() { + if (this.#storage.size === 0) { + return SerializableEmpty; + } + const map = new Map(), + hash = new MurmurHash3_64(), + transfer = []; + const context = Object.create(null); + let hasBitmap = false; + for (const [key, val] of this.#storage) { + const serialized = val instanceof AnnotationEditor ? val.serialize(false, context) : val; + if (serialized) { + map.set(key, serialized); + hash.update(`${key}:${JSON.stringify(serialized)}`); + hasBitmap ||= !!serialized.bitmap; + } + } + if (hasBitmap) { + for (const value of map.values()) { + if (value.bitmap) { + transfer.push(value.bitmap); + } + } + } + return map.size > 0 ? { + map, + hash: hash.hexdigest(), + transfer + } : SerializableEmpty; + } + get editorStats() { + let stats = null; + const typeToEditor = new Map(); + for (const value of this.#storage.values()) { + if (!(value instanceof AnnotationEditor)) { + continue; + } + const editorStats = value.telemetryFinalData; + if (!editorStats) { + continue; + } + const { + type + } = editorStats; + if (!typeToEditor.has(type)) { + typeToEditor.set(type, Object.getPrototypeOf(value).constructor); + } + stats ||= Object.create(null); + const map = stats[type] ||= new Map(); + for (const [key, val] of Object.entries(editorStats)) { + if (key === "type") { + continue; + } + let counters = map.get(key); + if (!counters) { + counters = new Map(); + map.set(key, counters); + } + const count = counters.get(val) ?? 0; + counters.set(val, count + 1); + } + } + for (const [type, editor] of typeToEditor) { + stats[type] = editor.computeTelemetryFinalData(stats[type]); + } + return stats; + } + resetModifiedIds() { + this.#modifiedIds = null; + } + get modifiedIds() { + if (this.#modifiedIds) { + return this.#modifiedIds; + } + const ids = []; + for (const value of this.#storage.values()) { + if (!(value instanceof AnnotationEditor) || !value.annotationElementId || !value.serialize()) { + continue; + } + ids.push(value.annotationElementId); + } + return this.#modifiedIds = { + ids: new Set(ids), + hash: ids.join(",") + }; + } +} +class PrintAnnotationStorage extends AnnotationStorage { + #serializable; + constructor(parent) { + super(); + const { + map, + hash, + transfer + } = parent.serializable; + const clone = structuredClone(map, transfer ? { + transfer + } : null); + this.#serializable = { + map: clone, + hash, + transfer + }; + } + get print() { + unreachable("Should not call PrintAnnotationStorage.print"); + } + get serializable() { + return this.#serializable; + } + get modifiedIds() { + return shadow(this, "modifiedIds", { + ids: new Set(), + hash: "" + }); + } +} + +;// CONCATENATED MODULE: ./src/display/font_loader.js + class FontLoader { #systemFonts = new Set(); constructor({ @@ -5964,11 +5369,14 @@ class FontLoader { this.styleElement = null; } } - async loadSystemFont(info) { + async loadSystemFont({ + systemFontInfo: info, + _inspectFont + }) { if (!info || this.#systemFonts.has(info.loadedName)) { return; } - (0, _util.assert)(!this.disableFontFace, "loadSystemFont shouldn't be called when `disableFontFace` is set."); + assert(!this.disableFontFace, "loadSystemFont shouldn't be called when `disableFontFace` is set."); if (this.isFontLoadingAPISupported) { const { loadedName, @@ -5980,13 +5388,14 @@ class FontLoader { try { await fontFace.load(); this.#systemFonts.add(loadedName); + _inspectFont?.(info); } catch { - (0, _util.warn)(`Cannot load system font: ${info.baseFontName}, installing it could help to improve PDF rendering.`); + warn(`Cannot load system font: ${info.baseFontName}, installing it could help to improve PDF rendering.`); this.removeNativeFontFace(fontFace); } return; } - (0, _util.unreachable)("Not implemented: loadSystemFont without the Font Loading API."); + unreachable("Not implemented: loadSystemFont without the Font Loading API."); } async bind(font) { if (font.attached || font.missingFile && !font.systemFontInfo) { @@ -5994,7 +5403,7 @@ class FontLoader { } font.attached = true; if (font.systemFontInfo) { - await this.loadSystemFont(font.systemFontInfo); + await this.loadSystemFont(font); return; } if (this.isFontLoadingAPISupported) { @@ -6004,7 +5413,7 @@ class FontLoader { try { await nativeFontFace.loaded; } catch (ex) { - (0, _util.warn)(`Failed to load font '${nativeFontFace.family}': '${ex}'.`); + warn(`Failed to load font '${nativeFontFace.family}': '${ex}'.`); font.disableFontFace = true; throw ex; } @@ -6025,20 +5434,20 @@ class FontLoader { } get isFontLoadingAPISupported() { const hasFonts = !!this._document?.fonts; - return (0, _util.shadow)(this, "isFontLoadingAPISupported", hasFonts); + return shadow(this, "isFontLoadingAPISupported", hasFonts); } get isSyncFontLoadingSupported() { let supported = false; - if (_util.isNodeJS) { + if (isNodeJS) { supported = true; - } else if (typeof navigator !== "undefined" && /Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent)) { + } else if (typeof navigator !== "undefined" && typeof navigator?.userAgent === "string" && /Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent)) { supported = true; } - return (0, _util.shadow)(this, "isSyncFontLoadingSupported", supported); + return shadow(this, "isSyncFontLoadingSupported", supported); } _queueLoadingCallback(callback) { function completeRequest() { - (0, _util.assert)(!request.done, "completeRequest() cannot be called twice."); + assert(!request.done, "completeRequest() cannot be called twice."); request.done = true; while (loadingRequests.length > 0 && loadingRequests[0].done) { const otherRequest = loadingRequests.shift(); @@ -6058,7 +5467,7 @@ class FontLoader { } get _loadTestFont() { 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=="); - return (0, _util.shadow)(this, "_loadTestFont", testFont); + return shadow(this, "_loadTestFont", testFont); } _prepareFontLoadEvent(font, request) { function int32(data, offset) { @@ -6077,7 +5486,7 @@ class FontLoader { let called = 0; function isFontReady(name, callback) { if (++called > 30) { - (0, _util.warn)("Load test font never loaded."); + warn("Load test font never loaded."); callback(); return; } @@ -6103,7 +5512,7 @@ class FontLoader { if (i < loadTestFontId.length) { checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i) | 0; } - data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, (0, _util.string32)(checksum)); + data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum)); const url = `url(data:font/opentype;base64,${btoa(data)});`; const rule = `@font-face {font-family:"${loadTestFontId}";src:${url}}`; this.insertRule(rule); @@ -6125,21 +5534,16 @@ class FontLoader { }); } } -exports.FontLoader = FontLoader; class FontFaceObject { constructor(translatedData, { - isEvalSupported = true, disableFontFace = false, - ignoreErrors = false, inspectFont = null }) { this.compiledGlyphs = Object.create(null); for (const i in translatedData) { this[i] = translatedData[i]; } - this.isEvalSupported = isEvalSupported !== false; this.disableFontFace = disableFontFace === true; - this.ignoreErrors = ignoreErrors === true; this._inspectFont = inspectFont; } createNativeFontFace() { @@ -6165,7 +5569,7 @@ class FontFaceObject { if (!this.data || this.disableFontFace) { return null; } - const data = (0, _util.bytesToString)(this.data); + const data = bytesToString(this.data); const url = `url(data:${this.mimetype};base64,${btoa(data)});`; let rule; if (!this.cssFontInfo) { @@ -6188,2317 +5592,149 @@ class FontFaceObject { try { cmds = objs.get(this.loadedName + "_path_" + character); } catch (ex) { - if (!this.ignoreErrors) { - throw ex; - } - (0, _util.warn)(`getPathGenerator - ignoring character: "${ex}".`); + warn(`getPathGenerator - ignoring character: "${ex}".`); + } + if (!Array.isArray(cmds) || cmds.length === 0) { return this.compiledGlyphs[character] = function (c, size) {}; } - if (this.isEvalSupported && _util.FeatureTest.isEvalSupported) { - const jsBuf = []; - for (const current of cmds) { - const args = current.args !== undefined ? current.args.join(",") : ""; - jsBuf.push("c.", current.cmd, "(", args, ");\n"); + const commands = []; + for (let i = 0, ii = cmds.length; i < ii;) { + switch (cmds[i++]) { + case FontRenderOps.BEZIER_CURVE_TO: + { + const [a, b, c, d, e, f] = cmds.slice(i, i + 6); + commands.push(ctx => ctx.bezierCurveTo(a, b, c, d, e, f)); + i += 6; + } + break; + case FontRenderOps.MOVE_TO: + { + const [a, b] = cmds.slice(i, i + 2); + commands.push(ctx => ctx.moveTo(a, b)); + i += 2; + } + break; + case FontRenderOps.LINE_TO: + { + const [a, b] = cmds.slice(i, i + 2); + commands.push(ctx => ctx.lineTo(a, b)); + i += 2; + } + break; + case FontRenderOps.QUADRATIC_CURVE_TO: + { + const [a, b, c, d] = cmds.slice(i, i + 4); + commands.push(ctx => ctx.quadraticCurveTo(a, b, c, d)); + i += 4; + } + break; + case FontRenderOps.RESTORE: + commands.push(ctx => ctx.restore()); + break; + case FontRenderOps.SAVE: + commands.push(ctx => ctx.save()); + break; + case FontRenderOps.SCALE: + assert(commands.length === 2, "Scale command is only valid at the third position."); + break; + case FontRenderOps.TRANSFORM: + { + const [a, b, c, d, e, f] = cmds.slice(i, i + 6); + commands.push(ctx => ctx.transform(a, b, c, d, e, f)); + i += 6; + } + break; + case FontRenderOps.TRANSLATE: + { + const [a, b] = cmds.slice(i, i + 2); + commands.push(ctx => ctx.translate(a, b)); + i += 2; + } + break; } - return this.compiledGlyphs[character] = new Function("c", "size", jsBuf.join("")); } - return this.compiledGlyphs[character] = function (c, size) { - for (const current of cmds) { - if (current.cmd === "scale") { - current.args = [size, -size]; - } - c[current.cmd].apply(c, current.args); + return this.compiledGlyphs[character] = function glyphDrawer(ctx, size) { + commands[0](ctx); + commands[1](ctx); + ctx.scale(size, -size); + for (let i = 2, ii = commands.length; i < ii; i++) { + commands[i](ctx); } }; } } -exports.FontFaceObject = FontFaceObject; -/***/ }), -/* 10 */ -/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { +;// CONCATENATED MODULE: ./src/display/node_utils.js - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.NodeStandardFontDataFactory = exports.NodeFilterFactory = exports.NodeCanvasFactory = exports.NodeCMapReaderFactory = void 0; -var _base_factory = __w_pdfjs_require__(7); -var _util = __w_pdfjs_require__(1); -; -; -const fetchData = function (url) { - return new Promise((resolve, reject) => { - const fs = require("fs"); - fs.readFile(url, (error, data) => { - if (error || !data) { - reject(new Error(error)); - return; - } - resolve(new Uint8Array(data)); - }); - }); -}; -class NodeFilterFactory extends _base_factory.BaseFilterFactory {} -exports.NodeFilterFactory = NodeFilterFactory; -class NodeCanvasFactory extends _base_factory.BaseCanvasFactory { - _createCanvas(width, height) { - const Canvas = require("canvas"); - return Canvas.createCanvas(width, height); - } -} -exports.NodeCanvasFactory = NodeCanvasFactory; -class NodeCMapReaderFactory extends _base_factory.BaseCMapReaderFactory { - _fetchData(url, compressionType) { - return fetchData(url).then(data => { - return { - cMapData: data, - compressionType - }; - }); - } -} -exports.NodeCMapReaderFactory = NodeCMapReaderFactory; -class NodeStandardFontDataFactory extends _base_factory.BaseStandardFontDataFactory { - _fetchData(url) { - return fetchData(url); - } -} -exports.NodeStandardFontDataFactory = NodeStandardFontDataFactory; - -/***/ }), -/* 11 */ -/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.CanvasGraphics = void 0; -var _util = __w_pdfjs_require__(1); -var _display_utils = __w_pdfjs_require__(6); -var _pattern_helper = __w_pdfjs_require__(12); -var _image_utils = __w_pdfjs_require__(13); -const MIN_FONT_SIZE = 16; -const MAX_FONT_SIZE = 100; -const MAX_GROUP_SIZE = 4096; -const EXECUTION_TIME = 15; -const EXECUTION_STEPS = 10; -const MAX_SIZE_TO_COMPILE = 1000; -const FULL_CHUNK_HEIGHT = 16; -function mirrorContextOperations(ctx, destCtx) { - if (ctx._removeMirroring) { - throw new Error("Context is already forwarding operations."); - } - ctx.__originalSave = ctx.save; - ctx.__originalRestore = ctx.restore; - ctx.__originalRotate = ctx.rotate; - ctx.__originalScale = ctx.scale; - ctx.__originalTranslate = ctx.translate; - ctx.__originalTransform = ctx.transform; - ctx.__originalSetTransform = ctx.setTransform; - ctx.__originalResetTransform = ctx.resetTransform; - ctx.__originalClip = ctx.clip; - ctx.__originalMoveTo = ctx.moveTo; - ctx.__originalLineTo = ctx.lineTo; - ctx.__originalBezierCurveTo = ctx.bezierCurveTo; - ctx.__originalRect = ctx.rect; - ctx.__originalClosePath = ctx.closePath; - ctx.__originalBeginPath = ctx.beginPath; - ctx._removeMirroring = () => { - ctx.save = ctx.__originalSave; - ctx.restore = ctx.__originalRestore; - ctx.rotate = ctx.__originalRotate; - ctx.scale = ctx.__originalScale; - ctx.translate = ctx.__originalTranslate; - ctx.transform = ctx.__originalTransform; - ctx.setTransform = ctx.__originalSetTransform; - ctx.resetTransform = ctx.__originalResetTransform; - ctx.clip = ctx.__originalClip; - ctx.moveTo = ctx.__originalMoveTo; - ctx.lineTo = ctx.__originalLineTo; - ctx.bezierCurveTo = ctx.__originalBezierCurveTo; - ctx.rect = ctx.__originalRect; - ctx.closePath = ctx.__originalClosePath; - ctx.beginPath = ctx.__originalBeginPath; - delete ctx._removeMirroring; - }; - ctx.save = function ctxSave() { - destCtx.save(); - this.__originalSave(); - }; - ctx.restore = function ctxRestore() { - destCtx.restore(); - this.__originalRestore(); - }; - ctx.translate = function ctxTranslate(x, y) { - destCtx.translate(x, y); - this.__originalTranslate(x, y); - }; - ctx.scale = function ctxScale(x, y) { - destCtx.scale(x, y); - this.__originalScale(x, y); - }; - ctx.transform = function ctxTransform(a, b, c, d, e, f) { - destCtx.transform(a, b, c, d, e, f); - this.__originalTransform(a, b, c, d, e, f); - }; - ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) { - destCtx.setTransform(a, b, c, d, e, f); - this.__originalSetTransform(a, b, c, d, e, f); - }; - ctx.resetTransform = function ctxResetTransform() { - destCtx.resetTransform(); - this.__originalResetTransform(); - }; - ctx.rotate = function ctxRotate(angle) { - destCtx.rotate(angle); - this.__originalRotate(angle); - }; - ctx.clip = function ctxRotate(rule) { - destCtx.clip(rule); - this.__originalClip(rule); - }; - ctx.moveTo = function (x, y) { - destCtx.moveTo(x, y); - this.__originalMoveTo(x, y); - }; - ctx.lineTo = function (x, y) { - destCtx.lineTo(x, y); - this.__originalLineTo(x, y); - }; - ctx.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) { - destCtx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y); - this.__originalBezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y); - }; - ctx.rect = function (x, y, width, height) { - destCtx.rect(x, y, width, height); - this.__originalRect(x, y, width, height); - }; - ctx.closePath = function () { - destCtx.closePath(); - this.__originalClosePath(); - }; - ctx.beginPath = function () { - destCtx.beginPath(); - this.__originalBeginPath(); - }; -} -class CachedCanvases { - constructor(canvasFactory) { - this.canvasFactory = canvasFactory; - this.cache = Object.create(null); - } - getCanvas(id, width, height) { - let canvasEntry; - if (this.cache[id] !== undefined) { - canvasEntry = this.cache[id]; - this.canvasFactory.reset(canvasEntry, width, height); - } else { - canvasEntry = this.canvasFactory.create(width, height); - this.cache[id] = canvasEntry; - } - return canvasEntry; - } - delete(id) { - delete this.cache[id]; - } - clear() { - for (const id in this.cache) { - const canvasEntry = this.cache[id]; - this.canvasFactory.destroy(canvasEntry); - delete this.cache[id]; - } - } -} -function drawImageAtIntegerCoords(ctx, srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH) { - const [a, b, c, d, tx, ty] = (0, _display_utils.getCurrentTransform)(ctx); - if (b === 0 && c === 0) { - const tlX = destX * a + tx; - const rTlX = Math.round(tlX); - const tlY = destY * d + ty; - const rTlY = Math.round(tlY); - const brX = (destX + destW) * a + tx; - const rWidth = Math.abs(Math.round(brX) - rTlX) || 1; - const brY = (destY + destH) * d + ty; - const rHeight = Math.abs(Math.round(brY) - rTlY) || 1; - ctx.setTransform(Math.sign(a), 0, 0, Math.sign(d), rTlX, rTlY); - ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rWidth, rHeight); - ctx.setTransform(a, b, c, d, tx, ty); - return [rWidth, rHeight]; - } - if (a === 0 && d === 0) { - const tlX = destY * c + tx; - const rTlX = Math.round(tlX); - const tlY = destX * b + ty; - const rTlY = Math.round(tlY); - const brX = (destY + destH) * c + tx; - const rWidth = Math.abs(Math.round(brX) - rTlX) || 1; - const brY = (destX + destW) * b + ty; - const rHeight = Math.abs(Math.round(brY) - rTlY) || 1; - ctx.setTransform(0, Math.sign(b), Math.sign(c), 0, rTlX, rTlY); - ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rHeight, rWidth); - ctx.setTransform(a, b, c, d, tx, ty); - return [rHeight, rWidth]; - } - ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH); - const scaleX = Math.hypot(a, b); - const scaleY = Math.hypot(c, d); - return [scaleX * destW, scaleY * destH]; -} -function compileType3Glyph(imgData) { - const { - width, - height - } = imgData; - if (width > MAX_SIZE_TO_COMPILE || height > MAX_SIZE_TO_COMPILE) { - return null; - } - const POINT_TO_PROCESS_LIMIT = 1000; - const POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]); - const width1 = width + 1; - let points = new Uint8Array(width1 * (height + 1)); - let i, j, j0; - const lineSize = width + 7 & ~7; - let data = new Uint8Array(lineSize * height), - pos = 0; - for (const elem of imgData.data) { - let mask = 128; - while (mask > 0) { - data[pos++] = elem & mask ? 0 : 255; - mask >>= 1; - } - } - let count = 0; - pos = 0; - if (data[pos] !== 0) { - points[0] = 1; - ++count; - } - for (j = 1; j < width; j++) { - if (data[pos] !== data[pos + 1]) { - points[j] = data[pos] ? 2 : 1; - ++count; - } - pos++; - } - if (data[pos] !== 0) { - points[j] = 2; - ++count; - } - for (i = 1; i < height; i++) { - pos = i * lineSize; - j0 = i * width1; - if (data[pos - lineSize] !== data[pos]) { - points[j0] = data[pos] ? 1 : 8; - ++count; - } - let sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0); - for (j = 1; j < width; j++) { - sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0); - if (POINT_TYPES[sum]) { - points[j0 + j] = POINT_TYPES[sum]; - ++count; - } - pos++; - } - if (data[pos - lineSize] !== data[pos]) { - points[j0 + j] = data[pos] ? 2 : 4; - ++count; - } - if (count > POINT_TO_PROCESS_LIMIT) { - return null; - } - } - pos = lineSize * (height - 1); - j0 = i * width1; - if (data[pos] !== 0) { - points[j0] = 8; - ++count; - } - for (j = 1; j < width; j++) { - if (data[pos] !== data[pos + 1]) { - points[j0 + j] = data[pos] ? 4 : 8; - ++count; - } - pos++; - } - if (data[pos] !== 0) { - points[j0 + j] = 4; - ++count; - } - if (count > POINT_TO_PROCESS_LIMIT) { - return null; - } - const steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]); - const path = new Path2D(); - for (i = 0; count && i <= height; i++) { - let p = i * width1; - const end = p + width; - while (p < end && !points[p]) { - p++; - } - if (p === end) { - continue; - } - path.moveTo(p % width1, i); - const p0 = p; - let type = points[p]; - do { - const step = steps[type]; - do { - p += step; - } while (!points[p]); - const pp = points[p]; - if (pp !== 5 && pp !== 10) { - type = pp; - points[p] = 0; - } else { - type = pp & 0x33 * type >> 4; - points[p] &= type >> 2 | type << 2; - } - path.lineTo(p % width1, p / width1 | 0); - if (!points[p]) { - --count; - } - } while (p0 !== p); - --i; - } - data = null; - points = null; - const drawOutline = function (c) { - c.save(); - c.scale(1 / width, -1 / height); - c.translate(0, -height); - c.fill(path); - c.beginPath(); - c.restore(); - }; - return drawOutline; -} -class CanvasExtraState { - constructor(width, height) { - this.alphaIsShape = false; - this.fontSize = 0; - this.fontSizeScale = 1; - this.textMatrix = _util.IDENTITY_MATRIX; - this.textMatrixScale = 1; - this.fontMatrix = _util.FONT_IDENTITY_MATRIX; - this.leading = 0; - this.x = 0; - this.y = 0; - this.lineX = 0; - this.lineY = 0; - this.charSpacing = 0; - this.wordSpacing = 0; - this.textHScale = 1; - this.textRenderingMode = _util.TextRenderingMode.FILL; - this.textRise = 0; - this.fillColor = "#000000"; - this.strokeColor = "#000000"; - this.patternFill = false; - this.fillAlpha = 1; - this.strokeAlpha = 1; - this.lineWidth = 1; - this.activeSMask = null; - this.transferMaps = "none"; - this.startNewPathAndClipBox([0, 0, width, height]); - } - clone() { - const clone = Object.create(this); - clone.clipBox = this.clipBox.slice(); - return clone; - } - setCurrentPoint(x, y) { - this.x = x; - this.y = y; - } - updatePathMinMax(transform, x, y) { - [x, y] = _util.Util.applyTransform([x, y], transform); - this.minX = Math.min(this.minX, x); - this.minY = Math.min(this.minY, y); - this.maxX = Math.max(this.maxX, x); - this.maxY = Math.max(this.maxY, y); - } - updateRectMinMax(transform, rect) { - const p1 = _util.Util.applyTransform(rect, transform); - const p2 = _util.Util.applyTransform(rect.slice(2), transform); - this.minX = Math.min(this.minX, p1[0], p2[0]); - this.minY = Math.min(this.minY, p1[1], p2[1]); - this.maxX = Math.max(this.maxX, p1[0], p2[0]); - this.maxY = Math.max(this.maxY, p1[1], p2[1]); - } - updateScalingPathMinMax(transform, minMax) { - _util.Util.scaleMinMax(transform, minMax); - this.minX = Math.min(this.minX, minMax[0]); - this.maxX = Math.max(this.maxX, minMax[1]); - this.minY = Math.min(this.minY, minMax[2]); - this.maxY = Math.max(this.maxY, minMax[3]); - } - updateCurvePathMinMax(transform, x0, y0, x1, y1, x2, y2, x3, y3, minMax) { - const box = _util.Util.bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3); - if (minMax) { - minMax[0] = Math.min(minMax[0], box[0], box[2]); - minMax[1] = Math.max(minMax[1], box[0], box[2]); - minMax[2] = Math.min(minMax[2], box[1], box[3]); - minMax[3] = Math.max(minMax[3], box[1], box[3]); - return; - } - this.updateRectMinMax(transform, box); - } - getPathBoundingBox(pathType = _pattern_helper.PathType.FILL, transform = null) { - const box = [this.minX, this.minY, this.maxX, this.maxY]; - if (pathType === _pattern_helper.PathType.STROKE) { - if (!transform) { - (0, _util.unreachable)("Stroke bounding box must include transform."); - } - const scale = _util.Util.singularValueDecompose2dScale(transform); - const xStrokePad = scale[0] * this.lineWidth / 2; - const yStrokePad = scale[1] * this.lineWidth / 2; - box[0] -= xStrokePad; - box[1] -= yStrokePad; - box[2] += xStrokePad; - box[3] += yStrokePad; - } - return box; - } - updateClipFromPath() { - const intersect = _util.Util.intersect(this.clipBox, this.getPathBoundingBox()); - this.startNewPathAndClipBox(intersect || [0, 0, 0, 0]); - } - isEmptyClip() { - return this.minX === Infinity; - } - startNewPathAndClipBox(box) { - this.clipBox = box; - this.minX = Infinity; - this.minY = Infinity; - this.maxX = 0; - this.maxY = 0; - } - getClippedPathBoundingBox(pathType = _pattern_helper.PathType.FILL, transform = null) { - return _util.Util.intersect(this.clipBox, this.getPathBoundingBox(pathType, transform)); - } -} -function putBinaryImageData(ctx, imgData) { - if (typeof ImageData !== "undefined" && imgData instanceof ImageData) { - ctx.putImageData(imgData, 0, 0); - return; - } - const height = imgData.height, - width = imgData.width; - const partialChunkHeight = height % FULL_CHUNK_HEIGHT; - const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT; - const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1; - const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT); - let srcPos = 0, - destPos; - const src = imgData.data; - const dest = chunkImgData.data; - let i, j, thisChunkHeight, elemsInThisChunk; - if (imgData.kind === _util.ImageKind.GRAYSCALE_1BPP) { - const srcLength = src.byteLength; - const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2); - const dest32DataLength = dest32.length; - const fullSrcDiff = width + 7 >> 3; - const white = 0xffffffff; - const black = _util.FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff; - for (i = 0; i < totalChunks; i++) { - thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight; - destPos = 0; - for (j = 0; j < thisChunkHeight; j++) { - const srcDiff = srcLength - srcPos; - let k = 0; - const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7; - const kEndUnrolled = kEnd & ~7; - let mask = 0; - let srcByte = 0; - for (; k < kEndUnrolled; k += 8) { - srcByte = src[srcPos++]; - dest32[destPos++] = srcByte & 128 ? white : black; - dest32[destPos++] = srcByte & 64 ? white : black; - dest32[destPos++] = srcByte & 32 ? white : black; - dest32[destPos++] = srcByte & 16 ? white : black; - dest32[destPos++] = srcByte & 8 ? white : black; - dest32[destPos++] = srcByte & 4 ? white : black; - dest32[destPos++] = srcByte & 2 ? white : black; - dest32[destPos++] = srcByte & 1 ? white : black; - } - for (; k < kEnd; k++) { - if (mask === 0) { - srcByte = src[srcPos++]; - mask = 128; - } - dest32[destPos++] = srcByte & mask ? white : black; - mask >>= 1; - } - } - while (destPos < dest32DataLength) { - dest32[destPos++] = 0; - } - ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); - } - } else if (imgData.kind === _util.ImageKind.RGBA_32BPP) { - j = 0; - elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4; - for (i = 0; i < fullChunks; i++) { - dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk)); - srcPos += elemsInThisChunk; - ctx.putImageData(chunkImgData, 0, j); - j += FULL_CHUNK_HEIGHT; - } - if (i < totalChunks) { - elemsInThisChunk = width * partialChunkHeight * 4; - dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk)); - ctx.putImageData(chunkImgData, 0, j); - } - } else if (imgData.kind === _util.ImageKind.RGB_24BPP) { - thisChunkHeight = FULL_CHUNK_HEIGHT; - elemsInThisChunk = width * thisChunkHeight; - for (i = 0; i < totalChunks; i++) { - if (i >= fullChunks) { - thisChunkHeight = partialChunkHeight; - elemsInThisChunk = width * thisChunkHeight; - } - destPos = 0; - for (j = elemsInThisChunk; j--;) { - dest[destPos++] = src[srcPos++]; - dest[destPos++] = src[srcPos++]; - dest[destPos++] = src[srcPos++]; - dest[destPos++] = 255; - } - ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); - } - } else { - throw new Error(`bad image kind: ${imgData.kind}`); - } -} -function putBinaryImageMask(ctx, imgData) { - if (imgData.bitmap) { - ctx.drawImage(imgData.bitmap, 0, 0); - return; - } - const height = imgData.height, - width = imgData.width; - const partialChunkHeight = height % FULL_CHUNK_HEIGHT; - const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT; - const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1; - const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT); - let srcPos = 0; - const src = imgData.data; - const dest = chunkImgData.data; - for (let i = 0; i < totalChunks; i++) { - const thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight; - ({ - srcPos - } = (0, _image_utils.convertBlackAndWhiteToRGBA)({ - src, - srcPos, - dest, - width, - height: thisChunkHeight, - nonBlackColor: 0 +if (isNodeJS) { + var packageCapability = Promise.withResolvers(); + var packageMap = null; + const loadPackages = async () => { + const fs = await import( /*webpackIgnore: true*/"fs"), + http = await import( /*webpackIgnore: true*/"http"), + https = await import( /*webpackIgnore: true*/"https"), + url = await import( /*webpackIgnore: true*/"url"); + let canvas, path2d; + return new Map(Object.entries({ + fs, + http, + https, + url, + canvas, + path2d })); - ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); + }; + loadPackages().then(map => { + packageMap = map; + packageCapability.resolve(); + }, reason => { + warn(`loadPackages: ${reason}`); + packageMap = new Map(); + packageCapability.resolve(); + }); +} +class NodePackages { + static get promise() { + return packageCapability.promise; + } + static get(name) { + return packageMap?.get(name); } } -function copyCtxState(sourceCtx, destCtx) { - const properties = ["strokeStyle", "fillStyle", "fillRule", "globalAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "globalCompositeOperation", "font", "filter"]; - for (const property of properties) { - if (sourceCtx[property] !== undefined) { - destCtx[property] = sourceCtx[property]; - } - } - if (sourceCtx.setLineDash !== undefined) { - destCtx.setLineDash(sourceCtx.getLineDash()); - destCtx.lineDashOffset = sourceCtx.lineDashOffset; +const node_utils_fetchData = function (url) { + const fs = NodePackages.get("fs"); + return fs.promises.readFile(url).then(data => new Uint8Array(data)); +}; +class NodeFilterFactory extends BaseFilterFactory {} +class NodeCanvasFactory extends BaseCanvasFactory { + _createCanvas(width, height) { + const canvas = NodePackages.get("canvas"); + return canvas.createCanvas(width, height); } } -function resetCtxToDefault(ctx) { - ctx.strokeStyle = ctx.fillStyle = "#000000"; - ctx.fillRule = "nonzero"; - ctx.globalAlpha = 1; - ctx.lineWidth = 1; - ctx.lineCap = "butt"; - ctx.lineJoin = "miter"; - ctx.miterLimit = 10; - ctx.globalCompositeOperation = "source-over"; - ctx.font = "10px sans-serif"; - if (ctx.setLineDash !== undefined) { - ctx.setLineDash([]); - ctx.lineDashOffset = 0; - } - if (!_util.isNodeJS) { - const { - filter - } = ctx; - if (filter !== "none" && filter !== "") { - ctx.filter = "none"; - } +class NodeCMapReaderFactory extends BaseCMapReaderFactory { + _fetchData(url, compressionType) { + return node_utils_fetchData(url).then(data => ({ + cMapData: data, + compressionType + })); } } -function composeSMaskBackdrop(bytes, r0, g0, b0) { - const length = bytes.length; - for (let i = 3; i < length; i += 4) { - const alpha = bytes[i]; - if (alpha === 0) { - bytes[i - 3] = r0; - bytes[i - 2] = g0; - bytes[i - 1] = b0; - } else if (alpha < 255) { - const alpha_ = 255 - alpha; - bytes[i - 3] = bytes[i - 3] * alpha + r0 * alpha_ >> 8; - bytes[i - 2] = bytes[i - 2] * alpha + g0 * alpha_ >> 8; - bytes[i - 1] = bytes[i - 1] * alpha + b0 * alpha_ >> 8; - } - } -} -function composeSMaskAlpha(maskData, layerData, transferMap) { - const length = maskData.length; - const scale = 1 / 255; - for (let i = 3; i < length; i += 4) { - const alpha = transferMap ? transferMap[maskData[i]] : maskData[i]; - layerData[i] = layerData[i] * alpha * scale | 0; - } -} -function composeSMaskLuminosity(maskData, layerData, transferMap) { - const length = maskData.length; - for (let i = 3; i < length; i += 4) { - const y = maskData[i - 3] * 77 + maskData[i - 2] * 152 + maskData[i - 1] * 28; - layerData[i] = transferMap ? layerData[i] * transferMap[y >> 8] >> 8 : layerData[i] * y >> 16; - } -} -function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap, layerOffsetX, layerOffsetY, maskOffsetX, maskOffsetY) { - const hasBackdrop = !!backdrop; - const r0 = hasBackdrop ? backdrop[0] : 0; - const g0 = hasBackdrop ? backdrop[1] : 0; - const b0 = hasBackdrop ? backdrop[2] : 0; - const composeFn = subtype === "Luminosity" ? composeSMaskLuminosity : composeSMaskAlpha; - const PIXELS_TO_PROCESS = 1048576; - const chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width)); - for (let row = 0; row < height; row += chunkSize) { - const chunkHeight = Math.min(chunkSize, height - row); - const maskData = maskCtx.getImageData(layerOffsetX - maskOffsetX, row + (layerOffsetY - maskOffsetY), width, chunkHeight); - const layerData = layerCtx.getImageData(layerOffsetX, row + layerOffsetY, width, chunkHeight); - if (hasBackdrop) { - composeSMaskBackdrop(maskData.data, r0, g0, b0); - } - composeFn(maskData.data, layerData.data, transferMap); - layerCtx.putImageData(layerData, layerOffsetX, row + layerOffsetY); - } -} -function composeSMask(ctx, smask, layerCtx, layerBox) { - const layerOffsetX = layerBox[0]; - const layerOffsetY = layerBox[1]; - const layerWidth = layerBox[2] - layerOffsetX; - const layerHeight = layerBox[3] - layerOffsetY; - if (layerWidth === 0 || layerHeight === 0) { - return; - } - genericComposeSMask(smask.context, layerCtx, layerWidth, layerHeight, smask.subtype, smask.backdrop, smask.transferMap, layerOffsetX, layerOffsetY, smask.offsetX, smask.offsetY); - ctx.save(); - ctx.globalAlpha = 1; - ctx.globalCompositeOperation = "source-over"; - ctx.setTransform(1, 0, 0, 1, 0, 0); - ctx.drawImage(layerCtx.canvas, 0, 0); - ctx.restore(); -} -function getImageSmoothingEnabled(transform, interpolate) { - const scale = _util.Util.singularValueDecompose2dScale(transform); - scale[0] = Math.fround(scale[0]); - scale[1] = Math.fround(scale[1]); - const actualScale = Math.fround((globalThis.devicePixelRatio || 1) * _display_utils.PixelsPerInch.PDF_TO_CSS_UNITS); - if (interpolate !== undefined) { - return interpolate; - } else if (scale[0] <= actualScale || scale[1] <= actualScale) { - return true; - } - return false; -} -const LINE_CAP_STYLES = ["butt", "round", "square"]; -const LINE_JOIN_STYLES = ["miter", "round", "bevel"]; -const NORMAL_CLIP = {}; -const EO_CLIP = {}; -class CanvasGraphics { - constructor(canvasCtx, commonObjs, objs, canvasFactory, filterFactory, { - optionalContentConfig, - markedContentStack = null - }, annotationCanvasMap, pageColors) { - this.ctx = canvasCtx; - this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height); - this.stateStack = []; - this.pendingClip = null; - this.pendingEOFill = false; - this.res = null; - this.xobjs = null; - this.commonObjs = commonObjs; - this.objs = objs; - this.canvasFactory = canvasFactory; - this.filterFactory = filterFactory; - this.groupStack = []; - this.processingType3 = null; - this.baseTransform = null; - this.baseTransformStack = []; - this.groupLevel = 0; - this.smaskStack = []; - this.smaskCounter = 0; - this.tempSMask = null; - this.suspendedCtx = null; - this.contentVisible = true; - this.markedContentStack = markedContentStack || []; - this.optionalContentConfig = optionalContentConfig; - this.cachedCanvases = new CachedCanvases(this.canvasFactory); - this.cachedPatterns = new Map(); - this.annotationCanvasMap = annotationCanvasMap; - this.viewportScale = 1; - this.outputScaleX = 1; - this.outputScaleY = 1; - this.pageColors = pageColors; - this._cachedScaleForStroking = [-1, 0]; - this._cachedGetSinglePixelWidth = null; - this._cachedBitmapsMap = new Map(); - } - getObject(data, fallback = null) { - if (typeof data === "string") { - return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data); - } - return fallback; - } - beginDrawing({ - transform, - viewport, - transparency = false, - background = null - }) { - const width = this.ctx.canvas.width; - const height = this.ctx.canvas.height; - const savedFillStyle = this.ctx.fillStyle; - this.ctx.fillStyle = background || "#ffffff"; - this.ctx.fillRect(0, 0, width, height); - this.ctx.fillStyle = savedFillStyle; - if (transparency) { - const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height); - this.compositeCtx = this.ctx; - this.transparentCanvas = transparentCanvas.canvas; - this.ctx = transparentCanvas.context; - this.ctx.save(); - this.ctx.transform(...(0, _display_utils.getCurrentTransform)(this.compositeCtx)); - } - this.ctx.save(); - resetCtxToDefault(this.ctx); - if (transform) { - this.ctx.transform(...transform); - this.outputScaleX = transform[0]; - this.outputScaleY = transform[0]; - } - this.ctx.transform(...viewport.transform); - this.viewportScale = viewport.scale; - this.baseTransform = (0, _display_utils.getCurrentTransform)(this.ctx); - } - executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) { - const argsArray = operatorList.argsArray; - const fnArray = operatorList.fnArray; - let i = executionStartIdx || 0; - const argsArrayLen = argsArray.length; - if (argsArrayLen === i) { - return i; - } - const chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === "function"; - const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0; - let steps = 0; - const commonObjs = this.commonObjs; - const objs = this.objs; - let fnId; - while (true) { - if (stepper !== undefined && i === stepper.nextBreakPoint) { - stepper.breakIt(i, continueCallback); - return i; - } - fnId = fnArray[i]; - if (fnId !== _util.OPS.dependency) { - this[fnId].apply(this, argsArray[i]); - } else { - for (const depObjId of argsArray[i]) { - const objsPool = depObjId.startsWith("g_") ? commonObjs : objs; - if (!objsPool.has(depObjId)) { - objsPool.get(depObjId, continueCallback); - return i; - } - } - } - i++; - if (i === argsArrayLen) { - return i; - } - if (chunkOperations && ++steps > EXECUTION_STEPS) { - if (Date.now() > endTime) { - continueCallback(); - return i; - } - steps = 0; - } - } - } - #restoreInitialState() { - while (this.stateStack.length || this.inSMaskMode) { - this.restore(); - } - this.ctx.restore(); - if (this.transparentCanvas) { - this.ctx = this.compositeCtx; - this.ctx.save(); - this.ctx.setTransform(1, 0, 0, 1, 0, 0); - this.ctx.drawImage(this.transparentCanvas, 0, 0); - this.ctx.restore(); - this.transparentCanvas = null; - } - } - endDrawing() { - this.#restoreInitialState(); - this.cachedCanvases.clear(); - this.cachedPatterns.clear(); - for (const cache of this._cachedBitmapsMap.values()) { - for (const canvas of cache.values()) { - if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) { - canvas.width = canvas.height = 0; - } - } - cache.clear(); - } - this._cachedBitmapsMap.clear(); - this.#drawFilter(); - } - #drawFilter() { - if (this.pageColors) { - const hcmFilterId = this.filterFactory.addHCMFilter(this.pageColors.foreground, this.pageColors.background); - if (hcmFilterId !== "none") { - const savedFilter = this.ctx.filter; - this.ctx.filter = hcmFilterId; - this.ctx.drawImage(this.ctx.canvas, 0, 0); - this.ctx.filter = savedFilter; - } - } - } - _scaleImage(img, inverseTransform) { - const width = img.width; - const height = img.height; - let widthScale = Math.max(Math.hypot(inverseTransform[0], inverseTransform[1]), 1); - let heightScale = Math.max(Math.hypot(inverseTransform[2], inverseTransform[3]), 1); - let paintWidth = width, - paintHeight = height; - let tmpCanvasId = "prescale1"; - let tmpCanvas, tmpCtx; - while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) { - let newWidth = paintWidth, - newHeight = paintHeight; - if (widthScale > 2 && paintWidth > 1) { - newWidth = paintWidth >= 16384 ? Math.floor(paintWidth / 2) - 1 || 1 : Math.ceil(paintWidth / 2); - widthScale /= paintWidth / newWidth; - } - if (heightScale > 2 && paintHeight > 1) { - newHeight = paintHeight >= 16384 ? Math.floor(paintHeight / 2) - 1 || 1 : Math.ceil(paintHeight) / 2; - heightScale /= paintHeight / newHeight; - } - tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight); - tmpCtx = tmpCanvas.context; - tmpCtx.clearRect(0, 0, newWidth, newHeight); - tmpCtx.drawImage(img, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight); - img = tmpCanvas.canvas; - paintWidth = newWidth; - paintHeight = newHeight; - tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1"; - } - return { - img, - paintWidth, - paintHeight - }; - } - _createMaskCanvas(img) { - const ctx = this.ctx; - const { - width, - height - } = img; - const fillColor = this.current.fillColor; - const isPatternFill = this.current.patternFill; - const currentTransform = (0, _display_utils.getCurrentTransform)(ctx); - let cache, cacheKey, scaled, maskCanvas; - if ((img.bitmap || img.data) && img.count > 1) { - const mainKey = img.bitmap || img.data.buffer; - cacheKey = JSON.stringify(isPatternFill ? currentTransform : [currentTransform.slice(0, 4), fillColor]); - cache = this._cachedBitmapsMap.get(mainKey); - if (!cache) { - cache = new Map(); - this._cachedBitmapsMap.set(mainKey, cache); - } - const cachedImage = cache.get(cacheKey); - if (cachedImage && !isPatternFill) { - const offsetX = Math.round(Math.min(currentTransform[0], currentTransform[2]) + currentTransform[4]); - const offsetY = Math.round(Math.min(currentTransform[1], currentTransform[3]) + currentTransform[5]); - return { - canvas: cachedImage, - offsetX, - offsetY - }; - } - scaled = cachedImage; - } - if (!scaled) { - maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height); - putBinaryImageMask(maskCanvas.context, img); - } - let maskToCanvas = _util.Util.transform(currentTransform, [1 / width, 0, 0, -1 / height, 0, 0]); - maskToCanvas = _util.Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]); - const cord1 = _util.Util.applyTransform([0, 0], maskToCanvas); - const cord2 = _util.Util.applyTransform([width, height], maskToCanvas); - const rect = _util.Util.normalizeRect([cord1[0], cord1[1], cord2[0], cord2[1]]); - const drawnWidth = Math.round(rect[2] - rect[0]) || 1; - const drawnHeight = Math.round(rect[3] - rect[1]) || 1; - const fillCanvas = this.cachedCanvases.getCanvas("fillCanvas", drawnWidth, drawnHeight); - const fillCtx = fillCanvas.context; - const offsetX = Math.min(cord1[0], cord2[0]); - const offsetY = Math.min(cord1[1], cord2[1]); - fillCtx.translate(-offsetX, -offsetY); - fillCtx.transform(...maskToCanvas); - if (!scaled) { - scaled = this._scaleImage(maskCanvas.canvas, (0, _display_utils.getCurrentTransformInverse)(fillCtx)); - scaled = scaled.img; - if (cache && isPatternFill) { - cache.set(cacheKey, scaled); - } - } - fillCtx.imageSmoothingEnabled = getImageSmoothingEnabled((0, _display_utils.getCurrentTransform)(fillCtx), img.interpolate); - drawImageAtIntegerCoords(fillCtx, scaled, 0, 0, scaled.width, scaled.height, 0, 0, width, height); - fillCtx.globalCompositeOperation = "source-in"; - const inverse = _util.Util.transform((0, _display_utils.getCurrentTransformInverse)(fillCtx), [1, 0, 0, 1, -offsetX, -offsetY]); - fillCtx.fillStyle = isPatternFill ? fillColor.getPattern(ctx, this, inverse, _pattern_helper.PathType.FILL) : fillColor; - fillCtx.fillRect(0, 0, width, height); - if (cache && !isPatternFill) { - this.cachedCanvases.delete("fillCanvas"); - cache.set(cacheKey, fillCanvas.canvas); - } - return { - canvas: fillCanvas.canvas, - offsetX: Math.round(offsetX), - offsetY: Math.round(offsetY) - }; - } - setLineWidth(width) { - if (width !== this.current.lineWidth) { - this._cachedScaleForStroking[0] = -1; - } - this.current.lineWidth = width; - this.ctx.lineWidth = width; - } - setLineCap(style) { - this.ctx.lineCap = LINE_CAP_STYLES[style]; - } - setLineJoin(style) { - this.ctx.lineJoin = LINE_JOIN_STYLES[style]; - } - setMiterLimit(limit) { - this.ctx.miterLimit = limit; - } - setDash(dashArray, dashPhase) { - const ctx = this.ctx; - if (ctx.setLineDash !== undefined) { - ctx.setLineDash(dashArray); - ctx.lineDashOffset = dashPhase; - } - } - setRenderingIntent(intent) {} - setFlatness(flatness) {} - setGState(states) { - for (const [key, value] of states) { - switch (key) { - case "LW": - this.setLineWidth(value); - break; - case "LC": - this.setLineCap(value); - break; - case "LJ": - this.setLineJoin(value); - break; - case "ML": - this.setMiterLimit(value); - break; - case "D": - this.setDash(value[0], value[1]); - break; - case "RI": - this.setRenderingIntent(value); - break; - case "FL": - this.setFlatness(value); - break; - case "Font": - this.setFont(value[0], value[1]); - break; - case "CA": - this.current.strokeAlpha = value; - break; - case "ca": - this.current.fillAlpha = value; - this.ctx.globalAlpha = value; - break; - case "BM": - this.ctx.globalCompositeOperation = value; - break; - case "SMask": - this.current.activeSMask = value ? this.tempSMask : null; - this.tempSMask = null; - this.checkSMaskState(); - break; - case "TR": - this.ctx.filter = this.current.transferMaps = this.filterFactory.addFilter(value); - break; - } - } - } - get inSMaskMode() { - return !!this.suspendedCtx; - } - checkSMaskState() { - const inSMaskMode = this.inSMaskMode; - if (this.current.activeSMask && !inSMaskMode) { - this.beginSMaskMode(); - } else if (!this.current.activeSMask && inSMaskMode) { - this.endSMaskMode(); - } - } - beginSMaskMode() { - if (this.inSMaskMode) { - throw new Error("beginSMaskMode called while already in smask mode"); - } - const drawnWidth = this.ctx.canvas.width; - const drawnHeight = this.ctx.canvas.height; - const cacheId = "smaskGroupAt" + this.groupLevel; - const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight); - this.suspendedCtx = this.ctx; - this.ctx = scratchCanvas.context; - const ctx = this.ctx; - ctx.setTransform(...(0, _display_utils.getCurrentTransform)(this.suspendedCtx)); - copyCtxState(this.suspendedCtx, ctx); - mirrorContextOperations(ctx, this.suspendedCtx); - this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]); - } - endSMaskMode() { - if (!this.inSMaskMode) { - throw new Error("endSMaskMode called while not in smask mode"); - } - this.ctx._removeMirroring(); - copyCtxState(this.ctx, this.suspendedCtx); - this.ctx = this.suspendedCtx; - this.suspendedCtx = null; - } - compose(dirtyBox) { - if (!this.current.activeSMask) { - return; - } - if (!dirtyBox) { - dirtyBox = [0, 0, this.ctx.canvas.width, this.ctx.canvas.height]; - } else { - dirtyBox[0] = Math.floor(dirtyBox[0]); - dirtyBox[1] = Math.floor(dirtyBox[1]); - dirtyBox[2] = Math.ceil(dirtyBox[2]); - dirtyBox[3] = Math.ceil(dirtyBox[3]); - } - const smask = this.current.activeSMask; - const suspendedCtx = this.suspendedCtx; - composeSMask(suspendedCtx, smask, this.ctx, dirtyBox); - this.ctx.save(); - this.ctx.setTransform(1, 0, 0, 1, 0, 0); - this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height); - this.ctx.restore(); - } - save() { - if (this.inSMaskMode) { - copyCtxState(this.ctx, this.suspendedCtx); - this.suspendedCtx.save(); - } else { - this.ctx.save(); - } - const old = this.current; - this.stateStack.push(old); - this.current = old.clone(); - } - restore() { - if (this.stateStack.length === 0 && this.inSMaskMode) { - this.endSMaskMode(); - } - if (this.stateStack.length !== 0) { - this.current = this.stateStack.pop(); - if (this.inSMaskMode) { - this.suspendedCtx.restore(); - copyCtxState(this.suspendedCtx, this.ctx); - } else { - this.ctx.restore(); - } - this.checkSMaskState(); - this.pendingClip = null; - this._cachedScaleForStroking[0] = -1; - this._cachedGetSinglePixelWidth = null; - } - } - transform(a, b, c, d, e, f) { - this.ctx.transform(a, b, c, d, e, f); - this._cachedScaleForStroking[0] = -1; - this._cachedGetSinglePixelWidth = null; - } - constructPath(ops, args, minMax) { - const ctx = this.ctx; - const current = this.current; - let x = current.x, - y = current.y; - let startX, startY; - const currentTransform = (0, _display_utils.getCurrentTransform)(ctx); - const isScalingMatrix = currentTransform[0] === 0 && currentTransform[3] === 0 || currentTransform[1] === 0 && currentTransform[2] === 0; - const minMaxForBezier = isScalingMatrix ? minMax.slice(0) : null; - for (let i = 0, j = 0, ii = ops.length; i < ii; i++) { - switch (ops[i] | 0) { - case _util.OPS.rectangle: - x = args[j++]; - y = args[j++]; - const width = args[j++]; - const height = args[j++]; - const xw = x + width; - const yh = y + height; - ctx.moveTo(x, y); - if (width === 0 || height === 0) { - ctx.lineTo(xw, yh); - } else { - ctx.lineTo(xw, y); - ctx.lineTo(xw, yh); - ctx.lineTo(x, yh); - } - if (!isScalingMatrix) { - current.updateRectMinMax(currentTransform, [x, y, xw, yh]); - } - ctx.closePath(); - break; - case _util.OPS.moveTo: - x = args[j++]; - y = args[j++]; - ctx.moveTo(x, y); - if (!isScalingMatrix) { - current.updatePathMinMax(currentTransform, x, y); - } - break; - case _util.OPS.lineTo: - x = args[j++]; - y = args[j++]; - ctx.lineTo(x, y); - if (!isScalingMatrix) { - current.updatePathMinMax(currentTransform, x, y); - } - break; - case _util.OPS.curveTo: - startX = x; - startY = y; - x = args[j + 4]; - y = args[j + 5]; - ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y); - current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], args[j + 2], args[j + 3], x, y, minMaxForBezier); - j += 6; - break; - case _util.OPS.curveTo2: - startX = x; - startY = y; - ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]); - current.updateCurvePathMinMax(currentTransform, startX, startY, x, y, args[j], args[j + 1], args[j + 2], args[j + 3], minMaxForBezier); - x = args[j + 2]; - y = args[j + 3]; - j += 4; - break; - case _util.OPS.curveTo3: - startX = x; - startY = y; - x = args[j + 2]; - y = args[j + 3]; - ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y); - current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], x, y, x, y, minMaxForBezier); - j += 4; - break; - case _util.OPS.closePath: - ctx.closePath(); - break; - } - } - if (isScalingMatrix) { - current.updateScalingPathMinMax(currentTransform, minMaxForBezier); - } - current.setCurrentPoint(x, y); - } - closePath() { - this.ctx.closePath(); - } - stroke(consumePath = true) { - const ctx = this.ctx; - const strokeColor = this.current.strokeColor; - ctx.globalAlpha = this.current.strokeAlpha; - if (this.contentVisible) { - if (typeof strokeColor === "object" && strokeColor?.getPattern) { - ctx.save(); - ctx.strokeStyle = strokeColor.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.STROKE); - this.rescaleAndStroke(false); - ctx.restore(); - } else { - this.rescaleAndStroke(true); - } - } - if (consumePath) { - this.consumePath(this.current.getClippedPathBoundingBox()); - } - ctx.globalAlpha = this.current.fillAlpha; - } - closeStroke() { - this.closePath(); - this.stroke(); - } - fill(consumePath = true) { - const ctx = this.ctx; - const fillColor = this.current.fillColor; - const isPatternFill = this.current.patternFill; - let needRestore = false; - if (isPatternFill) { - ctx.save(); - ctx.fillStyle = fillColor.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.FILL); - needRestore = true; - } - const intersect = this.current.getClippedPathBoundingBox(); - if (this.contentVisible && intersect !== null) { - if (this.pendingEOFill) { - ctx.fill("evenodd"); - this.pendingEOFill = false; - } else { - ctx.fill(); - } - } - if (needRestore) { - ctx.restore(); - } - if (consumePath) { - this.consumePath(intersect); - } - } - eoFill() { - this.pendingEOFill = true; - this.fill(); - } - fillStroke() { - this.fill(false); - this.stroke(false); - this.consumePath(); - } - eoFillStroke() { - this.pendingEOFill = true; - this.fillStroke(); - } - closeFillStroke() { - this.closePath(); - this.fillStroke(); - } - closeEOFillStroke() { - this.pendingEOFill = true; - this.closePath(); - this.fillStroke(); - } - endPath() { - this.consumePath(); - } - clip() { - this.pendingClip = NORMAL_CLIP; - } - eoClip() { - this.pendingClip = EO_CLIP; - } - beginText() { - this.current.textMatrix = _util.IDENTITY_MATRIX; - this.current.textMatrixScale = 1; - this.current.x = this.current.lineX = 0; - this.current.y = this.current.lineY = 0; - } - endText() { - const paths = this.pendingTextPaths; - const ctx = this.ctx; - if (paths === undefined) { - ctx.beginPath(); - return; - } - ctx.save(); - ctx.beginPath(); - for (const path of paths) { - ctx.setTransform(...path.transform); - ctx.translate(path.x, path.y); - path.addToPath(ctx, path.fontSize); - } - ctx.restore(); - ctx.clip(); - ctx.beginPath(); - delete this.pendingTextPaths; - } - setCharSpacing(spacing) { - this.current.charSpacing = spacing; - } - setWordSpacing(spacing) { - this.current.wordSpacing = spacing; - } - setHScale(scale) { - this.current.textHScale = scale / 100; - } - setLeading(leading) { - this.current.leading = -leading; - } - setFont(fontRefName, size) { - const fontObj = this.commonObjs.get(fontRefName); - const current = this.current; - if (!fontObj) { - throw new Error(`Can't find font for ${fontRefName}`); - } - current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX; - if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) { - (0, _util.warn)("Invalid font matrix for font " + fontRefName); - } - if (size < 0) { - size = -size; - current.fontDirection = -1; - } else { - current.fontDirection = 1; - } - this.current.font = fontObj; - this.current.fontSize = size; - if (fontObj.isType3Font) { - return; - } - const name = fontObj.loadedName || "sans-serif"; - const typeface = fontObj.systemFontInfo?.css || `"${name}", ${fontObj.fallbackName}`; - let bold = "normal"; - if (fontObj.black) { - bold = "900"; - } else if (fontObj.bold) { - bold = "bold"; - } - const italic = fontObj.italic ? "italic" : "normal"; - let browserFontSize = size; - if (size < MIN_FONT_SIZE) { - browserFontSize = MIN_FONT_SIZE; - } else if (size > MAX_FONT_SIZE) { - browserFontSize = MAX_FONT_SIZE; - } - this.current.fontSizeScale = size / browserFontSize; - this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`; - } - setTextRenderingMode(mode) { - this.current.textRenderingMode = mode; - } - setTextRise(rise) { - this.current.textRise = rise; - } - moveText(x, y) { - this.current.x = this.current.lineX += x; - this.current.y = this.current.lineY += y; - } - setLeadingMoveText(x, y) { - this.setLeading(-y); - this.moveText(x, y); - } - setTextMatrix(a, b, c, d, e, f) { - this.current.textMatrix = [a, b, c, d, e, f]; - this.current.textMatrixScale = Math.hypot(a, b); - this.current.x = this.current.lineX = 0; - this.current.y = this.current.lineY = 0; - } - nextLine() { - this.moveText(0, this.current.leading); - } - paintChar(character, x, y, patternTransform) { - const ctx = this.ctx; - const current = this.current; - const font = current.font; - const textRenderingMode = current.textRenderingMode; - const fontSize = current.fontSize / current.fontSizeScale; - const fillStrokeMode = textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK; - const isAddToPathSet = !!(textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG); - const patternFill = current.patternFill && !font.missingFile; - let addToPath; - if (font.disableFontFace || isAddToPathSet || patternFill) { - addToPath = font.getPathGenerator(this.commonObjs, character); - } - if (font.disableFontFace || patternFill) { - ctx.save(); - ctx.translate(x, y); - ctx.beginPath(); - addToPath(ctx, fontSize); - if (patternTransform) { - ctx.setTransform(...patternTransform); - } - if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) { - ctx.fill(); - } - if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) { - ctx.stroke(); - } - ctx.restore(); - } else { - if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) { - ctx.fillText(character, x, y); - } - if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) { - ctx.strokeText(character, x, y); - } - } - if (isAddToPathSet) { - const paths = this.pendingTextPaths ||= []; - paths.push({ - transform: (0, _display_utils.getCurrentTransform)(ctx), - x, - y, - fontSize, - addToPath - }); - } - } - get isFontSubpixelAAEnabled() { - const { - context: ctx - } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10); - ctx.scale(1.5, 1); - ctx.fillText("I", 0, 10); - const data = ctx.getImageData(0, 0, 10, 10).data; - let enabled = false; - for (let i = 3; i < data.length; i += 4) { - if (data[i] > 0 && data[i] < 255) { - enabled = true; - break; - } - } - return (0, _util.shadow)(this, "isFontSubpixelAAEnabled", enabled); - } - showText(glyphs) { - const current = this.current; - const font = current.font; - if (font.isType3Font) { - return this.showType3Text(glyphs); - } - const fontSize = current.fontSize; - if (fontSize === 0) { - return undefined; - } - const ctx = this.ctx; - const fontSizeScale = current.fontSizeScale; - const charSpacing = current.charSpacing; - const wordSpacing = current.wordSpacing; - const fontDirection = current.fontDirection; - const textHScale = current.textHScale * fontDirection; - const glyphsLength = glyphs.length; - const vertical = font.vertical; - const spacingDir = vertical ? 1 : -1; - const defaultVMetrics = font.defaultVMetrics; - const widthAdvanceScale = fontSize * current.fontMatrix[0]; - const simpleFillText = current.textRenderingMode === _util.TextRenderingMode.FILL && !font.disableFontFace && !current.patternFill; - ctx.save(); - ctx.transform(...current.textMatrix); - ctx.translate(current.x, current.y + current.textRise); - if (fontDirection > 0) { - ctx.scale(textHScale, -1); - } else { - ctx.scale(textHScale, 1); - } - let patternTransform; - if (current.patternFill) { - ctx.save(); - const pattern = current.fillColor.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.FILL); - patternTransform = (0, _display_utils.getCurrentTransform)(ctx); - ctx.restore(); - ctx.fillStyle = pattern; - } - let lineWidth = current.lineWidth; - const scale = current.textMatrixScale; - if (scale === 0 || lineWidth === 0) { - const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK; - if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) { - lineWidth = this.getSinglePixelWidth(); - } - } else { - lineWidth /= scale; - } - if (fontSizeScale !== 1.0) { - ctx.scale(fontSizeScale, fontSizeScale); - lineWidth /= fontSizeScale; - } - ctx.lineWidth = lineWidth; - if (font.isInvalidPDFjsFont) { - const chars = []; - let width = 0; - for (const glyph of glyphs) { - chars.push(glyph.unicode); - width += glyph.width; - } - ctx.fillText(chars.join(""), 0, 0); - current.x += width * widthAdvanceScale * textHScale; - ctx.restore(); - this.compose(); - return undefined; - } - let x = 0, - i; - for (i = 0; i < glyphsLength; ++i) { - const glyph = glyphs[i]; - if (typeof glyph === "number") { - x += spacingDir * glyph * fontSize / 1000; - continue; - } - let restoreNeeded = false; - const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing; - const character = glyph.fontChar; - const accent = glyph.accent; - let scaledX, scaledY; - let width = glyph.width; - if (vertical) { - const vmetric = glyph.vmetric || defaultVMetrics; - const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale; - const vy = vmetric[2] * widthAdvanceScale; - width = vmetric ? -vmetric[0] : width; - scaledX = vx / fontSizeScale; - scaledY = (x + vy) / fontSizeScale; - } else { - scaledX = x / fontSizeScale; - scaledY = 0; - } - if (font.remeasure && width > 0) { - const measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale; - if (width < measuredWidth && this.isFontSubpixelAAEnabled) { - const characterScaleX = width / measuredWidth; - restoreNeeded = true; - ctx.save(); - ctx.scale(characterScaleX, 1); - scaledX /= characterScaleX; - } else if (width !== measuredWidth) { - scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale; - } - } - if (this.contentVisible && (glyph.isInFont || font.missingFile)) { - if (simpleFillText && !accent) { - ctx.fillText(character, scaledX, scaledY); - } else { - this.paintChar(character, scaledX, scaledY, patternTransform); - if (accent) { - const scaledAccentX = scaledX + fontSize * accent.offset.x / fontSizeScale; - const scaledAccentY = scaledY - fontSize * accent.offset.y / fontSizeScale; - this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY, patternTransform); - } - } - } - const charWidth = vertical ? width * widthAdvanceScale - spacing * fontDirection : width * widthAdvanceScale + spacing * fontDirection; - x += charWidth; - if (restoreNeeded) { - ctx.restore(); - } - } - if (vertical) { - current.y -= x; - } else { - current.x += x * textHScale; - } - ctx.restore(); - this.compose(); - return undefined; - } - showType3Text(glyphs) { - const ctx = this.ctx; - const current = this.current; - const font = current.font; - const fontSize = current.fontSize; - const fontDirection = current.fontDirection; - const spacingDir = font.vertical ? 1 : -1; - const charSpacing = current.charSpacing; - const wordSpacing = current.wordSpacing; - const textHScale = current.textHScale * fontDirection; - const fontMatrix = current.fontMatrix || _util.FONT_IDENTITY_MATRIX; - const glyphsLength = glyphs.length; - const isTextInvisible = current.textRenderingMode === _util.TextRenderingMode.INVISIBLE; - let i, glyph, width, spacingLength; - if (isTextInvisible || fontSize === 0) { - return; - } - this._cachedScaleForStroking[0] = -1; - this._cachedGetSinglePixelWidth = null; - ctx.save(); - ctx.transform(...current.textMatrix); - ctx.translate(current.x, current.y); - ctx.scale(textHScale, fontDirection); - for (i = 0; i < glyphsLength; ++i) { - glyph = glyphs[i]; - if (typeof glyph === "number") { - spacingLength = spacingDir * glyph * fontSize / 1000; - this.ctx.translate(spacingLength, 0); - current.x += spacingLength * textHScale; - continue; - } - const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing; - const operatorList = font.charProcOperatorList[glyph.operatorListId]; - if (!operatorList) { - (0, _util.warn)(`Type3 character "${glyph.operatorListId}" is not available.`); - continue; - } - if (this.contentVisible) { - this.processingType3 = glyph; - this.save(); - ctx.scale(fontSize, fontSize); - ctx.transform(...fontMatrix); - this.executeOperatorList(operatorList); - this.restore(); - } - const transformed = _util.Util.applyTransform([glyph.width, 0], fontMatrix); - width = transformed[0] * fontSize + spacing; - ctx.translate(width, 0); - current.x += width * textHScale; - } - ctx.restore(); - this.processingType3 = null; - } - setCharWidth(xWidth, yWidth) {} - setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) { - this.ctx.rect(llx, lly, urx - llx, ury - lly); - this.ctx.clip(); - this.endPath(); - } - getColorN_Pattern(IR) { - let pattern; - if (IR[0] === "TilingPattern") { - const color = IR[1]; - const baseTransform = this.baseTransform || (0, _display_utils.getCurrentTransform)(this.ctx); - const canvasGraphicsFactory = { - createCanvasGraphics: ctx => { - return new CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, { - optionalContentConfig: this.optionalContentConfig, - markedContentStack: this.markedContentStack - }); - } - }; - pattern = new _pattern_helper.TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform); - } else { - pattern = this._getPattern(IR[1], IR[2]); - } - return pattern; - } - setStrokeColorN() { - this.current.strokeColor = this.getColorN_Pattern(arguments); - } - setFillColorN() { - this.current.fillColor = this.getColorN_Pattern(arguments); - this.current.patternFill = true; - } - setStrokeRGBColor(r, g, b) { - const color = _util.Util.makeHexColor(r, g, b); - this.ctx.strokeStyle = color; - this.current.strokeColor = color; - } - setFillRGBColor(r, g, b) { - const color = _util.Util.makeHexColor(r, g, b); - this.ctx.fillStyle = color; - this.current.fillColor = color; - this.current.patternFill = false; - } - _getPattern(objId, matrix = null) { - let pattern; - if (this.cachedPatterns.has(objId)) { - pattern = this.cachedPatterns.get(objId); - } else { - pattern = (0, _pattern_helper.getShadingPattern)(this.getObject(objId)); - this.cachedPatterns.set(objId, pattern); - } - if (matrix) { - pattern.matrix = matrix; - } - return pattern; - } - shadingFill(objId) { - if (!this.contentVisible) { - return; - } - const ctx = this.ctx; - this.save(); - const pattern = this._getPattern(objId); - ctx.fillStyle = pattern.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.SHADING); - const inv = (0, _display_utils.getCurrentTransformInverse)(ctx); - if (inv) { - const { - width, - height - } = ctx.canvas; - const [x0, y0, x1, y1] = _util.Util.getAxialAlignedBoundingBox([0, 0, width, height], inv); - this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0); - } else { - this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10); - } - this.compose(this.current.getClippedPathBoundingBox()); - this.restore(); - } - beginInlineImage() { - (0, _util.unreachable)("Should not call beginInlineImage"); - } - beginImageData() { - (0, _util.unreachable)("Should not call beginImageData"); - } - paintFormXObjectBegin(matrix, bbox) { - if (!this.contentVisible) { - return; - } - this.save(); - this.baseTransformStack.push(this.baseTransform); - if (Array.isArray(matrix) && matrix.length === 6) { - this.transform(...matrix); - } - this.baseTransform = (0, _display_utils.getCurrentTransform)(this.ctx); - if (bbox) { - const width = bbox[2] - bbox[0]; - const height = bbox[3] - bbox[1]; - this.ctx.rect(bbox[0], bbox[1], width, height); - this.current.updateRectMinMax((0, _display_utils.getCurrentTransform)(this.ctx), bbox); - this.clip(); - this.endPath(); - } - } - paintFormXObjectEnd() { - if (!this.contentVisible) { - return; - } - this.restore(); - this.baseTransform = this.baseTransformStack.pop(); - } - beginGroup(group) { - if (!this.contentVisible) { - return; - } - this.save(); - if (this.inSMaskMode) { - this.endSMaskMode(); - this.current.activeSMask = null; - } - const currentCtx = this.ctx; - if (!group.isolated) { - (0, _util.info)("TODO: Support non-isolated groups."); - } - if (group.knockout) { - (0, _util.warn)("Knockout groups not supported."); - } - const currentTransform = (0, _display_utils.getCurrentTransform)(currentCtx); - if (group.matrix) { - currentCtx.transform(...group.matrix); - } - if (!group.bbox) { - throw new Error("Bounding box is required."); - } - let bounds = _util.Util.getAxialAlignedBoundingBox(group.bbox, (0, _display_utils.getCurrentTransform)(currentCtx)); - const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height]; - bounds = _util.Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0]; - const offsetX = Math.floor(bounds[0]); - const offsetY = Math.floor(bounds[1]); - let drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1); - let drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1); - let scaleX = 1, - scaleY = 1; - if (drawnWidth > MAX_GROUP_SIZE) { - scaleX = drawnWidth / MAX_GROUP_SIZE; - drawnWidth = MAX_GROUP_SIZE; - } - if (drawnHeight > MAX_GROUP_SIZE) { - scaleY = drawnHeight / MAX_GROUP_SIZE; - drawnHeight = MAX_GROUP_SIZE; - } - this.current.startNewPathAndClipBox([0, 0, drawnWidth, drawnHeight]); - let cacheId = "groupAt" + this.groupLevel; - if (group.smask) { - cacheId += "_smask_" + this.smaskCounter++ % 2; - } - const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight); - const groupCtx = scratchCanvas.context; - groupCtx.scale(1 / scaleX, 1 / scaleY); - groupCtx.translate(-offsetX, -offsetY); - groupCtx.transform(...currentTransform); - if (group.smask) { - this.smaskStack.push({ - canvas: scratchCanvas.canvas, - context: groupCtx, - offsetX, - offsetY, - scaleX, - scaleY, - subtype: group.smask.subtype, - backdrop: group.smask.backdrop, - transferMap: group.smask.transferMap || null, - startTransformInverse: null - }); - } else { - currentCtx.setTransform(1, 0, 0, 1, 0, 0); - currentCtx.translate(offsetX, offsetY); - currentCtx.scale(scaleX, scaleY); - currentCtx.save(); - } - copyCtxState(currentCtx, groupCtx); - this.ctx = groupCtx; - this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]); - this.groupStack.push(currentCtx); - this.groupLevel++; - } - endGroup(group) { - if (!this.contentVisible) { - return; - } - this.groupLevel--; - const groupCtx = this.ctx; - const ctx = this.groupStack.pop(); - this.ctx = ctx; - this.ctx.imageSmoothingEnabled = false; - if (group.smask) { - this.tempSMask = this.smaskStack.pop(); - this.restore(); - } else { - this.ctx.restore(); - const currentMtx = (0, _display_utils.getCurrentTransform)(this.ctx); - this.restore(); - this.ctx.save(); - this.ctx.setTransform(...currentMtx); - const dirtyBox = _util.Util.getAxialAlignedBoundingBox([0, 0, groupCtx.canvas.width, groupCtx.canvas.height], currentMtx); - this.ctx.drawImage(groupCtx.canvas, 0, 0); - this.ctx.restore(); - this.compose(dirtyBox); - } - } - beginAnnotation(id, rect, transform, matrix, hasOwnCanvas) { - this.#restoreInitialState(); - resetCtxToDefault(this.ctx); - this.ctx.save(); - this.save(); - if (this.baseTransform) { - this.ctx.setTransform(...this.baseTransform); - } - if (Array.isArray(rect) && rect.length === 4) { - const width = rect[2] - rect[0]; - const height = rect[3] - rect[1]; - if (hasOwnCanvas && this.annotationCanvasMap) { - transform = transform.slice(); - transform[4] -= rect[0]; - transform[5] -= rect[1]; - rect = rect.slice(); - rect[0] = rect[1] = 0; - rect[2] = width; - rect[3] = height; - const [scaleX, scaleY] = _util.Util.singularValueDecompose2dScale((0, _display_utils.getCurrentTransform)(this.ctx)); - const { - viewportScale - } = this; - const canvasWidth = Math.ceil(width * this.outputScaleX * viewportScale); - const canvasHeight = Math.ceil(height * this.outputScaleY * viewportScale); - this.annotationCanvas = this.canvasFactory.create(canvasWidth, canvasHeight); - const { - canvas, - context - } = this.annotationCanvas; - this.annotationCanvasMap.set(id, canvas); - this.annotationCanvas.savedCtx = this.ctx; - this.ctx = context; - this.ctx.save(); - this.ctx.setTransform(scaleX, 0, 0, -scaleY, 0, height * scaleY); - resetCtxToDefault(this.ctx); - } else { - resetCtxToDefault(this.ctx); - this.ctx.rect(rect[0], rect[1], width, height); - this.ctx.clip(); - this.endPath(); - } - } - this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height); - this.transform(...transform); - this.transform(...matrix); - } - endAnnotation() { - if (this.annotationCanvas) { - this.ctx.restore(); - this.#drawFilter(); - this.ctx = this.annotationCanvas.savedCtx; - delete this.annotationCanvas.savedCtx; - delete this.annotationCanvas; - } - } - paintImageMaskXObject(img) { - if (!this.contentVisible) { - return; - } - const count = img.count; - img = this.getObject(img.data, img); - img.count = count; - const ctx = this.ctx; - const glyph = this.processingType3; - if (glyph) { - if (glyph.compiled === undefined) { - glyph.compiled = compileType3Glyph(img); - } - if (glyph.compiled) { - glyph.compiled(ctx); - return; - } - } - const mask = this._createMaskCanvas(img); - const maskCanvas = mask.canvas; - ctx.save(); - ctx.setTransform(1, 0, 0, 1, 0, 0); - ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY); - ctx.restore(); - this.compose(); - } - paintImageMaskXObjectRepeat(img, scaleX, skewX = 0, skewY = 0, scaleY, positions) { - if (!this.contentVisible) { - return; - } - img = this.getObject(img.data, img); - const ctx = this.ctx; - ctx.save(); - const currentTransform = (0, _display_utils.getCurrentTransform)(ctx); - ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0); - const mask = this._createMaskCanvas(img); - ctx.setTransform(1, 0, 0, 1, mask.offsetX - currentTransform[4], mask.offsetY - currentTransform[5]); - for (let i = 0, ii = positions.length; i < ii; i += 2) { - const trans = _util.Util.transform(currentTransform, [scaleX, skewX, skewY, scaleY, positions[i], positions[i + 1]]); - const [x, y] = _util.Util.applyTransform([0, 0], trans); - ctx.drawImage(mask.canvas, x, y); - } - ctx.restore(); - this.compose(); - } - paintImageMaskXObjectGroup(images) { - if (!this.contentVisible) { - return; - } - const ctx = this.ctx; - const fillColor = this.current.fillColor; - const isPatternFill = this.current.patternFill; - for (const image of images) { - const { - data, - width, - height, - transform - } = image; - const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height); - const maskCtx = maskCanvas.context; - maskCtx.save(); - const img = this.getObject(data, image); - putBinaryImageMask(maskCtx, img); - maskCtx.globalCompositeOperation = "source-in"; - maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.FILL) : fillColor; - maskCtx.fillRect(0, 0, width, height); - maskCtx.restore(); - ctx.save(); - ctx.transform(...transform); - ctx.scale(1, -1); - drawImageAtIntegerCoords(ctx, maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1); - ctx.restore(); - } - this.compose(); - } - paintImageXObject(objId) { - if (!this.contentVisible) { - return; - } - const imgData = this.getObject(objId); - if (!imgData) { - (0, _util.warn)("Dependent image isn't ready yet"); - return; - } - this.paintInlineImageXObject(imgData); - } - paintImageXObjectRepeat(objId, scaleX, scaleY, positions) { - if (!this.contentVisible) { - return; - } - const imgData = this.getObject(objId); - if (!imgData) { - (0, _util.warn)("Dependent image isn't ready yet"); - return; - } - const width = imgData.width; - const height = imgData.height; - const map = []; - for (let i = 0, ii = positions.length; i < ii; i += 2) { - map.push({ - transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]], - x: 0, - y: 0, - w: width, - h: height - }); - } - this.paintInlineImageXObjectGroup(imgData, map); - } - applyTransferMapsToCanvas(ctx) { - if (this.current.transferMaps !== "none") { - ctx.filter = this.current.transferMaps; - ctx.drawImage(ctx.canvas, 0, 0); - ctx.filter = "none"; - } - return ctx.canvas; - } - applyTransferMapsToBitmap(imgData) { - if (this.current.transferMaps === "none") { - return imgData.bitmap; - } - const { - bitmap, - width, - height - } = imgData; - const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height); - const tmpCtx = tmpCanvas.context; - tmpCtx.filter = this.current.transferMaps; - tmpCtx.drawImage(bitmap, 0, 0); - tmpCtx.filter = "none"; - return tmpCanvas.canvas; - } - paintInlineImageXObject(imgData) { - if (!this.contentVisible) { - return; - } - const width = imgData.width; - const height = imgData.height; - const ctx = this.ctx; - this.save(); - if (!_util.isNodeJS) { - const { - filter - } = ctx; - if (filter !== "none" && filter !== "") { - ctx.filter = "none"; - } - } - ctx.scale(1 / width, -1 / height); - let imgToPaint; - if (imgData.bitmap) { - imgToPaint = this.applyTransferMapsToBitmap(imgData); - } else if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) { - imgToPaint = imgData; - } else { - const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height); - const tmpCtx = tmpCanvas.context; - putBinaryImageData(tmpCtx, imgData); - imgToPaint = this.applyTransferMapsToCanvas(tmpCtx); - } - const scaled = this._scaleImage(imgToPaint, (0, _display_utils.getCurrentTransformInverse)(ctx)); - ctx.imageSmoothingEnabled = getImageSmoothingEnabled((0, _display_utils.getCurrentTransform)(ctx), imgData.interpolate); - drawImageAtIntegerCoords(ctx, scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height); - this.compose(); - this.restore(); - } - paintInlineImageXObjectGroup(imgData, map) { - if (!this.contentVisible) { - return; - } - const ctx = this.ctx; - let imgToPaint; - if (imgData.bitmap) { - imgToPaint = imgData.bitmap; - } else { - const w = imgData.width; - const h = imgData.height; - const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h); - const tmpCtx = tmpCanvas.context; - putBinaryImageData(tmpCtx, imgData); - imgToPaint = this.applyTransferMapsToCanvas(tmpCtx); - } - for (const entry of map) { - ctx.save(); - ctx.transform(...entry.transform); - ctx.scale(1, -1); - drawImageAtIntegerCoords(ctx, imgToPaint, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1); - ctx.restore(); - } - this.compose(); - } - paintSolidColorImageMask() { - if (!this.contentVisible) { - return; - } - this.ctx.fillRect(0, 0, 1, 1); - this.compose(); - } - markPoint(tag) {} - markPointProps(tag, properties) {} - beginMarkedContent(tag) { - this.markedContentStack.push({ - visible: true - }); - } - beginMarkedContentProps(tag, properties) { - if (tag === "OC") { - this.markedContentStack.push({ - visible: this.optionalContentConfig.isVisible(properties) - }); - } else { - this.markedContentStack.push({ - visible: true - }); - } - this.contentVisible = this.isContentVisible(); - } - endMarkedContent() { - this.markedContentStack.pop(); - this.contentVisible = this.isContentVisible(); - } - beginCompat() {} - endCompat() {} - consumePath(clipBox) { - const isEmpty = this.current.isEmptyClip(); - if (this.pendingClip) { - this.current.updateClipFromPath(); - } - if (!this.pendingClip) { - this.compose(clipBox); - } - const ctx = this.ctx; - if (this.pendingClip) { - if (!isEmpty) { - if (this.pendingClip === EO_CLIP) { - ctx.clip("evenodd"); - } else { - ctx.clip(); - } - } - this.pendingClip = null; - } - this.current.startNewPathAndClipBox(this.current.clipBox); - ctx.beginPath(); - } - getSinglePixelWidth() { - if (!this._cachedGetSinglePixelWidth) { - const m = (0, _display_utils.getCurrentTransform)(this.ctx); - if (m[1] === 0 && m[2] === 0) { - this._cachedGetSinglePixelWidth = 1 / Math.min(Math.abs(m[0]), Math.abs(m[3])); - } else { - const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]); - const normX = Math.hypot(m[0], m[2]); - const normY = Math.hypot(m[1], m[3]); - this._cachedGetSinglePixelWidth = Math.max(normX, normY) / absDet; - } - } - return this._cachedGetSinglePixelWidth; - } - getScaleForStroking() { - if (this._cachedScaleForStroking[0] === -1) { - const { - lineWidth - } = this.current; - const { - a, - b, - c, - d - } = this.ctx.getTransform(); - let scaleX, scaleY; - if (b === 0 && c === 0) { - const normX = Math.abs(a); - const normY = Math.abs(d); - if (normX === normY) { - if (lineWidth === 0) { - scaleX = scaleY = 1 / normX; - } else { - const scaledLineWidth = normX * lineWidth; - scaleX = scaleY = scaledLineWidth < 1 ? 1 / scaledLineWidth : 1; - } - } else if (lineWidth === 0) { - scaleX = 1 / normX; - scaleY = 1 / normY; - } else { - const scaledXLineWidth = normX * lineWidth; - const scaledYLineWidth = normY * lineWidth; - scaleX = scaledXLineWidth < 1 ? 1 / scaledXLineWidth : 1; - scaleY = scaledYLineWidth < 1 ? 1 / scaledYLineWidth : 1; - } - } else { - const absDet = Math.abs(a * d - b * c); - const normX = Math.hypot(a, b); - const normY = Math.hypot(c, d); - if (lineWidth === 0) { - scaleX = normY / absDet; - scaleY = normX / absDet; - } else { - const baseArea = lineWidth * absDet; - scaleX = normY > baseArea ? normY / baseArea : 1; - scaleY = normX > baseArea ? normX / baseArea : 1; - } - } - this._cachedScaleForStroking[0] = scaleX; - this._cachedScaleForStroking[1] = scaleY; - } - return this._cachedScaleForStroking; - } - rescaleAndStroke(saveRestore) { - const { - ctx - } = this; - const { - lineWidth - } = this.current; - const [scaleX, scaleY] = this.getScaleForStroking(); - ctx.lineWidth = lineWidth || 1; - if (scaleX === 1 && scaleY === 1) { - ctx.stroke(); - return; - } - const dashes = ctx.getLineDash(); - if (saveRestore) { - ctx.save(); - } - ctx.scale(scaleX, scaleY); - if (dashes.length > 0) { - const scale = Math.max(scaleX, scaleY); - ctx.setLineDash(dashes.map(x => x / scale)); - ctx.lineDashOffset /= scale; - } - ctx.stroke(); - if (saveRestore) { - ctx.restore(); - } - } - isContentVisible() { - for (let i = this.markedContentStack.length - 1; i >= 0; i--) { - if (!this.markedContentStack[i].visible) { - return false; - } - } - return true; - } -} -exports.CanvasGraphics = CanvasGraphics; -for (const op in _util.OPS) { - if (CanvasGraphics.prototype[op] !== undefined) { - CanvasGraphics.prototype[_util.OPS[op]] = CanvasGraphics.prototype[op]; +class NodeStandardFontDataFactory extends BaseStandardFontDataFactory { + _fetchData(url) { + return node_utils_fetchData(url); } } -/***/ }), -/* 12 */ -/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { +;// CONCATENATED MODULE: ./src/display/pattern_helper.js - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.TilingPattern = exports.PathType = void 0; -exports.getShadingPattern = getShadingPattern; -var _util = __w_pdfjs_require__(1); -var _display_utils = __w_pdfjs_require__(6); const PathType = { FILL: "Fill", STROKE: "Stroke", SHADING: "Shading" }; -exports.PathType = PathType; function applyBoundingBox(ctx, bbox) { if (!bbox) { return; @@ -8510,13 +5746,8 @@ function applyBoundingBox(ctx, bbox) { ctx.clip(region); } class BaseShadingPattern { - constructor() { - if (this.constructor === BaseShadingPattern) { - (0, _util.unreachable)("Cannot initialize BaseShadingPattern."); - } - } getPattern() { - (0, _util.unreachable)("Abstract method `getPattern` called."); + unreachable("Abstract method `getPattern` called."); } } class RadialAxialShadingPattern extends BaseShadingPattern { @@ -8546,7 +5777,7 @@ class RadialAxialShadingPattern extends BaseShadingPattern { getPattern(ctx, owner, inverse, pathType) { let pattern; if (pathType === PathType.STROKE || pathType === PathType.FILL) { - const ownerBBox = owner.current.getClippedPathBoundingBox(pathType, (0, _display_utils.getCurrentTransform)(ctx)) || [0, 0, 0, 0]; + const ownerBBox = owner.current.getClippedPathBoundingBox(pathType, getCurrentTransform(ctx)) || [0, 0, 0, 0]; const width = Math.ceil(ownerBBox[2] - ownerBBox[0]) || 1; const height = Math.ceil(ownerBBox[3] - ownerBBox[1]) || 1; const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", width, height, true); @@ -8555,7 +5786,7 @@ class RadialAxialShadingPattern extends BaseShadingPattern { tmpCtx.beginPath(); tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height); tmpCtx.translate(-ownerBBox[0], -ownerBBox[1]); - inverse = _util.Util.transform(inverse, [1, 0, 0, 1, ownerBBox[0], ownerBBox[1]]); + inverse = Util.transform(inverse, [1, 0, 0, 1, ownerBBox[0], ownerBBox[1]]); tmpCtx.transform(...owner.baseTransform); if (this.matrix) { tmpCtx.transform(...this.matrix); @@ -8763,11 +5994,11 @@ class MeshShadingPattern extends BaseShadingPattern { applyBoundingBox(ctx, this._bbox); let scale; if (pathType === PathType.SHADING) { - scale = _util.Util.singularValueDecompose2dScale((0, _display_utils.getCurrentTransform)(ctx)); + scale = Util.singularValueDecompose2dScale(getCurrentTransform(ctx)); } else { - scale = _util.Util.singularValueDecompose2dScale(owner.baseTransform); + scale = Util.singularValueDecompose2dScale(owner.baseTransform); if (this.matrix) { - const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix); + const matrixScale = Util.singularValueDecompose2dScale(this.matrix); scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]]; } } @@ -8807,7 +6038,7 @@ class TilingPattern { static MAX_PATTERN_SIZE = 3000; constructor(IR, color, ctx, canvasGraphicsFactory, baseTransform) { this.operatorList = IR[2]; - this.matrix = IR[3] || [1, 0, 0, 1, 0, 0]; + this.matrix = IR[3]; this.bbox = IR[4]; this.xstep = IR[5]; this.ystep = IR[6]; @@ -8827,13 +6058,13 @@ class TilingPattern { const tilingType = this.tilingType; const color = this.color; const canvasGraphicsFactory = this.canvasGraphicsFactory; - (0, _util.info)("TilingType: " + tilingType); + info("TilingType: " + tilingType); const x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3]; - const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix); - const curMatrixScale = _util.Util.singularValueDecompose2dScale(this.baseTransform); + const matrixScale = Util.singularValueDecompose2dScale(this.matrix); + const curMatrixScale = Util.singularValueDecompose2dScale(this.baseTransform); const combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]]; const dimx = this.getSizeAndScale(xstep, this.ctx.canvas.width, combinedScale[0]); const dimy = this.getSizeAndScale(ystep, this.ctx.canvas.height, combinedScale[1]); @@ -8858,7 +6089,7 @@ class TilingPattern { graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0); tmpCtx.save(); this.clipBbox(graphics, adjustedX0, adjustedY0, adjustedX1, adjustedY1); - graphics.baseTransform = (0, _display_utils.getCurrentTransform)(graphics.ctx); + graphics.baseTransform = getCurrentTransform(graphics.ctx); graphics.executeOperatorList(operatorList); graphics.endDrawing(); return { @@ -8887,7 +6118,7 @@ class TilingPattern { const bboxWidth = x1 - x0; const bboxHeight = y1 - y0; graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight); - graphics.current.updateRectMinMax((0, _display_utils.getCurrentTransform)(graphics.ctx), [x0, y0, x1, y1]); + graphics.current.updateRectMinMax(getCurrentTransform(graphics.ctx), [x0, y0, x1, y1]); graphics.clip(); graphics.endPath(); } @@ -8903,22 +6134,22 @@ class TilingPattern { current.strokeColor = ctx.strokeStyle; break; case PaintType.UNCOLORED: - const cssColor = _util.Util.makeHexColor(color[0], color[1], color[2]); + const cssColor = Util.makeHexColor(color[0], color[1], color[2]); context.fillStyle = cssColor; context.strokeStyle = cssColor; current.fillColor = cssColor; current.strokeColor = cssColor; break; default: - throw new _util.FormatError(`Unsupported paint type: ${paintType}`); + throw new FormatError(`Unsupported paint type: ${paintType}`); } } getPattern(ctx, owner, inverse, pathType) { let matrix = inverse; if (pathType !== PathType.SHADING) { - matrix = _util.Util.transform(matrix, owner.baseTransform); + matrix = Util.transform(matrix, owner.baseTransform); if (this.matrix) { - matrix = _util.Util.transform(matrix, this.matrix); + matrix = Util.transform(matrix, this.matrix); } } const temporaryPatternCanvas = this.createPatternCanvas(owner); @@ -8930,26 +6161,14 @@ class TilingPattern { return pattern; } } -exports.TilingPattern = TilingPattern; -/***/ }), -/* 13 */ -/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { +;// CONCATENATED MODULE: ./src/shared/image_utils.js - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.convertBlackAndWhiteToRGBA = convertBlackAndWhiteToRGBA; -exports.convertToRGBA = convertToRGBA; -exports.grayToRGBA = grayToRGBA; -var _util = __w_pdfjs_require__(1); function convertToRGBA(params) { switch (params.kind) { - case _util.ImageKind.GRAYSCALE_1BPP: + case ImageKind.GRAYSCALE_1BPP: return convertBlackAndWhiteToRGBA(params); - case _util.ImageKind.RGB_24BPP: + case ImageKind.RGB_24BPP: return convertRGBToRGBA(params); } return null; @@ -8963,7 +6182,7 @@ function convertBlackAndWhiteToRGBA({ nonBlackColor = 0xffffffff, inverseDecode = false }) { - const black = _util.FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff; + const black = util_FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff; const [zeroMapping, oneMapping] = inverseDecode ? [nonBlackColor, black] : [black, nonBlackColor]; const widthInSource = width >> 3; const widthRemainder = width & 7; @@ -9006,7 +6225,7 @@ function convertRGBToRGBA({ let i = 0; const len32 = src.length >> 2; const src32 = new Uint32Array(src.buffer, srcPos, len32); - if (_util.FeatureTest.isLittleEndian) { + if (FeatureTest.isLittleEndian) { for (; i < len32 - 2; i += 3, destPos += 4) { const s1 = src32[i]; const s2 = src32[i + 1]; @@ -9039,7 +6258,7 @@ function convertRGBToRGBA({ }; } function grayToRGBA(src, dest) { - if (_util.FeatureTest.isLittleEndian) { + if (FeatureTest.isLittleEndian) { for (let i = 0, ii = src.length; i < ii; i++) { dest[i] = src[i] * 0x10101 | 0xff000000; } @@ -9050,32 +6269,2211 @@ function grayToRGBA(src, dest) { } } -/***/ }), -/* 14 */ -/***/ ((__unused_webpack_module, exports) => { +;// CONCATENATED MODULE: ./src/display/canvas.js -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.GlobalWorkerOptions = void 0; -const GlobalWorkerOptions = Object.create(null); -exports.GlobalWorkerOptions = GlobalWorkerOptions; -GlobalWorkerOptions.workerPort = null; -GlobalWorkerOptions.workerSrc = ""; -/***/ }), -/* 15 */ -/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { +const MIN_FONT_SIZE = 16; +const MAX_FONT_SIZE = 100; +const EXECUTION_TIME = 15; +const EXECUTION_STEPS = 10; +const MAX_SIZE_TO_COMPILE = 1000; +const FULL_CHUNK_HEIGHT = 16; +function mirrorContextOperations(ctx, destCtx) { + if (ctx._removeMirroring) { + throw new Error("Context is already forwarding operations."); + } + ctx.__originalSave = ctx.save; + ctx.__originalRestore = ctx.restore; + ctx.__originalRotate = ctx.rotate; + ctx.__originalScale = ctx.scale; + ctx.__originalTranslate = ctx.translate; + ctx.__originalTransform = ctx.transform; + ctx.__originalSetTransform = ctx.setTransform; + ctx.__originalResetTransform = ctx.resetTransform; + ctx.__originalClip = ctx.clip; + ctx.__originalMoveTo = ctx.moveTo; + ctx.__originalLineTo = ctx.lineTo; + ctx.__originalBezierCurveTo = ctx.bezierCurveTo; + ctx.__originalRect = ctx.rect; + ctx.__originalClosePath = ctx.closePath; + ctx.__originalBeginPath = ctx.beginPath; + ctx._removeMirroring = () => { + ctx.save = ctx.__originalSave; + ctx.restore = ctx.__originalRestore; + ctx.rotate = ctx.__originalRotate; + ctx.scale = ctx.__originalScale; + ctx.translate = ctx.__originalTranslate; + ctx.transform = ctx.__originalTransform; + ctx.setTransform = ctx.__originalSetTransform; + ctx.resetTransform = ctx.__originalResetTransform; + ctx.clip = ctx.__originalClip; + ctx.moveTo = ctx.__originalMoveTo; + ctx.lineTo = ctx.__originalLineTo; + ctx.bezierCurveTo = ctx.__originalBezierCurveTo; + ctx.rect = ctx.__originalRect; + ctx.closePath = ctx.__originalClosePath; + ctx.beginPath = ctx.__originalBeginPath; + delete ctx._removeMirroring; + }; + ctx.save = function ctxSave() { + destCtx.save(); + this.__originalSave(); + }; + ctx.restore = function ctxRestore() { + destCtx.restore(); + this.__originalRestore(); + }; + ctx.translate = function ctxTranslate(x, y) { + destCtx.translate(x, y); + this.__originalTranslate(x, y); + }; + ctx.scale = function ctxScale(x, y) { + destCtx.scale(x, y); + this.__originalScale(x, y); + }; + ctx.transform = function ctxTransform(a, b, c, d, e, f) { + destCtx.transform(a, b, c, d, e, f); + this.__originalTransform(a, b, c, d, e, f); + }; + ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) { + destCtx.setTransform(a, b, c, d, e, f); + this.__originalSetTransform(a, b, c, d, e, f); + }; + ctx.resetTransform = function ctxResetTransform() { + destCtx.resetTransform(); + this.__originalResetTransform(); + }; + ctx.rotate = function ctxRotate(angle) { + destCtx.rotate(angle); + this.__originalRotate(angle); + }; + ctx.clip = function ctxRotate(rule) { + destCtx.clip(rule); + this.__originalClip(rule); + }; + ctx.moveTo = function (x, y) { + destCtx.moveTo(x, y); + this.__originalMoveTo(x, y); + }; + ctx.lineTo = function (x, y) { + destCtx.lineTo(x, y); + this.__originalLineTo(x, y); + }; + ctx.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) { + destCtx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y); + this.__originalBezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y); + }; + ctx.rect = function (x, y, width, height) { + destCtx.rect(x, y, width, height); + this.__originalRect(x, y, width, height); + }; + ctx.closePath = function () { + destCtx.closePath(); + this.__originalClosePath(); + }; + ctx.beginPath = function () { + destCtx.beginPath(); + this.__originalBeginPath(); + }; +} +class CachedCanvases { + constructor(canvasFactory) { + this.canvasFactory = canvasFactory; + this.cache = Object.create(null); + } + getCanvas(id, width, height) { + let canvasEntry; + if (this.cache[id] !== undefined) { + canvasEntry = this.cache[id]; + this.canvasFactory.reset(canvasEntry, width, height); + } else { + canvasEntry = this.canvasFactory.create(width, height); + this.cache[id] = canvasEntry; + } + return canvasEntry; + } + delete(id) { + delete this.cache[id]; + } + clear() { + for (const id in this.cache) { + const canvasEntry = this.cache[id]; + this.canvasFactory.destroy(canvasEntry); + delete this.cache[id]; + } + } +} +function drawImageAtIntegerCoords(ctx, srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH) { + const [a, b, c, d, tx, ty] = getCurrentTransform(ctx); + if (b === 0 && c === 0) { + const tlX = destX * a + tx; + const rTlX = Math.round(tlX); + const tlY = destY * d + ty; + const rTlY = Math.round(tlY); + const brX = (destX + destW) * a + tx; + const rWidth = Math.abs(Math.round(brX) - rTlX) || 1; + const brY = (destY + destH) * d + ty; + const rHeight = Math.abs(Math.round(brY) - rTlY) || 1; + ctx.setTransform(Math.sign(a), 0, 0, Math.sign(d), rTlX, rTlY); + ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rWidth, rHeight); + ctx.setTransform(a, b, c, d, tx, ty); + return [rWidth, rHeight]; + } + if (a === 0 && d === 0) { + const tlX = destY * c + tx; + const rTlX = Math.round(tlX); + const tlY = destX * b + ty; + const rTlY = Math.round(tlY); + const brX = (destY + destH) * c + tx; + const rWidth = Math.abs(Math.round(brX) - rTlX) || 1; + const brY = (destX + destW) * b + ty; + const rHeight = Math.abs(Math.round(brY) - rTlY) || 1; + ctx.setTransform(0, Math.sign(b), Math.sign(c), 0, rTlX, rTlY); + ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rHeight, rWidth); + ctx.setTransform(a, b, c, d, tx, ty); + return [rHeight, rWidth]; + } + ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH); + const scaleX = Math.hypot(a, b); + const scaleY = Math.hypot(c, d); + return [scaleX * destW, scaleY * destH]; +} +function compileType3Glyph(imgData) { + const { + width, + height + } = imgData; + if (width > MAX_SIZE_TO_COMPILE || height > MAX_SIZE_TO_COMPILE) { + return null; + } + const POINT_TO_PROCESS_LIMIT = 1000; + const POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]); + const width1 = width + 1; + let points = new Uint8Array(width1 * (height + 1)); + let i, j, j0; + const lineSize = width + 7 & ~7; + let data = new Uint8Array(lineSize * height), + pos = 0; + for (const elem of imgData.data) { + let mask = 128; + while (mask > 0) { + data[pos++] = elem & mask ? 0 : 255; + mask >>= 1; + } + } + let count = 0; + pos = 0; + if (data[pos] !== 0) { + points[0] = 1; + ++count; + } + for (j = 1; j < width; j++) { + if (data[pos] !== data[pos + 1]) { + points[j] = data[pos] ? 2 : 1; + ++count; + } + pos++; + } + if (data[pos] !== 0) { + points[j] = 2; + ++count; + } + for (i = 1; i < height; i++) { + pos = i * lineSize; + j0 = i * width1; + if (data[pos - lineSize] !== data[pos]) { + points[j0] = data[pos] ? 1 : 8; + ++count; + } + let sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0); + for (j = 1; j < width; j++) { + sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0); + if (POINT_TYPES[sum]) { + points[j0 + j] = POINT_TYPES[sum]; + ++count; + } + pos++; + } + if (data[pos - lineSize] !== data[pos]) { + points[j0 + j] = data[pos] ? 2 : 4; + ++count; + } + if (count > POINT_TO_PROCESS_LIMIT) { + return null; + } + } + pos = lineSize * (height - 1); + j0 = i * width1; + if (data[pos] !== 0) { + points[j0] = 8; + ++count; + } + for (j = 1; j < width; j++) { + if (data[pos] !== data[pos + 1]) { + points[j0 + j] = data[pos] ? 4 : 8; + ++count; + } + pos++; + } + if (data[pos] !== 0) { + points[j0 + j] = 4; + ++count; + } + if (count > POINT_TO_PROCESS_LIMIT) { + return null; + } + const steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]); + const path = new Path2D(); + for (i = 0; count && i <= height; i++) { + let p = i * width1; + const end = p + width; + while (p < end && !points[p]) { + p++; + } + if (p === end) { + continue; + } + path.moveTo(p % width1, i); + const p0 = p; + let type = points[p]; + do { + const step = steps[type]; + do { + p += step; + } while (!points[p]); + const pp = points[p]; + if (pp !== 5 && pp !== 10) { + type = pp; + points[p] = 0; + } else { + type = pp & 0x33 * type >> 4; + points[p] &= type >> 2 | type << 2; + } + path.lineTo(p % width1, p / width1 | 0); + if (!points[p]) { + --count; + } + } while (p0 !== p); + --i; + } + data = null; + points = null; + const drawOutline = function (c) { + c.save(); + c.scale(1 / width, -1 / height); + c.translate(0, -height); + c.fill(path); + c.beginPath(); + c.restore(); + }; + return drawOutline; +} +class CanvasExtraState { + constructor(width, height) { + this.alphaIsShape = false; + this.fontSize = 0; + this.fontSizeScale = 1; + this.textMatrix = IDENTITY_MATRIX; + this.textMatrixScale = 1; + this.fontMatrix = FONT_IDENTITY_MATRIX; + this.leading = 0; + this.x = 0; + this.y = 0; + this.lineX = 0; + this.lineY = 0; + this.charSpacing = 0; + this.wordSpacing = 0; + this.textHScale = 1; + this.textRenderingMode = TextRenderingMode.FILL; + this.textRise = 0; + this.fillColor = "#000000"; + this.strokeColor = "#000000"; + this.patternFill = false; + this.fillAlpha = 1; + this.strokeAlpha = 1; + this.lineWidth = 1; + this.activeSMask = null; + this.transferMaps = "none"; + this.startNewPathAndClipBox([0, 0, width, height]); + } + clone() { + const clone = Object.create(this); + clone.clipBox = this.clipBox.slice(); + return clone; + } + setCurrentPoint(x, y) { + this.x = x; + this.y = y; + } + updatePathMinMax(transform, x, y) { + [x, y] = Util.applyTransform([x, y], transform); + this.minX = Math.min(this.minX, x); + this.minY = Math.min(this.minY, y); + this.maxX = Math.max(this.maxX, x); + this.maxY = Math.max(this.maxY, y); + } + updateRectMinMax(transform, rect) { + const p1 = Util.applyTransform(rect, transform); + const p2 = Util.applyTransform(rect.slice(2), transform); + const p3 = Util.applyTransform([rect[0], rect[3]], transform); + const p4 = Util.applyTransform([rect[2], rect[1]], transform); + this.minX = Math.min(this.minX, p1[0], p2[0], p3[0], p4[0]); + this.minY = Math.min(this.minY, p1[1], p2[1], p3[1], p4[1]); + this.maxX = Math.max(this.maxX, p1[0], p2[0], p3[0], p4[0]); + this.maxY = Math.max(this.maxY, p1[1], p2[1], p3[1], p4[1]); + } + updateScalingPathMinMax(transform, minMax) { + Util.scaleMinMax(transform, minMax); + this.minX = Math.min(this.minX, minMax[0]); + this.minY = Math.min(this.minY, minMax[1]); + this.maxX = Math.max(this.maxX, minMax[2]); + this.maxY = Math.max(this.maxY, minMax[3]); + } + updateCurvePathMinMax(transform, x0, y0, x1, y1, x2, y2, x3, y3, minMax) { + const box = Util.bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3, minMax); + if (minMax) { + return; + } + this.updateRectMinMax(transform, box); + } + getPathBoundingBox(pathType = PathType.FILL, transform = null) { + const box = [this.minX, this.minY, this.maxX, this.maxY]; + if (pathType === PathType.STROKE) { + if (!transform) { + unreachable("Stroke bounding box must include transform."); + } + const scale = Util.singularValueDecompose2dScale(transform); + const xStrokePad = scale[0] * this.lineWidth / 2; + const yStrokePad = scale[1] * this.lineWidth / 2; + box[0] -= xStrokePad; + box[1] -= yStrokePad; + box[2] += xStrokePad; + box[3] += yStrokePad; + } + return box; + } + updateClipFromPath() { + const intersect = Util.intersect(this.clipBox, this.getPathBoundingBox()); + this.startNewPathAndClipBox(intersect || [0, 0, 0, 0]); + } + isEmptyClip() { + return this.minX === Infinity; + } + startNewPathAndClipBox(box) { + this.clipBox = box; + this.minX = Infinity; + this.minY = Infinity; + this.maxX = 0; + this.maxY = 0; + } + getClippedPathBoundingBox(pathType = PathType.FILL, transform = null) { + return Util.intersect(this.clipBox, this.getPathBoundingBox(pathType, transform)); + } +} +function putBinaryImageData(ctx, imgData) { + if (typeof ImageData !== "undefined" && imgData instanceof ImageData) { + ctx.putImageData(imgData, 0, 0); + return; + } + const height = imgData.height, + width = imgData.width; + const partialChunkHeight = height % FULL_CHUNK_HEIGHT; + const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT; + const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1; + const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT); + let srcPos = 0, + destPos; + const src = imgData.data; + const dest = chunkImgData.data; + let i, j, thisChunkHeight, elemsInThisChunk; + if (imgData.kind === util_ImageKind.GRAYSCALE_1BPP) { + const srcLength = src.byteLength; + const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2); + const dest32DataLength = dest32.length; + const fullSrcDiff = width + 7 >> 3; + const white = 0xffffffff; + const black = util_FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff; + for (i = 0; i < totalChunks; i++) { + thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight; + destPos = 0; + for (j = 0; j < thisChunkHeight; j++) { + const srcDiff = srcLength - srcPos; + let k = 0; + const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7; + const kEndUnrolled = kEnd & ~7; + let mask = 0; + let srcByte = 0; + for (; k < kEndUnrolled; k += 8) { + srcByte = src[srcPos++]; + dest32[destPos++] = srcByte & 128 ? white : black; + dest32[destPos++] = srcByte & 64 ? white : black; + dest32[destPos++] = srcByte & 32 ? white : black; + dest32[destPos++] = srcByte & 16 ? white : black; + dest32[destPos++] = srcByte & 8 ? white : black; + dest32[destPos++] = srcByte & 4 ? white : black; + dest32[destPos++] = srcByte & 2 ? white : black; + dest32[destPos++] = srcByte & 1 ? white : black; + } + for (; k < kEnd; k++) { + if (mask === 0) { + srcByte = src[srcPos++]; + mask = 128; + } + dest32[destPos++] = srcByte & mask ? white : black; + mask >>= 1; + } + } + while (destPos < dest32DataLength) { + dest32[destPos++] = 0; + } + ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); + } + } else if (imgData.kind === util_ImageKind.RGBA_32BPP) { + j = 0; + elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4; + for (i = 0; i < fullChunks; i++) { + dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk)); + srcPos += elemsInThisChunk; + ctx.putImageData(chunkImgData, 0, j); + j += FULL_CHUNK_HEIGHT; + } + if (i < totalChunks) { + elemsInThisChunk = width * partialChunkHeight * 4; + dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk)); + ctx.putImageData(chunkImgData, 0, j); + } + } else if (imgData.kind === util_ImageKind.RGB_24BPP) { + thisChunkHeight = FULL_CHUNK_HEIGHT; + elemsInThisChunk = width * thisChunkHeight; + for (i = 0; i < totalChunks; i++) { + if (i >= fullChunks) { + thisChunkHeight = partialChunkHeight; + elemsInThisChunk = width * thisChunkHeight; + } + destPos = 0; + for (j = elemsInThisChunk; j--;) { + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + dest[destPos++] = 255; + } + ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); + } + } else { + throw new Error(`bad image kind: ${imgData.kind}`); + } +} +function putBinaryImageMask(ctx, imgData) { + if (imgData.bitmap) { + ctx.drawImage(imgData.bitmap, 0, 0); + return; + } + const height = imgData.height, + width = imgData.width; + const partialChunkHeight = height % FULL_CHUNK_HEIGHT; + const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT; + const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1; + const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT); + let srcPos = 0; + const src = imgData.data; + const dest = chunkImgData.data; + for (let i = 0; i < totalChunks; i++) { + const thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight; + ({ + srcPos + } = convertBlackAndWhiteToRGBA({ + src, + srcPos, + dest, + width, + height: thisChunkHeight, + nonBlackColor: 0 + })); + ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); + } +} +function copyCtxState(sourceCtx, destCtx) { + const properties = ["strokeStyle", "fillStyle", "fillRule", "globalAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "globalCompositeOperation", "font", "filter"]; + for (const property of properties) { + if (sourceCtx[property] !== undefined) { + destCtx[property] = sourceCtx[property]; + } + } + if (sourceCtx.setLineDash !== undefined) { + destCtx.setLineDash(sourceCtx.getLineDash()); + destCtx.lineDashOffset = sourceCtx.lineDashOffset; + } +} +function resetCtxToDefault(ctx) { + ctx.strokeStyle = ctx.fillStyle = "#000000"; + ctx.fillRule = "nonzero"; + ctx.globalAlpha = 1; + ctx.lineWidth = 1; + ctx.lineCap = "butt"; + ctx.lineJoin = "miter"; + ctx.miterLimit = 10; + ctx.globalCompositeOperation = "source-over"; + ctx.font = "10px sans-serif"; + if (ctx.setLineDash !== undefined) { + ctx.setLineDash([]); + ctx.lineDashOffset = 0; + } + if (!isNodeJS) { + const { + filter + } = ctx; + if (filter !== "none" && filter !== "") { + ctx.filter = "none"; + } + } +} +function getImageSmoothingEnabled(transform, interpolate) { + if (interpolate) { + return true; + } + const scale = Util.singularValueDecompose2dScale(transform); + scale[0] = Math.fround(scale[0]); + scale[1] = Math.fround(scale[1]); + const actualScale = Math.fround((globalThis.devicePixelRatio || 1) * PixelsPerInch.PDF_TO_CSS_UNITS); + return scale[0] <= actualScale && scale[1] <= actualScale; +} +const LINE_CAP_STYLES = ["butt", "round", "square"]; +const LINE_JOIN_STYLES = ["miter", "round", "bevel"]; +const NORMAL_CLIP = {}; +const EO_CLIP = {}; +class CanvasGraphics { + constructor(canvasCtx, commonObjs, objs, canvasFactory, filterFactory, { + optionalContentConfig, + markedContentStack = null + }, annotationCanvasMap, pageColors) { + this.ctx = canvasCtx; + this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height); + this.stateStack = []; + this.pendingClip = null; + this.pendingEOFill = false; + this.res = null; + this.xobjs = null; + this.commonObjs = commonObjs; + this.objs = objs; + this.canvasFactory = canvasFactory; + this.filterFactory = filterFactory; + this.groupStack = []; + this.processingType3 = null; + this.baseTransform = null; + this.baseTransformStack = []; + this.groupLevel = 0; + this.smaskStack = []; + this.smaskCounter = 0; + this.tempSMask = null; + this.suspendedCtx = null; + this.contentVisible = true; + this.markedContentStack = markedContentStack || []; + this.optionalContentConfig = optionalContentConfig; + this.cachedCanvases = new CachedCanvases(this.canvasFactory); + this.cachedPatterns = new Map(); + this.annotationCanvasMap = annotationCanvasMap; + this.viewportScale = 1; + this.outputScaleX = 1; + this.outputScaleY = 1; + this.pageColors = pageColors; + this._cachedScaleForStroking = [-1, 0]; + this._cachedGetSinglePixelWidth = null; + this._cachedBitmapsMap = new Map(); + } + getObject(data, fallback = null) { + if (typeof data === "string") { + return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data); + } + return fallback; + } + beginDrawing({ + transform, + viewport, + transparency = false, + background = null + }) { + const width = this.ctx.canvas.width; + const height = this.ctx.canvas.height; + const savedFillStyle = this.ctx.fillStyle; + this.ctx.fillStyle = background || "#ffffff"; + this.ctx.fillRect(0, 0, width, height); + this.ctx.fillStyle = savedFillStyle; + if (transparency) { + const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height); + this.compositeCtx = this.ctx; + this.transparentCanvas = transparentCanvas.canvas; + this.ctx = transparentCanvas.context; + this.ctx.save(); + this.ctx.transform(...getCurrentTransform(this.compositeCtx)); + } + this.ctx.save(); + resetCtxToDefault(this.ctx); + if (transform) { + this.ctx.transform(...transform); + this.outputScaleX = transform[0]; + this.outputScaleY = transform[0]; + } + this.ctx.transform(...viewport.transform); + this.viewportScale = viewport.scale; + this.baseTransform = getCurrentTransform(this.ctx); + } + executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) { + const argsArray = operatorList.argsArray; + const fnArray = operatorList.fnArray; + let i = executionStartIdx || 0; + const argsArrayLen = argsArray.length; + if (argsArrayLen === i) { + return i; + } + const chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === "function"; + const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0; + let steps = 0; + const commonObjs = this.commonObjs; + const objs = this.objs; + let fnId; + while (true) { + if (stepper !== undefined && i === stepper.nextBreakPoint) { + stepper.breakIt(i, continueCallback); + return i; + } + fnId = fnArray[i]; + if (fnId !== OPS.dependency) { + this[fnId].apply(this, argsArray[i]); + } else { + for (const depObjId of argsArray[i]) { + const objsPool = depObjId.startsWith("g_") ? commonObjs : objs; + if (!objsPool.has(depObjId)) { + objsPool.get(depObjId, continueCallback); + return i; + } + } + } + i++; + if (i === argsArrayLen) { + return i; + } + if (chunkOperations && ++steps > EXECUTION_STEPS) { + if (Date.now() > endTime) { + continueCallback(); + return i; + } + steps = 0; + } + } + } + #restoreInitialState() { + while (this.stateStack.length || this.inSMaskMode) { + this.restore(); + } + this.current.activeSMask = null; + this.ctx.restore(); + if (this.transparentCanvas) { + this.ctx = this.compositeCtx; + this.ctx.save(); + this.ctx.setTransform(1, 0, 0, 1, 0, 0); + this.ctx.drawImage(this.transparentCanvas, 0, 0); + this.ctx.restore(); + this.transparentCanvas = null; + } + } + endDrawing() { + this.#restoreInitialState(); + this.cachedCanvases.clear(); + this.cachedPatterns.clear(); + for (const cache of this._cachedBitmapsMap.values()) { + for (const canvas of cache.values()) { + if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) { + canvas.width = canvas.height = 0; + } + } + cache.clear(); + } + this._cachedBitmapsMap.clear(); + this.#drawFilter(); + } + #drawFilter() { + if (this.pageColors) { + const hcmFilterId = this.filterFactory.addHCMFilter(this.pageColors.foreground, this.pageColors.background); + if (hcmFilterId !== "none") { + const savedFilter = this.ctx.filter; + this.ctx.filter = hcmFilterId; + this.ctx.drawImage(this.ctx.canvas, 0, 0); + this.ctx.filter = savedFilter; + } + } + } + _scaleImage(img, inverseTransform) { + const width = img.width; + const height = img.height; + let widthScale = Math.max(Math.hypot(inverseTransform[0], inverseTransform[1]), 1); + let heightScale = Math.max(Math.hypot(inverseTransform[2], inverseTransform[3]), 1); + let paintWidth = width, + paintHeight = height; + let tmpCanvasId = "prescale1"; + let tmpCanvas, tmpCtx; + while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) { + let newWidth = paintWidth, + newHeight = paintHeight; + if (widthScale > 2 && paintWidth > 1) { + newWidth = paintWidth >= 16384 ? Math.floor(paintWidth / 2) - 1 || 1 : Math.ceil(paintWidth / 2); + widthScale /= paintWidth / newWidth; + } + if (heightScale > 2 && paintHeight > 1) { + newHeight = paintHeight >= 16384 ? Math.floor(paintHeight / 2) - 1 || 1 : Math.ceil(paintHeight) / 2; + heightScale /= paintHeight / newHeight; + } + tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight); + tmpCtx = tmpCanvas.context; + tmpCtx.clearRect(0, 0, newWidth, newHeight); + tmpCtx.drawImage(img, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight); + img = tmpCanvas.canvas; + paintWidth = newWidth; + paintHeight = newHeight; + tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1"; + } + return { + img, + paintWidth, + paintHeight + }; + } + _createMaskCanvas(img) { + const ctx = this.ctx; + const { + width, + height + } = img; + const fillColor = this.current.fillColor; + const isPatternFill = this.current.patternFill; + const currentTransform = getCurrentTransform(ctx); + let cache, cacheKey, scaled, maskCanvas; + if ((img.bitmap || img.data) && img.count > 1) { + const mainKey = img.bitmap || img.data.buffer; + cacheKey = JSON.stringify(isPatternFill ? currentTransform : [currentTransform.slice(0, 4), fillColor]); + cache = this._cachedBitmapsMap.get(mainKey); + if (!cache) { + cache = new Map(); + this._cachedBitmapsMap.set(mainKey, cache); + } + const cachedImage = cache.get(cacheKey); + if (cachedImage && !isPatternFill) { + const offsetX = Math.round(Math.min(currentTransform[0], currentTransform[2]) + currentTransform[4]); + const offsetY = Math.round(Math.min(currentTransform[1], currentTransform[3]) + currentTransform[5]); + return { + canvas: cachedImage, + offsetX, + offsetY + }; + } + scaled = cachedImage; + } + if (!scaled) { + maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height); + putBinaryImageMask(maskCanvas.context, img); + } + let maskToCanvas = Util.transform(currentTransform, [1 / width, 0, 0, -1 / height, 0, 0]); + maskToCanvas = Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]); + const [minX, minY, maxX, maxY] = Util.getAxialAlignedBoundingBox([0, 0, width, height], maskToCanvas); + const drawnWidth = Math.round(maxX - minX) || 1; + const drawnHeight = Math.round(maxY - minY) || 1; + const fillCanvas = this.cachedCanvases.getCanvas("fillCanvas", drawnWidth, drawnHeight); + const fillCtx = fillCanvas.context; + const offsetX = minX; + const offsetY = minY; + fillCtx.translate(-offsetX, -offsetY); + fillCtx.transform(...maskToCanvas); + if (!scaled) { + scaled = this._scaleImage(maskCanvas.canvas, getCurrentTransformInverse(fillCtx)); + scaled = scaled.img; + if (cache && isPatternFill) { + cache.set(cacheKey, scaled); + } + } + fillCtx.imageSmoothingEnabled = getImageSmoothingEnabled(getCurrentTransform(fillCtx), img.interpolate); + drawImageAtIntegerCoords(fillCtx, scaled, 0, 0, scaled.width, scaled.height, 0, 0, width, height); + fillCtx.globalCompositeOperation = "source-in"; + const inverse = Util.transform(getCurrentTransformInverse(fillCtx), [1, 0, 0, 1, -offsetX, -offsetY]); + fillCtx.fillStyle = isPatternFill ? fillColor.getPattern(ctx, this, inverse, PathType.FILL) : fillColor; + fillCtx.fillRect(0, 0, width, height); + if (cache && !isPatternFill) { + this.cachedCanvases.delete("fillCanvas"); + cache.set(cacheKey, fillCanvas.canvas); + } + return { + canvas: fillCanvas.canvas, + offsetX: Math.round(offsetX), + offsetY: Math.round(offsetY) + }; + } + setLineWidth(width) { + if (width !== this.current.lineWidth) { + this._cachedScaleForStroking[0] = -1; + } + this.current.lineWidth = width; + this.ctx.lineWidth = width; + } + setLineCap(style) { + this.ctx.lineCap = LINE_CAP_STYLES[style]; + } + setLineJoin(style) { + this.ctx.lineJoin = LINE_JOIN_STYLES[style]; + } + setMiterLimit(limit) { + this.ctx.miterLimit = limit; + } + setDash(dashArray, dashPhase) { + const ctx = this.ctx; + if (ctx.setLineDash !== undefined) { + ctx.setLineDash(dashArray); + ctx.lineDashOffset = dashPhase; + } + } + setRenderingIntent(intent) {} + setFlatness(flatness) {} + setGState(states) { + for (const [key, value] of states) { + switch (key) { + case "LW": + this.setLineWidth(value); + break; + case "LC": + this.setLineCap(value); + break; + case "LJ": + this.setLineJoin(value); + break; + case "ML": + this.setMiterLimit(value); + break; + case "D": + this.setDash(value[0], value[1]); + break; + case "RI": + this.setRenderingIntent(value); + break; + case "FL": + this.setFlatness(value); + break; + case "Font": + this.setFont(value[0], value[1]); + break; + case "CA": + this.current.strokeAlpha = value; + break; + case "ca": + this.current.fillAlpha = value; + this.ctx.globalAlpha = value; + break; + case "BM": + this.ctx.globalCompositeOperation = value; + break; + case "SMask": + this.current.activeSMask = value ? this.tempSMask : null; + this.tempSMask = null; + this.checkSMaskState(); + break; + case "TR": + this.ctx.filter = this.current.transferMaps = this.filterFactory.addFilter(value); + break; + } + } + } + get inSMaskMode() { + return !!this.suspendedCtx; + } + checkSMaskState() { + const inSMaskMode = this.inSMaskMode; + if (this.current.activeSMask && !inSMaskMode) { + this.beginSMaskMode(); + } else if (!this.current.activeSMask && inSMaskMode) { + this.endSMaskMode(); + } + } + beginSMaskMode() { + if (this.inSMaskMode) { + throw new Error("beginSMaskMode called while already in smask mode"); + } + const drawnWidth = this.ctx.canvas.width; + const drawnHeight = this.ctx.canvas.height; + const cacheId = "smaskGroupAt" + this.groupLevel; + const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight); + this.suspendedCtx = this.ctx; + this.ctx = scratchCanvas.context; + const ctx = this.ctx; + ctx.setTransform(...getCurrentTransform(this.suspendedCtx)); + copyCtxState(this.suspendedCtx, ctx); + mirrorContextOperations(ctx, this.suspendedCtx); + this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]); + } + endSMaskMode() { + if (!this.inSMaskMode) { + throw new Error("endSMaskMode called while not in smask mode"); + } + this.ctx._removeMirroring(); + copyCtxState(this.ctx, this.suspendedCtx); + this.ctx = this.suspendedCtx; + this.suspendedCtx = null; + } + compose(dirtyBox) { + if (!this.current.activeSMask) { + return; + } + if (!dirtyBox) { + dirtyBox = [0, 0, this.ctx.canvas.width, this.ctx.canvas.height]; + } else { + dirtyBox[0] = Math.floor(dirtyBox[0]); + dirtyBox[1] = Math.floor(dirtyBox[1]); + dirtyBox[2] = Math.ceil(dirtyBox[2]); + dirtyBox[3] = Math.ceil(dirtyBox[3]); + } + const smask = this.current.activeSMask; + const suspendedCtx = this.suspendedCtx; + this.composeSMask(suspendedCtx, smask, this.ctx, dirtyBox); + this.ctx.save(); + this.ctx.setTransform(1, 0, 0, 1, 0, 0); + this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height); + this.ctx.restore(); + } + composeSMask(ctx, smask, layerCtx, layerBox) { + const layerOffsetX = layerBox[0]; + const layerOffsetY = layerBox[1]; + const layerWidth = layerBox[2] - layerOffsetX; + const layerHeight = layerBox[3] - layerOffsetY; + if (layerWidth === 0 || layerHeight === 0) { + return; + } + this.genericComposeSMask(smask.context, layerCtx, layerWidth, layerHeight, smask.subtype, smask.backdrop, smask.transferMap, layerOffsetX, layerOffsetY, smask.offsetX, smask.offsetY); + ctx.save(); + ctx.globalAlpha = 1; + ctx.globalCompositeOperation = "source-over"; + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.drawImage(layerCtx.canvas, 0, 0); + ctx.restore(); + } + genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap, layerOffsetX, layerOffsetY, maskOffsetX, maskOffsetY) { + let maskCanvas = maskCtx.canvas; + let maskX = layerOffsetX - maskOffsetX; + let maskY = layerOffsetY - maskOffsetY; + if (backdrop) { + if (maskX < 0 || maskY < 0 || maskX + width > maskCanvas.width || maskY + height > maskCanvas.height) { + const canvas = this.cachedCanvases.getCanvas("maskExtension", width, height); + const ctx = canvas.context; + ctx.drawImage(maskCanvas, -maskX, -maskY); + if (backdrop.some(c => c !== 0)) { + ctx.globalCompositeOperation = "destination-atop"; + ctx.fillStyle = Util.makeHexColor(...backdrop); + ctx.fillRect(0, 0, width, height); + ctx.globalCompositeOperation = "source-over"; + } + maskCanvas = canvas.canvas; + maskX = maskY = 0; + } else if (backdrop.some(c => c !== 0)) { + maskCtx.save(); + maskCtx.globalAlpha = 1; + maskCtx.setTransform(1, 0, 0, 1, 0, 0); + const clip = new Path2D(); + clip.rect(maskX, maskY, width, height); + maskCtx.clip(clip); + maskCtx.globalCompositeOperation = "destination-atop"; + maskCtx.fillStyle = Util.makeHexColor(...backdrop); + maskCtx.fillRect(maskX, maskY, width, height); + maskCtx.restore(); + } + } + layerCtx.save(); + layerCtx.globalAlpha = 1; + layerCtx.setTransform(1, 0, 0, 1, 0, 0); + if (subtype === "Alpha" && transferMap) { + layerCtx.filter = this.filterFactory.addAlphaFilter(transferMap); + } else if (subtype === "Luminosity") { + layerCtx.filter = this.filterFactory.addLuminosityFilter(transferMap); + } + const clip = new Path2D(); + clip.rect(layerOffsetX, layerOffsetY, width, height); + layerCtx.clip(clip); + layerCtx.globalCompositeOperation = "destination-in"; + layerCtx.drawImage(maskCanvas, maskX, maskY, width, height, layerOffsetX, layerOffsetY, width, height); + layerCtx.restore(); + } + save() { + if (this.inSMaskMode) { + copyCtxState(this.ctx, this.suspendedCtx); + this.suspendedCtx.save(); + } else { + this.ctx.save(); + } + const old = this.current; + this.stateStack.push(old); + this.current = old.clone(); + } + restore() { + if (this.stateStack.length === 0 && this.inSMaskMode) { + this.endSMaskMode(); + } + if (this.stateStack.length !== 0) { + this.current = this.stateStack.pop(); + if (this.inSMaskMode) { + this.suspendedCtx.restore(); + copyCtxState(this.suspendedCtx, this.ctx); + } else { + this.ctx.restore(); + } + this.checkSMaskState(); + this.pendingClip = null; + this._cachedScaleForStroking[0] = -1; + this._cachedGetSinglePixelWidth = null; + } + } + transform(a, b, c, d, e, f) { + this.ctx.transform(a, b, c, d, e, f); + this._cachedScaleForStroking[0] = -1; + this._cachedGetSinglePixelWidth = null; + } + constructPath(ops, args, minMax) { + const ctx = this.ctx; + const current = this.current; + let x = current.x, + y = current.y; + let startX, startY; + const currentTransform = getCurrentTransform(ctx); + const isScalingMatrix = currentTransform[0] === 0 && currentTransform[3] === 0 || currentTransform[1] === 0 && currentTransform[2] === 0; + const minMaxForBezier = isScalingMatrix ? minMax.slice(0) : null; + for (let i = 0, j = 0, ii = ops.length; i < ii; i++) { + switch (ops[i] | 0) { + case OPS.rectangle: + x = args[j++]; + y = args[j++]; + const width = args[j++]; + const height = args[j++]; + const xw = x + width; + const yh = y + height; + ctx.moveTo(x, y); + if (width === 0 || height === 0) { + ctx.lineTo(xw, yh); + } else { + ctx.lineTo(xw, y); + ctx.lineTo(xw, yh); + ctx.lineTo(x, yh); + } + if (!isScalingMatrix) { + current.updateRectMinMax(currentTransform, [x, y, xw, yh]); + } + ctx.closePath(); + break; + case OPS.moveTo: + x = args[j++]; + y = args[j++]; + ctx.moveTo(x, y); + if (!isScalingMatrix) { + current.updatePathMinMax(currentTransform, x, y); + } + break; + case OPS.lineTo: + x = args[j++]; + y = args[j++]; + ctx.lineTo(x, y); + if (!isScalingMatrix) { + current.updatePathMinMax(currentTransform, x, y); + } + break; + case OPS.curveTo: + startX = x; + startY = y; + x = args[j + 4]; + y = args[j + 5]; + ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y); + current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], args[j + 2], args[j + 3], x, y, minMaxForBezier); + j += 6; + break; + case OPS.curveTo2: + startX = x; + startY = y; + ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]); + current.updateCurvePathMinMax(currentTransform, startX, startY, x, y, args[j], args[j + 1], args[j + 2], args[j + 3], minMaxForBezier); + x = args[j + 2]; + y = args[j + 3]; + j += 4; + break; + case OPS.curveTo3: + startX = x; + startY = y; + x = args[j + 2]; + y = args[j + 3]; + ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y); + current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], x, y, x, y, minMaxForBezier); + j += 4; + break; + case OPS.closePath: + ctx.closePath(); + break; + } + } + if (isScalingMatrix) { + current.updateScalingPathMinMax(currentTransform, minMaxForBezier); + } + current.setCurrentPoint(x, y); + } + closePath() { + this.ctx.closePath(); + } + stroke(consumePath = true) { + const ctx = this.ctx; + const strokeColor = this.current.strokeColor; + ctx.globalAlpha = this.current.strokeAlpha; + if (this.contentVisible) { + if (typeof strokeColor === "object" && strokeColor?.getPattern) { + ctx.save(); + ctx.strokeStyle = strokeColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.STROKE); + this.rescaleAndStroke(false); + ctx.restore(); + } else { + this.rescaleAndStroke(true); + } + } + if (consumePath) { + this.consumePath(this.current.getClippedPathBoundingBox()); + } + ctx.globalAlpha = this.current.fillAlpha; + } + closeStroke() { + this.closePath(); + this.stroke(); + } + fill(consumePath = true) { + const ctx = this.ctx; + const fillColor = this.current.fillColor; + const isPatternFill = this.current.patternFill; + let needRestore = false; + if (isPatternFill) { + ctx.save(); + ctx.fillStyle = fillColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.FILL); + needRestore = true; + } + const intersect = this.current.getClippedPathBoundingBox(); + if (this.contentVisible && intersect !== null) { + if (this.pendingEOFill) { + ctx.fill("evenodd"); + this.pendingEOFill = false; + } else { + ctx.fill(); + } + } + if (needRestore) { + ctx.restore(); + } + if (consumePath) { + this.consumePath(intersect); + } + } + eoFill() { + this.pendingEOFill = true; + this.fill(); + } + fillStroke() { + this.fill(false); + this.stroke(false); + this.consumePath(); + } + eoFillStroke() { + this.pendingEOFill = true; + this.fillStroke(); + } + closeFillStroke() { + this.closePath(); + this.fillStroke(); + } + closeEOFillStroke() { + this.pendingEOFill = true; + this.closePath(); + this.fillStroke(); + } + endPath() { + this.consumePath(); + } + clip() { + this.pendingClip = NORMAL_CLIP; + } + eoClip() { + this.pendingClip = EO_CLIP; + } + beginText() { + this.current.textMatrix = IDENTITY_MATRIX; + this.current.textMatrixScale = 1; + this.current.x = this.current.lineX = 0; + this.current.y = this.current.lineY = 0; + } + endText() { + const paths = this.pendingTextPaths; + const ctx = this.ctx; + if (paths === undefined) { + ctx.beginPath(); + return; + } + ctx.save(); + ctx.beginPath(); + for (const path of paths) { + ctx.setTransform(...path.transform); + ctx.translate(path.x, path.y); + path.addToPath(ctx, path.fontSize); + } + ctx.restore(); + ctx.clip(); + ctx.beginPath(); + delete this.pendingTextPaths; + } + setCharSpacing(spacing) { + this.current.charSpacing = spacing; + } + setWordSpacing(spacing) { + this.current.wordSpacing = spacing; + } + setHScale(scale) { + this.current.textHScale = scale / 100; + } + setLeading(leading) { + this.current.leading = -leading; + } + setFont(fontRefName, size) { + const fontObj = this.commonObjs.get(fontRefName); + const current = this.current; + if (!fontObj) { + throw new Error(`Can't find font for ${fontRefName}`); + } + current.fontMatrix = fontObj.fontMatrix || FONT_IDENTITY_MATRIX; + if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) { + warn("Invalid font matrix for font " + fontRefName); + } + if (size < 0) { + size = -size; + current.fontDirection = -1; + } else { + current.fontDirection = 1; + } + this.current.font = fontObj; + this.current.fontSize = size; + if (fontObj.isType3Font) { + return; + } + const name = fontObj.loadedName || "sans-serif"; + const typeface = fontObj.systemFontInfo?.css || `"${name}", ${fontObj.fallbackName}`; + let bold = "normal"; + if (fontObj.black) { + bold = "900"; + } else if (fontObj.bold) { + bold = "bold"; + } + const italic = fontObj.italic ? "italic" : "normal"; + let browserFontSize = size; + if (size < MIN_FONT_SIZE) { + browserFontSize = MIN_FONT_SIZE; + } else if (size > MAX_FONT_SIZE) { + browserFontSize = MAX_FONT_SIZE; + } + this.current.fontSizeScale = size / browserFontSize; + this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`; + } + setTextRenderingMode(mode) { + this.current.textRenderingMode = mode; + } + setTextRise(rise) { + this.current.textRise = rise; + } + moveText(x, y) { + this.current.x = this.current.lineX += x; + this.current.y = this.current.lineY += y; + } + setLeadingMoveText(x, y) { + this.setLeading(-y); + this.moveText(x, y); + } + setTextMatrix(a, b, c, d, e, f) { + this.current.textMatrix = [a, b, c, d, e, f]; + this.current.textMatrixScale = Math.hypot(a, b); + this.current.x = this.current.lineX = 0; + this.current.y = this.current.lineY = 0; + } + nextLine() { + this.moveText(0, this.current.leading); + } + paintChar(character, x, y, patternTransform) { + const ctx = this.ctx; + const current = this.current; + const font = current.font; + const textRenderingMode = current.textRenderingMode; + const fontSize = current.fontSize / current.fontSizeScale; + const fillStrokeMode = textRenderingMode & TextRenderingMode.FILL_STROKE_MASK; + const isAddToPathSet = !!(textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG); + const patternFill = current.patternFill && !font.missingFile; + let addToPath; + if (font.disableFontFace || isAddToPathSet || patternFill) { + addToPath = font.getPathGenerator(this.commonObjs, character); + } + if (font.disableFontFace || patternFill) { + ctx.save(); + ctx.translate(x, y); + ctx.beginPath(); + addToPath(ctx, fontSize); + if (patternTransform) { + ctx.setTransform(...patternTransform); + } + if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) { + ctx.fill(); + } + if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { + ctx.stroke(); + } + ctx.restore(); + } else { + if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) { + ctx.fillText(character, x, y); + } + if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { + ctx.strokeText(character, x, y); + } + } + if (isAddToPathSet) { + const paths = this.pendingTextPaths ||= []; + paths.push({ + transform: getCurrentTransform(ctx), + x, + y, + fontSize, + addToPath + }); + } + } + get isFontSubpixelAAEnabled() { + const { + context: ctx + } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10); + ctx.scale(1.5, 1); + ctx.fillText("I", 0, 10); + const data = ctx.getImageData(0, 0, 10, 10).data; + let enabled = false; + for (let i = 3; i < data.length; i += 4) { + if (data[i] > 0 && data[i] < 255) { + enabled = true; + break; + } + } + return shadow(this, "isFontSubpixelAAEnabled", enabled); + } + showText(glyphs) { + const current = this.current; + const font = current.font; + if (font.isType3Font) { + return this.showType3Text(glyphs); + } + const fontSize = current.fontSize; + if (fontSize === 0) { + return undefined; + } + const ctx = this.ctx; + const fontSizeScale = current.fontSizeScale; + const charSpacing = current.charSpacing; + const wordSpacing = current.wordSpacing; + const fontDirection = current.fontDirection; + const textHScale = current.textHScale * fontDirection; + const glyphsLength = glyphs.length; + const vertical = font.vertical; + const spacingDir = vertical ? 1 : -1; + const defaultVMetrics = font.defaultVMetrics; + const widthAdvanceScale = fontSize * current.fontMatrix[0]; + const simpleFillText = current.textRenderingMode === TextRenderingMode.FILL && !font.disableFontFace && !current.patternFill; + ctx.save(); + ctx.transform(...current.textMatrix); + ctx.translate(current.x, current.y + current.textRise); + if (fontDirection > 0) { + ctx.scale(textHScale, -1); + } else { + ctx.scale(textHScale, 1); + } + let patternTransform; + if (current.patternFill) { + ctx.save(); + const pattern = current.fillColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.FILL); + patternTransform = getCurrentTransform(ctx); + ctx.restore(); + ctx.fillStyle = pattern; + } + let lineWidth = current.lineWidth; + const scale = current.textMatrixScale; + if (scale === 0 || lineWidth === 0) { + const fillStrokeMode = current.textRenderingMode & TextRenderingMode.FILL_STROKE_MASK; + if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { + lineWidth = this.getSinglePixelWidth(); + } + } else { + lineWidth /= scale; + } + if (fontSizeScale !== 1.0) { + ctx.scale(fontSizeScale, fontSizeScale); + lineWidth /= fontSizeScale; + } + ctx.lineWidth = lineWidth; + if (font.isInvalidPDFjsFont) { + const chars = []; + let width = 0; + for (const glyph of glyphs) { + chars.push(glyph.unicode); + width += glyph.width; + } + ctx.fillText(chars.join(""), 0, 0); + current.x += width * widthAdvanceScale * textHScale; + ctx.restore(); + this.compose(); + return undefined; + } + let x = 0, + i; + for (i = 0; i < glyphsLength; ++i) { + const glyph = glyphs[i]; + if (typeof glyph === "number") { + x += spacingDir * glyph * fontSize / 1000; + continue; + } + let restoreNeeded = false; + const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing; + const character = glyph.fontChar; + const accent = glyph.accent; + let scaledX, scaledY; + let width = glyph.width; + if (vertical) { + const vmetric = glyph.vmetric || defaultVMetrics; + const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale; + const vy = vmetric[2] * widthAdvanceScale; + width = vmetric ? -vmetric[0] : width; + scaledX = vx / fontSizeScale; + scaledY = (x + vy) / fontSizeScale; + } else { + scaledX = x / fontSizeScale; + scaledY = 0; + } + if (font.remeasure && width > 0) { + const measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale; + if (width < measuredWidth && this.isFontSubpixelAAEnabled) { + const characterScaleX = width / measuredWidth; + restoreNeeded = true; + ctx.save(); + ctx.scale(characterScaleX, 1); + scaledX /= characterScaleX; + } else if (width !== measuredWidth) { + scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale; + } + } + if (this.contentVisible && (glyph.isInFont || font.missingFile)) { + if (simpleFillText && !accent) { + ctx.fillText(character, scaledX, scaledY); + } else { + this.paintChar(character, scaledX, scaledY, patternTransform); + if (accent) { + const scaledAccentX = scaledX + fontSize * accent.offset.x / fontSizeScale; + const scaledAccentY = scaledY - fontSize * accent.offset.y / fontSizeScale; + this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY, patternTransform); + } + } + } + const charWidth = vertical ? width * widthAdvanceScale - spacing * fontDirection : width * widthAdvanceScale + spacing * fontDirection; + x += charWidth; + if (restoreNeeded) { + ctx.restore(); + } + } + if (vertical) { + current.y -= x; + } else { + current.x += x * textHScale; + } + ctx.restore(); + this.compose(); + return undefined; + } + showType3Text(glyphs) { + const ctx = this.ctx; + const current = this.current; + const font = current.font; + const fontSize = current.fontSize; + const fontDirection = current.fontDirection; + const spacingDir = font.vertical ? 1 : -1; + const charSpacing = current.charSpacing; + const wordSpacing = current.wordSpacing; + const textHScale = current.textHScale * fontDirection; + const fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX; + const glyphsLength = glyphs.length; + const isTextInvisible = current.textRenderingMode === TextRenderingMode.INVISIBLE; + let i, glyph, width, spacingLength; + if (isTextInvisible || fontSize === 0) { + return; + } + this._cachedScaleForStroking[0] = -1; + this._cachedGetSinglePixelWidth = null; + ctx.save(); + ctx.transform(...current.textMatrix); + ctx.translate(current.x, current.y); + ctx.scale(textHScale, fontDirection); + for (i = 0; i < glyphsLength; ++i) { + glyph = glyphs[i]; + if (typeof glyph === "number") { + spacingLength = spacingDir * glyph * fontSize / 1000; + this.ctx.translate(spacingLength, 0); + current.x += spacingLength * textHScale; + continue; + } + const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing; + const operatorList = font.charProcOperatorList[glyph.operatorListId]; + if (!operatorList) { + warn(`Type3 character "${glyph.operatorListId}" is not available.`); + continue; + } + if (this.contentVisible) { + this.processingType3 = glyph; + this.save(); + ctx.scale(fontSize, fontSize); + ctx.transform(...fontMatrix); + this.executeOperatorList(operatorList); + this.restore(); + } + const transformed = Util.applyTransform([glyph.width, 0], fontMatrix); + width = transformed[0] * fontSize + spacing; + ctx.translate(width, 0); + current.x += width * textHScale; + } + ctx.restore(); + this.processingType3 = null; + } + setCharWidth(xWidth, yWidth) {} + setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) { + this.ctx.rect(llx, lly, urx - llx, ury - lly); + this.ctx.clip(); + this.endPath(); + } + getColorN_Pattern(IR) { + let pattern; + if (IR[0] === "TilingPattern") { + const color = IR[1]; + const baseTransform = this.baseTransform || getCurrentTransform(this.ctx); + const canvasGraphicsFactory = { + createCanvasGraphics: ctx => new CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, { + optionalContentConfig: this.optionalContentConfig, + markedContentStack: this.markedContentStack + }) + }; + pattern = new TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform); + } else { + pattern = this._getPattern(IR[1], IR[2]); + } + return pattern; + } + setStrokeColorN() { + this.current.strokeColor = this.getColorN_Pattern(arguments); + } + setFillColorN() { + this.current.fillColor = this.getColorN_Pattern(arguments); + this.current.patternFill = true; + } + setStrokeRGBColor(r, g, b) { + this.ctx.strokeStyle = this.current.strokeColor = Util.makeHexColor(r, g, b); + } + setStrokeTransparent() { + this.ctx.strokeStyle = this.current.strokeColor = "transparent"; + } + setFillRGBColor(r, g, b) { + this.ctx.fillStyle = this.current.fillColor = Util.makeHexColor(r, g, b); + this.current.patternFill = false; + } + setFillTransparent() { + this.ctx.fillStyle = this.current.fillColor = "transparent"; + this.current.patternFill = false; + } + _getPattern(objId, matrix = null) { + let pattern; + if (this.cachedPatterns.has(objId)) { + pattern = this.cachedPatterns.get(objId); + } else { + pattern = getShadingPattern(this.getObject(objId)); + this.cachedPatterns.set(objId, pattern); + } + if (matrix) { + pattern.matrix = matrix; + } + return pattern; + } + shadingFill(objId) { + if (!this.contentVisible) { + return; + } + const ctx = this.ctx; + this.save(); + const pattern = this._getPattern(objId); + ctx.fillStyle = pattern.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.SHADING); + const inv = getCurrentTransformInverse(ctx); + if (inv) { + const { + width, + height + } = ctx.canvas; + const [x0, y0, x1, y1] = Util.getAxialAlignedBoundingBox([0, 0, width, height], inv); + this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0); + } else { + this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10); + } + this.compose(this.current.getClippedPathBoundingBox()); + this.restore(); + } + beginInlineImage() { + unreachable("Should not call beginInlineImage"); + } + beginImageData() { + unreachable("Should not call beginImageData"); + } + paintFormXObjectBegin(matrix, bbox) { + if (!this.contentVisible) { + return; + } + this.save(); + this.baseTransformStack.push(this.baseTransform); + if (matrix) { + this.transform(...matrix); + } + this.baseTransform = getCurrentTransform(this.ctx); + if (bbox) { + const width = bbox[2] - bbox[0]; + const height = bbox[3] - bbox[1]; + this.ctx.rect(bbox[0], bbox[1], width, height); + this.current.updateRectMinMax(getCurrentTransform(this.ctx), bbox); + this.clip(); + this.endPath(); + } + } + paintFormXObjectEnd() { + if (!this.contentVisible) { + return; + } + this.restore(); + this.baseTransform = this.baseTransformStack.pop(); + } + beginGroup(group) { + if (!this.contentVisible) { + return; + } + this.save(); + if (this.inSMaskMode) { + this.endSMaskMode(); + this.current.activeSMask = null; + } + const currentCtx = this.ctx; + if (!group.isolated) { + info("TODO: Support non-isolated groups."); + } + if (group.knockout) { + warn("Knockout groups not supported."); + } + const currentTransform = getCurrentTransform(currentCtx); + if (group.matrix) { + currentCtx.transform(...group.matrix); + } + if (!group.bbox) { + throw new Error("Bounding box is required."); + } + let bounds = Util.getAxialAlignedBoundingBox(group.bbox, getCurrentTransform(currentCtx)); + const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height]; + bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0]; + const offsetX = Math.floor(bounds[0]); + const offsetY = Math.floor(bounds[1]); + const drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1); + const drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1); + this.current.startNewPathAndClipBox([0, 0, drawnWidth, drawnHeight]); + let cacheId = "groupAt" + this.groupLevel; + if (group.smask) { + cacheId += "_smask_" + this.smaskCounter++ % 2; + } + const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight); + const groupCtx = scratchCanvas.context; + groupCtx.translate(-offsetX, -offsetY); + groupCtx.transform(...currentTransform); + if (group.smask) { + this.smaskStack.push({ + canvas: scratchCanvas.canvas, + context: groupCtx, + offsetX, + offsetY, + subtype: group.smask.subtype, + backdrop: group.smask.backdrop, + transferMap: group.smask.transferMap || null, + startTransformInverse: null + }); + } else { + currentCtx.setTransform(1, 0, 0, 1, 0, 0); + currentCtx.translate(offsetX, offsetY); + currentCtx.save(); + } + copyCtxState(currentCtx, groupCtx); + this.ctx = groupCtx; + this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]); + this.groupStack.push(currentCtx); + this.groupLevel++; + } + endGroup(group) { + if (!this.contentVisible) { + return; + } + this.groupLevel--; + const groupCtx = this.ctx; + const ctx = this.groupStack.pop(); + this.ctx = ctx; + this.ctx.imageSmoothingEnabled = false; + if (group.smask) { + this.tempSMask = this.smaskStack.pop(); + this.restore(); + } else { + this.ctx.restore(); + const currentMtx = getCurrentTransform(this.ctx); + this.restore(); + this.ctx.save(); + this.ctx.setTransform(...currentMtx); + const dirtyBox = Util.getAxialAlignedBoundingBox([0, 0, groupCtx.canvas.width, groupCtx.canvas.height], currentMtx); + this.ctx.drawImage(groupCtx.canvas, 0, 0); + this.ctx.restore(); + this.compose(dirtyBox); + } + } + beginAnnotation(id, rect, transform, matrix, hasOwnCanvas) { + this.#restoreInitialState(); + resetCtxToDefault(this.ctx); + this.ctx.save(); + this.save(); + if (this.baseTransform) { + this.ctx.setTransform(...this.baseTransform); + } + if (rect) { + const width = rect[2] - rect[0]; + const height = rect[3] - rect[1]; + if (hasOwnCanvas && this.annotationCanvasMap) { + transform = transform.slice(); + transform[4] -= rect[0]; + transform[5] -= rect[1]; + rect = rect.slice(); + rect[0] = rect[1] = 0; + rect[2] = width; + rect[3] = height; + const [scaleX, scaleY] = Util.singularValueDecompose2dScale(getCurrentTransform(this.ctx)); + const { + viewportScale + } = this; + const canvasWidth = Math.ceil(width * this.outputScaleX * viewportScale); + const canvasHeight = Math.ceil(height * this.outputScaleY * viewportScale); + this.annotationCanvas = this.canvasFactory.create(canvasWidth, canvasHeight); + const { + canvas, + context + } = this.annotationCanvas; + this.annotationCanvasMap.set(id, canvas); + this.annotationCanvas.savedCtx = this.ctx; + this.ctx = context; + this.ctx.save(); + this.ctx.setTransform(scaleX, 0, 0, -scaleY, 0, height * scaleY); + resetCtxToDefault(this.ctx); + } else { + resetCtxToDefault(this.ctx); + this.ctx.rect(rect[0], rect[1], width, height); + this.ctx.clip(); + this.endPath(); + } + } + this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height); + this.transform(...transform); + this.transform(...matrix); + } + endAnnotation() { + if (this.annotationCanvas) { + this.ctx.restore(); + this.#drawFilter(); + this.ctx = this.annotationCanvas.savedCtx; + delete this.annotationCanvas.savedCtx; + delete this.annotationCanvas; + } + } + paintImageMaskXObject(img) { + if (!this.contentVisible) { + return; + } + const count = img.count; + img = this.getObject(img.data, img); + img.count = count; + const ctx = this.ctx; + const glyph = this.processingType3; + if (glyph) { + if (glyph.compiled === undefined) { + glyph.compiled = compileType3Glyph(img); + } + if (glyph.compiled) { + glyph.compiled(ctx); + return; + } + } + const mask = this._createMaskCanvas(img); + const maskCanvas = mask.canvas; + ctx.save(); + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY); + ctx.restore(); + this.compose(); + } + paintImageMaskXObjectRepeat(img, scaleX, skewX = 0, skewY = 0, scaleY, positions) { + if (!this.contentVisible) { + return; + } + img = this.getObject(img.data, img); + const ctx = this.ctx; + ctx.save(); + const currentTransform = getCurrentTransform(ctx); + ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0); + const mask = this._createMaskCanvas(img); + ctx.setTransform(1, 0, 0, 1, mask.offsetX - currentTransform[4], mask.offsetY - currentTransform[5]); + for (let i = 0, ii = positions.length; i < ii; i += 2) { + const trans = Util.transform(currentTransform, [scaleX, skewX, skewY, scaleY, positions[i], positions[i + 1]]); + const [x, y] = Util.applyTransform([0, 0], trans); + ctx.drawImage(mask.canvas, x, y); + } + ctx.restore(); + this.compose(); + } + paintImageMaskXObjectGroup(images) { + if (!this.contentVisible) { + return; + } + const ctx = this.ctx; + const fillColor = this.current.fillColor; + const isPatternFill = this.current.patternFill; + for (const image of images) { + const { + data, + width, + height, + transform + } = image; + const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height); + const maskCtx = maskCanvas.context; + maskCtx.save(); + const img = this.getObject(data, image); + putBinaryImageMask(maskCtx, img); + maskCtx.globalCompositeOperation = "source-in"; + maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this, getCurrentTransformInverse(ctx), PathType.FILL) : fillColor; + maskCtx.fillRect(0, 0, width, height); + maskCtx.restore(); + ctx.save(); + ctx.transform(...transform); + ctx.scale(1, -1); + drawImageAtIntegerCoords(ctx, maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1); + ctx.restore(); + } + this.compose(); + } + paintImageXObject(objId) { + if (!this.contentVisible) { + return; + } + const imgData = this.getObject(objId); + if (!imgData) { + warn("Dependent image isn't ready yet"); + return; + } + this.paintInlineImageXObject(imgData); + } + paintImageXObjectRepeat(objId, scaleX, scaleY, positions) { + if (!this.contentVisible) { + return; + } + const imgData = this.getObject(objId); + if (!imgData) { + warn("Dependent image isn't ready yet"); + return; + } + const width = imgData.width; + const height = imgData.height; + const map = []; + for (let i = 0, ii = positions.length; i < ii; i += 2) { + map.push({ + transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]], + x: 0, + y: 0, + w: width, + h: height + }); + } + this.paintInlineImageXObjectGroup(imgData, map); + } + applyTransferMapsToCanvas(ctx) { + if (this.current.transferMaps !== "none") { + ctx.filter = this.current.transferMaps; + ctx.drawImage(ctx.canvas, 0, 0); + ctx.filter = "none"; + } + return ctx.canvas; + } + applyTransferMapsToBitmap(imgData) { + if (this.current.transferMaps === "none") { + return imgData.bitmap; + } + const { + bitmap, + width, + height + } = imgData; + const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height); + const tmpCtx = tmpCanvas.context; + tmpCtx.filter = this.current.transferMaps; + tmpCtx.drawImage(bitmap, 0, 0); + tmpCtx.filter = "none"; + return tmpCanvas.canvas; + } + paintInlineImageXObject(imgData) { + if (!this.contentVisible) { + return; + } + const width = imgData.width; + const height = imgData.height; + const ctx = this.ctx; + this.save(); + if (!isNodeJS) { + const { + filter + } = ctx; + if (filter !== "none" && filter !== "") { + ctx.filter = "none"; + } + } + ctx.scale(1 / width, -1 / height); + let imgToPaint; + if (imgData.bitmap) { + imgToPaint = this.applyTransferMapsToBitmap(imgData); + } else if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) { + imgToPaint = imgData; + } else { + const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height); + const tmpCtx = tmpCanvas.context; + putBinaryImageData(tmpCtx, imgData); + imgToPaint = this.applyTransferMapsToCanvas(tmpCtx); + } + const scaled = this._scaleImage(imgToPaint, getCurrentTransformInverse(ctx)); + ctx.imageSmoothingEnabled = getImageSmoothingEnabled(getCurrentTransform(ctx), imgData.interpolate); + drawImageAtIntegerCoords(ctx, scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height); + this.compose(); + this.restore(); + } + paintInlineImageXObjectGroup(imgData, map) { + if (!this.contentVisible) { + return; + } + const ctx = this.ctx; + let imgToPaint; + if (imgData.bitmap) { + imgToPaint = imgData.bitmap; + } else { + const w = imgData.width; + const h = imgData.height; + const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h); + const tmpCtx = tmpCanvas.context; + putBinaryImageData(tmpCtx, imgData); + imgToPaint = this.applyTransferMapsToCanvas(tmpCtx); + } + for (const entry of map) { + ctx.save(); + ctx.transform(...entry.transform); + ctx.scale(1, -1); + drawImageAtIntegerCoords(ctx, imgToPaint, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1); + ctx.restore(); + } + this.compose(); + } + paintSolidColorImageMask() { + if (!this.contentVisible) { + return; + } + this.ctx.fillRect(0, 0, 1, 1); + this.compose(); + } + markPoint(tag) {} + markPointProps(tag, properties) {} + beginMarkedContent(tag) { + this.markedContentStack.push({ + visible: true + }); + } + beginMarkedContentProps(tag, properties) { + if (tag === "OC") { + this.markedContentStack.push({ + visible: this.optionalContentConfig.isVisible(properties) + }); + } else { + this.markedContentStack.push({ + visible: true + }); + } + this.contentVisible = this.isContentVisible(); + } + endMarkedContent() { + this.markedContentStack.pop(); + this.contentVisible = this.isContentVisible(); + } + beginCompat() {} + endCompat() {} + consumePath(clipBox) { + const isEmpty = this.current.isEmptyClip(); + if (this.pendingClip) { + this.current.updateClipFromPath(); + } + if (!this.pendingClip) { + this.compose(clipBox); + } + const ctx = this.ctx; + if (this.pendingClip) { + if (!isEmpty) { + if (this.pendingClip === EO_CLIP) { + ctx.clip("evenodd"); + } else { + ctx.clip(); + } + } + this.pendingClip = null; + } + this.current.startNewPathAndClipBox(this.current.clipBox); + ctx.beginPath(); + } + getSinglePixelWidth() { + if (!this._cachedGetSinglePixelWidth) { + const m = getCurrentTransform(this.ctx); + if (m[1] === 0 && m[2] === 0) { + this._cachedGetSinglePixelWidth = 1 / Math.min(Math.abs(m[0]), Math.abs(m[3])); + } else { + const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]); + const normX = Math.hypot(m[0], m[2]); + const normY = Math.hypot(m[1], m[3]); + this._cachedGetSinglePixelWidth = Math.max(normX, normY) / absDet; + } + } + return this._cachedGetSinglePixelWidth; + } + getScaleForStroking() { + if (this._cachedScaleForStroking[0] === -1) { + const { + lineWidth + } = this.current; + const { + a, + b, + c, + d + } = this.ctx.getTransform(); + let scaleX, scaleY; + if (b === 0 && c === 0) { + const normX = Math.abs(a); + const normY = Math.abs(d); + if (normX === normY) { + if (lineWidth === 0) { + scaleX = scaleY = 1 / normX; + } else { + const scaledLineWidth = normX * lineWidth; + scaleX = scaleY = scaledLineWidth < 1 ? 1 / scaledLineWidth : 1; + } + } else if (lineWidth === 0) { + scaleX = 1 / normX; + scaleY = 1 / normY; + } else { + const scaledXLineWidth = normX * lineWidth; + const scaledYLineWidth = normY * lineWidth; + scaleX = scaledXLineWidth < 1 ? 1 / scaledXLineWidth : 1; + scaleY = scaledYLineWidth < 1 ? 1 / scaledYLineWidth : 1; + } + } else { + const absDet = Math.abs(a * d - b * c); + const normX = Math.hypot(a, b); + const normY = Math.hypot(c, d); + if (lineWidth === 0) { + scaleX = normY / absDet; + scaleY = normX / absDet; + } else { + const baseArea = lineWidth * absDet; + scaleX = normY > baseArea ? normY / baseArea : 1; + scaleY = normX > baseArea ? normX / baseArea : 1; + } + } + this._cachedScaleForStroking[0] = scaleX; + this._cachedScaleForStroking[1] = scaleY; + } + return this._cachedScaleForStroking; + } + rescaleAndStroke(saveRestore) { + const { + ctx + } = this; + const { + lineWidth + } = this.current; + const [scaleX, scaleY] = this.getScaleForStroking(); + ctx.lineWidth = lineWidth || 1; + if (scaleX === 1 && scaleY === 1) { + ctx.stroke(); + return; + } + const dashes = ctx.getLineDash(); + if (saveRestore) { + ctx.save(); + } + ctx.scale(scaleX, scaleY); + if (dashes.length > 0) { + const scale = Math.max(scaleX, scaleY); + ctx.setLineDash(dashes.map(x => x / scale)); + ctx.lineDashOffset /= scale; + } + ctx.stroke(); + if (saveRestore) { + ctx.restore(); + } + } + isContentVisible() { + for (let i = this.markedContentStack.length - 1; i >= 0; i--) { + if (!this.markedContentStack[i].visible) { + return false; + } + } + return true; + } +} +for (const op in OPS) { + if (CanvasGraphics.prototype[op] !== undefined) { + CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op]; + } +} +;// CONCATENATED MODULE: ./src/display/worker_options.js +class GlobalWorkerOptions { + static #port = null; + static #src = ""; + static get workerPort() { + return this.#port; + } + static set workerPort(val) { + if (!(typeof Worker !== "undefined" && val instanceof Worker) && val !== null) { + throw new Error("Invalid `workerPort` type."); + } + this.#port = val; + } + static get workerSrc() { + return this.#src; + } + static set workerSrc(val) { + if (typeof val !== "string") { + throw new Error("Invalid `workerSrc` type."); + } + this.#src = val; + } +} +;// CONCATENATED MODULE: ./src/shared/message_handler.js -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.MessageHandler = void 0; -var _util = __w_pdfjs_require__(1); const CallbackKind = { UNKNOWN: 0, DATA: 1, @@ -9094,21 +8492,21 @@ const StreamKind = { }; function wrapReason(reason) { if (!(reason instanceof Error || typeof reason === "object" && reason !== null)) { - (0, _util.unreachable)('wrapReason: Expected "reason" to be a (possibly cloned) Error.'); + unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.'); } switch (reason.name) { case "AbortException": - return new _util.AbortException(reason.message); + return new AbortException(reason.message); case "MissingPDFException": - return new _util.MissingPDFException(reason.message); + return new MissingPDFException(reason.message); case "PasswordException": - return new _util.PasswordException(reason.message, reason.code); + return new PasswordException(reason.message, reason.code); case "UnexpectedResponseException": - return new _util.UnexpectedResponseException(reason.message, reason.status); + return new UnexpectedResponseException(reason.message, reason.status); case "UnknownErrorException": - return new _util.UnknownErrorException(reason.message, reason.details); + return new UnknownErrorException(reason.message, reason.details); default: - return new _util.UnknownErrorException(reason.message, reason.toString()); + return new UnknownErrorException(reason.message, reason.toString()); } } class MessageHandler { @@ -9200,7 +8598,7 @@ class MessageHandler { } sendWithPromise(actionName, data, transfers) { const callbackId = this.callbackId++; - const capability = new _util.PromiseCapability(); + const capability = Promise.withResolvers(); this.callbackCapabilities[callbackId] = capability; try { this.comObj.postMessage({ @@ -9222,7 +8620,7 @@ class MessageHandler { comObj = this.comObj; return new ReadableStream({ start: controller => { - const startCapability = new _util.PromiseCapability(); + const startCapability = Promise.withResolvers(); this.streamControllers[streamId] = { controller, startCall: startCapability, @@ -9241,7 +8639,7 @@ class MessageHandler { return startCapability.promise; }, pull: controller => { - const pullCapability = new _util.PromiseCapability(); + const pullCapability = Promise.withResolvers(); this.streamControllers[streamId].pullCall = pullCapability; comObj.postMessage({ sourceName, @@ -9253,8 +8651,8 @@ class MessageHandler { return pullCapability.promise; }, cancel: reason => { - (0, _util.assert)(reason instanceof Error, "cancel must have a valid reason"); - const cancelCapability = new _util.PromiseCapability(); + assert(reason instanceof Error, "cancel must have a valid reason"); + const cancelCapability = Promise.withResolvers(); this.streamControllers[streamId].cancelCall = cancelCapability; this.streamControllers[streamId].isClosed = true; comObj.postMessage({ @@ -9283,7 +8681,7 @@ class MessageHandler { const lastDesiredSize = this.desiredSize; this.desiredSize -= size; if (lastDesiredSize > 0 && this.desiredSize <= 0) { - this.sinkCapability = new _util.PromiseCapability(); + this.sinkCapability = Promise.withResolvers(); this.ready = this.sinkCapability.promise; } comObj.postMessage({ @@ -9308,7 +8706,7 @@ class MessageHandler { delete self.streamSinks[streamId]; }, error(reason) { - (0, _util.assert)(reason instanceof Error, "error must have a valid reason"); + assert(reason instanceof Error, "error must have a valid reason"); if (this.isCancelled) { return; } @@ -9321,7 +8719,7 @@ class MessageHandler { reason: wrapReason(reason) }); }, - sinkCapability: new _util.PromiseCapability(), + sinkCapability: Promise.withResolvers(), onPull: null, onCancel: null, isCancelled: false, @@ -9409,14 +8807,14 @@ class MessageHandler { }); break; case StreamKind.ENQUEUE: - (0, _util.assert)(streamController, "enqueue should have stream controller"); + assert(streamController, "enqueue should have stream controller"); if (streamController.isClosed) { break; } streamController.controller.enqueue(data.chunk); break; case StreamKind.CLOSE: - (0, _util.assert)(streamController, "close should have stream controller"); + assert(streamController, "close should have stream controller"); if (streamController.isClosed) { break; } @@ -9425,7 +8823,7 @@ class MessageHandler { this.#deleteStreamController(streamController, streamId); break; case StreamKind.ERROR: - (0, _util.assert)(streamController, "error should have stream controller"); + assert(streamController, "error should have stream controller"); streamController.controller.error(wrapReason(data.reason)); this.#deleteStreamController(streamController, streamId); break; @@ -9476,19 +8874,9 @@ class MessageHandler { this.comObj.removeEventListener("message", this._onComObjOnMessage); } } -exports.MessageHandler = MessageHandler; -/***/ }), -/* 16 */ -/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { +;// CONCATENATED MODULE: ./src/display/metadata.js - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.Metadata = void 0; -var _util = __w_pdfjs_require__(1); class Metadata { #metadataMap; #data; @@ -9506,40 +8894,56 @@ class Metadata { return this.#metadataMap.get(name) ?? null; } getAll() { - return (0, _util.objectFromMap)(this.#metadataMap); + return objectFromMap(this.#metadataMap); } has(name) { return this.#metadataMap.has(name); } } -exports.Metadata = Metadata; -/***/ }), -/* 17 */ -/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { +;// CONCATENATED MODULE: ./src/display/optional_content_config.js - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.OptionalContentConfig = void 0; -var _util = __w_pdfjs_require__(1); -var _murmurhash = __w_pdfjs_require__(8); const INTERNAL = Symbol("INTERNAL"); class OptionalContentGroup { + #isDisplay = false; + #isPrint = false; + #userSet = false; #visible = true; - constructor(name, intent) { + constructor(renderingIntent, { + name, + intent, + usage + }) { + this.#isDisplay = !!(renderingIntent & RenderingIntentFlag.DISPLAY); + this.#isPrint = !!(renderingIntent & RenderingIntentFlag.PRINT); this.name = name; this.intent = intent; + this.usage = usage; } get visible() { - return this.#visible; - } - _setVisible(internal, visible) { - if (internal !== INTERNAL) { - (0, _util.unreachable)("Internal method `_setVisible` called."); + if (this.#userSet) { + return this.#visible; } + if (!this.#visible) { + return false; + } + const { + print, + view + } = this.usage; + if (this.#isDisplay) { + return view?.viewState !== "OFF"; + } else if (this.#isPrint) { + return print?.printState !== "OFF"; + } + return true; + } + _setVisible(internal, visible, userSet = false) { + if (internal !== INTERNAL) { + unreachable("Internal method `_setVisible` called."); + } + this.#userSet = userSet; this.#visible = visible; } } @@ -9548,7 +8952,8 @@ class OptionalContentConfig { #groups = new Map(); #initialHash = null; #order = null; - constructor(data) { + constructor(data, renderingIntent = RenderingIntentFlag.DISPLAY) { + this.renderingIntent = renderingIntent; this.name = null; this.creator = null; if (data === null) { @@ -9558,7 +8963,7 @@ class OptionalContentConfig { this.creator = data.creator; this.#order = data.order; for (const group of data.groups) { - this.#groups.set(group.id, new OptionalContentGroup(group.name, group.intent)); + this.#groups.set(group.id, new OptionalContentGroup(renderingIntent, group)); } if (data.baseState === "OFF") { for (const group of this.#groups.values()) { @@ -9587,7 +8992,7 @@ class OptionalContentConfig { } else if (this.#groups.has(element)) { state = this.#groups.get(element).visible; } else { - (0, _util.warn)(`Optional content group not found: ${element}`); + warn(`Optional content group not found: ${element}`); return true; } switch (operator) { @@ -9614,12 +9019,12 @@ class OptionalContentConfig { return true; } if (!group) { - (0, _util.warn)("Optional content group not defined."); + info("Optional content group not defined."); return true; } if (group.type === "OCG") { if (!this.#groups.has(group.id)) { - (0, _util.warn)(`Optional content group not found: ${group.id}`); + warn(`Optional content group not found: ${group.id}`); return true; } return this.#groups.get(group.id).visible; @@ -9630,7 +9035,7 @@ class OptionalContentConfig { if (!group.policy || group.policy === "AnyOn") { for (const id of group.ids) { if (!this.#groups.has(id)) { - (0, _util.warn)(`Optional content group not found: ${id}`); + warn(`Optional content group not found: ${id}`); return true; } if (this.#groups.get(id).visible) { @@ -9641,7 +9046,7 @@ class OptionalContentConfig { } else if (group.policy === "AllOn") { for (const id of group.ids) { if (!this.#groups.has(id)) { - (0, _util.warn)(`Optional content group not found: ${id}`); + warn(`Optional content group not found: ${id}`); return true; } if (!this.#groups.get(id).visible) { @@ -9652,7 +9057,7 @@ class OptionalContentConfig { } else if (group.policy === "AnyOff") { for (const id of group.ids) { if (!this.#groups.has(id)) { - (0, _util.warn)(`Optional content group not found: ${id}`); + warn(`Optional content group not found: ${id}`); return true; } if (!this.#groups.get(id).visible) { @@ -9663,7 +9068,7 @@ class OptionalContentConfig { } else if (group.policy === "AllOff") { for (const id of group.ids) { if (!this.#groups.has(id)) { - (0, _util.warn)(`Optional content group not found: ${id}`); + warn(`Optional content group not found: ${id}`); return true; } if (this.#groups.get(id).visible) { @@ -9672,18 +9077,50 @@ class OptionalContentConfig { } return true; } - (0, _util.warn)(`Unknown optional content policy ${group.policy}.`); + warn(`Unknown optional content policy ${group.policy}.`); return true; } - (0, _util.warn)(`Unknown group type ${group.type}.`); + warn(`Unknown group type ${group.type}.`); return true; } setVisibility(id, visible = true) { - if (!this.#groups.has(id)) { - (0, _util.warn)(`Optional content group not found: ${id}`); + const group = this.#groups.get(id); + if (!group) { + warn(`Optional content group not found: ${id}`); return; } - this.#groups.get(id)._setVisible(INTERNAL, !!visible); + group._setVisible(INTERNAL, !!visible, true); + this.#cachedGetHash = null; + } + setOCGState({ + state, + preserveRB + }) { + let operator; + for (const elem of state) { + switch (elem) { + case "ON": + case "OFF": + case "Toggle": + operator = elem; + continue; + } + const group = this.#groups.get(elem); + if (!group) { + continue; + } + switch (operator) { + case "ON": + group._setVisible(INTERNAL, true); + break; + case "OFF": + group._setVisible(INTERNAL, false); + break; + case "Toggle": + group._setVisible(INTERNAL, !group.visible); + break; + } + } this.#cachedGetHash = null; } get hasInitialVisibility() { @@ -9699,7 +9136,7 @@ class OptionalContentConfig { return [...this.#groups.keys()]; } getGroups() { - return this.#groups.size > 0 ? (0, _util.objectFromMap)(this.#groups) : null; + return this.#groups.size > 0 ? objectFromMap(this.#groups) : null; } getGroup(id) { return this.#groups.get(id) || null; @@ -9708,37 +9145,29 @@ class OptionalContentConfig { if (this.#cachedGetHash !== null) { return this.#cachedGetHash; } - const hash = new _murmurhash.MurmurHash3_64(); + const hash = new MurmurHash3_64(); for (const [id, group] of this.#groups) { hash.update(`${id}:${group.visible}`); } return this.#cachedGetHash = hash.hexdigest(); } } -exports.OptionalContentConfig = OptionalContentConfig; -/***/ }), -/* 18 */ -/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { +;// CONCATENATED MODULE: ./src/display/transport_stream.js - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.PDFDataTransportStream = void 0; -var _util = __w_pdfjs_require__(1); -var _display_utils = __w_pdfjs_require__(6); class PDFDataTransportStream { - constructor({ - length, - initialData, - progressiveDone = false, - contentDispositionFilename = null, + constructor(pdfDataRangeTransport, { disableRange = false, disableStream = false - }, pdfDataRangeTransport) { - (0, _util.assert)(pdfDataRangeTransport, 'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.'); + }) { + assert(pdfDataRangeTransport, 'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.'); + const { + length, + initialData, + progressiveDone, + contentDispositionFilename + } = pdfDataRangeTransport; this._queuedChunks = []; this._progressiveDone = progressiveDone; this._contentDispositionFilename = contentDispositionFilename; @@ -9752,27 +9181,27 @@ class PDFDataTransportStream { this._contentLength = length; this._fullRequestReader = null; this._rangeReaders = []; - this._pdfDataRangeTransport.addRangeListener((begin, chunk) => { + pdfDataRangeTransport.addRangeListener((begin, chunk) => { this._onReceiveData({ begin, chunk }); }); - this._pdfDataRangeTransport.addProgressListener((loaded, total) => { + pdfDataRangeTransport.addProgressListener((loaded, total) => { this._onProgress({ loaded, total }); }); - this._pdfDataRangeTransport.addProgressiveReadListener(chunk => { + pdfDataRangeTransport.addProgressiveReadListener(chunk => { this._onReceiveData({ chunk }); }); - this._pdfDataRangeTransport.addProgressiveDoneListener(() => { + pdfDataRangeTransport.addProgressiveDoneListener(() => { this._onProgressiveDone(); }); - this._pdfDataRangeTransport.transportReady(); + pdfDataRangeTransport.transportReady(); } _onReceiveData({ begin, @@ -9793,7 +9222,7 @@ class PDFDataTransportStream { rangeReader._enqueue(buffer); return true; }); - (0, _util.assert)(found, "_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found."); + assert(found, "_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found."); } } get _progressiveDataLength() { @@ -9822,7 +9251,7 @@ class PDFDataTransportStream { } } getFullReader() { - (0, _util.assert)(!this._fullRequestReader, "PDFDataTransportStream.getFullReader can only be called once."); + assert(!this._fullRequestReader, "PDFDataTransportStream.getFullReader can only be called once."); const queuedChunks = this._queuedChunks; this._queuedChunks = null; return new PDFDataTransportStreamReader(this, queuedChunks, this._progressiveDone, this._contentDispositionFilename); @@ -9844,12 +9273,11 @@ class PDFDataTransportStream { this._pdfDataRangeTransport.abort(); } } -exports.PDFDataTransportStream = PDFDataTransportStream; class PDFDataTransportStreamReader { constructor(stream, queuedChunks, progressiveDone = false, contentDispositionFilename = null) { this._stream = stream; this._done = progressiveDone || false; - this._filename = (0, _display_utils.isPdfFile)(contentDispositionFilename) ? contentDispositionFilename : null; + this._filename = isPdfFile(contentDispositionFilename) ? contentDispositionFilename : null; this._queuedChunks = queuedChunks || []; this._loaded = 0; for (const chunk of this._queuedChunks) { @@ -9904,7 +9332,7 @@ class PDFDataTransportStreamReader { done: true }; } - const requestCapability = new _util.PromiseCapability(); + const requestCapability = Promise.withResolvers(); this._requests.push(requestCapability); return requestCapability.promise; } @@ -9976,7 +9404,7 @@ class PDFDataTransportStreamRangeReader { done: true }; } - const requestCapability = new _util.PromiseCapability(); + const requestCapability = Promise.withResolvers(); this._requests.push(requestCapability); return requestCapability.promise; } @@ -9993,306 +9421,8 @@ class PDFDataTransportStreamRangeReader { } } -/***/ }), -/* 19 */ -/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { +;// CONCATENATED MODULE: ./src/display/content_disposition.js - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.PDFFetchStream = void 0; -var _util = __w_pdfjs_require__(1); -var _network_utils = __w_pdfjs_require__(20); -; -function createFetchOptions(headers, withCredentials, abortController) { - return { - method: "GET", - headers, - signal: abortController.signal, - mode: "cors", - credentials: withCredentials ? "include" : "same-origin", - redirect: "follow" - }; -} -function createHeaders(httpHeaders) { - const headers = new Headers(); - for (const property in httpHeaders) { - const value = httpHeaders[property]; - if (value === undefined) { - continue; - } - headers.append(property, value); - } - return headers; -} -function getArrayBuffer(val) { - if (val instanceof Uint8Array) { - return val.buffer; - } - if (val instanceof ArrayBuffer) { - return val; - } - (0, _util.warn)(`getArrayBuffer - unexpected data format: ${val}`); - return new Uint8Array(val).buffer; -} -class PDFFetchStream { - constructor(source) { - this.source = source; - this.isHttp = /^https?:/i.test(source.url); - this.httpHeaders = this.isHttp && source.httpHeaders || {}; - this._fullRequestReader = null; - this._rangeRequestReaders = []; - } - get _progressiveDataLength() { - return this._fullRequestReader?._loaded ?? 0; - } - getFullReader() { - (0, _util.assert)(!this._fullRequestReader, "PDFFetchStream.getFullReader can only be called once."); - this._fullRequestReader = new PDFFetchStreamReader(this); - return this._fullRequestReader; - } - getRangeReader(begin, end) { - if (end <= this._progressiveDataLength) { - return null; - } - const reader = new PDFFetchStreamRangeReader(this, begin, end); - this._rangeRequestReaders.push(reader); - return reader; - } - cancelAllRequests(reason) { - this._fullRequestReader?.cancel(reason); - for (const reader of this._rangeRequestReaders.slice(0)) { - reader.cancel(reason); - } - } -} -exports.PDFFetchStream = PDFFetchStream; -class PDFFetchStreamReader { - constructor(stream) { - this._stream = stream; - this._reader = null; - this._loaded = 0; - this._filename = null; - const source = stream.source; - this._withCredentials = source.withCredentials || false; - this._contentLength = source.length; - this._headersCapability = new _util.PromiseCapability(); - this._disableRange = source.disableRange || false; - this._rangeChunkSize = source.rangeChunkSize; - if (!this._rangeChunkSize && !this._disableRange) { - this._disableRange = true; - } - this._abortController = new AbortController(); - this._isStreamingSupported = !source.disableStream; - this._isRangeSupported = !source.disableRange; - this._headers = createHeaders(this._stream.httpHeaders); - const url = source.url; - fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => { - if (!(0, _network_utils.validateResponseStatus)(response.status)) { - throw (0, _network_utils.createResponseStatusError)(response.status, url); - } - this._reader = response.body.getReader(); - this._headersCapability.resolve(); - const getResponseHeader = name => { - return response.headers.get(name); - }; - const { - allowRangeRequests, - suggestedLength - } = (0, _network_utils.validateRangeRequestCapabilities)({ - getResponseHeader, - isHttp: this._stream.isHttp, - rangeChunkSize: this._rangeChunkSize, - disableRange: this._disableRange - }); - this._isRangeSupported = allowRangeRequests; - this._contentLength = suggestedLength || this._contentLength; - this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader); - if (!this._isStreamingSupported && this._isRangeSupported) { - this.cancel(new _util.AbortException("Streaming is disabled.")); - } - }).catch(this._headersCapability.reject); - this.onProgress = null; - } - get headersReady() { - return this._headersCapability.promise; - } - get filename() { - return this._filename; - } - get contentLength() { - return this._contentLength; - } - get isRangeSupported() { - return this._isRangeSupported; - } - get isStreamingSupported() { - return this._isStreamingSupported; - } - async read() { - await this._headersCapability.promise; - const { - value, - done - } = await this._reader.read(); - if (done) { - return { - value, - done - }; - } - this._loaded += value.byteLength; - this.onProgress?.({ - loaded: this._loaded, - total: this._contentLength - }); - return { - value: getArrayBuffer(value), - done: false - }; - } - cancel(reason) { - this._reader?.cancel(reason); - this._abortController.abort(); - } -} -class PDFFetchStreamRangeReader { - constructor(stream, begin, end) { - this._stream = stream; - this._reader = null; - this._loaded = 0; - const source = stream.source; - this._withCredentials = source.withCredentials || false; - this._readCapability = new _util.PromiseCapability(); - this._isStreamingSupported = !source.disableStream; - this._abortController = new AbortController(); - this._headers = createHeaders(this._stream.httpHeaders); - this._headers.append("Range", `bytes=${begin}-${end - 1}`); - const url = source.url; - fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => { - if (!(0, _network_utils.validateResponseStatus)(response.status)) { - throw (0, _network_utils.createResponseStatusError)(response.status, url); - } - this._readCapability.resolve(); - this._reader = response.body.getReader(); - }).catch(this._readCapability.reject); - this.onProgress = null; - } - get isStreamingSupported() { - return this._isStreamingSupported; - } - async read() { - await this._readCapability.promise; - const { - value, - done - } = await this._reader.read(); - if (done) { - return { - value, - done - }; - } - this._loaded += value.byteLength; - this.onProgress?.({ - loaded: this._loaded - }); - return { - value: getArrayBuffer(value), - done: false - }; - } - cancel(reason) { - this._reader?.cancel(reason); - this._abortController.abort(); - } -} - -/***/ }), -/* 20 */ -/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.createResponseStatusError = createResponseStatusError; -exports.extractFilenameFromHeader = extractFilenameFromHeader; -exports.validateRangeRequestCapabilities = validateRangeRequestCapabilities; -exports.validateResponseStatus = validateResponseStatus; -var _util = __w_pdfjs_require__(1); -var _content_disposition = __w_pdfjs_require__(21); -var _display_utils = __w_pdfjs_require__(6); -function validateRangeRequestCapabilities({ - getResponseHeader, - isHttp, - rangeChunkSize, - disableRange -}) { - const returnValues = { - allowRangeRequests: false, - suggestedLength: undefined - }; - const length = parseInt(getResponseHeader("Content-Length"), 10); - if (!Number.isInteger(length)) { - return returnValues; - } - returnValues.suggestedLength = length; - if (length <= 2 * rangeChunkSize) { - return returnValues; - } - if (disableRange || !isHttp) { - return returnValues; - } - if (getResponseHeader("Accept-Ranges") !== "bytes") { - return returnValues; - } - const contentEncoding = getResponseHeader("Content-Encoding") || "identity"; - if (contentEncoding !== "identity") { - return returnValues; - } - returnValues.allowRangeRequests = true; - return returnValues; -} -function extractFilenameFromHeader(getResponseHeader) { - const contentDisposition = getResponseHeader("Content-Disposition"); - if (contentDisposition) { - let filename = (0, _content_disposition.getFilenameFromContentDispositionHeader)(contentDisposition); - if (filename.includes("%")) { - try { - filename = decodeURIComponent(filename); - } catch {} - } - if ((0, _display_utils.isPdfFile)(filename)) { - return filename; - } - } - return null; -} -function createResponseStatusError(status, url) { - if (status === 404 || status === 0 && url.startsWith("file:")) { - return new _util.MissingPDFException('Missing PDF "' + url + '".'); - } - return new _util.UnexpectedResponseException(`Unexpected server response (${status}) while retrieving PDF "${url}".`, status); -} -function validateResponseStatus(status) { - return status === 200 || status === 206; -} - -/***/ }), -/* 21 */ -/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.getFilenameFromContentDispositionHeader = getFilenameFromContentDispositionHeader; -var _util = __w_pdfjs_require__(1); function getFilenameFromContentDispositionHeader(contentDisposition) { let needsEncodingFixup = true; let tmp = toParamRegExp("filename\\*", "i").exec(contentDisposition); @@ -10328,7 +9458,7 @@ function getFilenameFromContentDispositionHeader(contentDisposition) { const decoder = new TextDecoder(encoding, { fatal: true }); - const buffer = (0, _util.stringToBytes)(value); + const buffer = stringToBytes(value); value = decoder.decode(buffer); needsEncodingFixup = false; } catch {} @@ -10422,27 +9552,281 @@ function getFilenameFromContentDispositionHeader(contentDisposition) { return ""; } -/***/ }), -/* 22 */ -/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { +;// CONCATENATED MODULE: ./src/display/network_utils.js -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.PDFNetworkStream = void 0; -var _util = __w_pdfjs_require__(1); -var _network_utils = __w_pdfjs_require__(20); -; +function validateRangeRequestCapabilities({ + getResponseHeader, + isHttp, + rangeChunkSize, + disableRange +}) { + const returnValues = { + allowRangeRequests: false, + suggestedLength: undefined + }; + const length = parseInt(getResponseHeader("Content-Length"), 10); + if (!Number.isInteger(length)) { + return returnValues; + } + returnValues.suggestedLength = length; + if (length <= 2 * rangeChunkSize) { + return returnValues; + } + if (disableRange || !isHttp) { + return returnValues; + } + if (getResponseHeader("Accept-Ranges") !== "bytes") { + return returnValues; + } + const contentEncoding = getResponseHeader("Content-Encoding") || "identity"; + if (contentEncoding !== "identity") { + return returnValues; + } + returnValues.allowRangeRequests = true; + return returnValues; +} +function extractFilenameFromHeader(getResponseHeader) { + const contentDisposition = getResponseHeader("Content-Disposition"); + if (contentDisposition) { + let filename = getFilenameFromContentDispositionHeader(contentDisposition); + if (filename.includes("%")) { + try { + filename = decodeURIComponent(filename); + } catch {} + } + if (isPdfFile(filename)) { + return filename; + } + } + return null; +} +function createResponseStatusError(status, url) { + if (status === 404 || status === 0 && url.startsWith("file:")) { + return new MissingPDFException('Missing PDF "' + url + '".'); + } + return new UnexpectedResponseException(`Unexpected server response (${status}) while retrieving PDF "${url}".`, status); +} +function validateResponseStatus(status) { + return status === 200 || status === 206; +} + +;// CONCATENATED MODULE: ./src/display/fetch_stream.js + + +function createFetchOptions(headers, withCredentials, abortController) { + return { + method: "GET", + headers, + signal: abortController.signal, + mode: "cors", + credentials: withCredentials ? "include" : "same-origin", + redirect: "follow" + }; +} +function createHeaders(httpHeaders) { + const headers = new Headers(); + for (const property in httpHeaders) { + const value = httpHeaders[property]; + if (value === undefined) { + continue; + } + headers.append(property, value); + } + return headers; +} +function getArrayBuffer(val) { + if (val instanceof Uint8Array) { + return val.buffer; + } + if (val instanceof ArrayBuffer) { + return val; + } + warn(`getArrayBuffer - unexpected data format: ${val}`); + return new Uint8Array(val).buffer; +} +class PDFFetchStream { + constructor(source) { + this.source = source; + this.isHttp = /^https?:/i.test(source.url); + this.httpHeaders = this.isHttp && source.httpHeaders || {}; + this._fullRequestReader = null; + this._rangeRequestReaders = []; + } + get _progressiveDataLength() { + return this._fullRequestReader?._loaded ?? 0; + } + getFullReader() { + assert(!this._fullRequestReader, "PDFFetchStream.getFullReader can only be called once."); + this._fullRequestReader = new PDFFetchStreamReader(this); + return this._fullRequestReader; + } + getRangeReader(begin, end) { + if (end <= this._progressiveDataLength) { + return null; + } + const reader = new PDFFetchStreamRangeReader(this, begin, end); + this._rangeRequestReaders.push(reader); + return reader; + } + cancelAllRequests(reason) { + this._fullRequestReader?.cancel(reason); + for (const reader of this._rangeRequestReaders.slice(0)) { + reader.cancel(reason); + } + } +} +class PDFFetchStreamReader { + constructor(stream) { + this._stream = stream; + this._reader = null; + this._loaded = 0; + this._filename = null; + const source = stream.source; + this._withCredentials = source.withCredentials || false; + this._contentLength = source.length; + this._headersCapability = Promise.withResolvers(); + this._disableRange = source.disableRange || false; + this._rangeChunkSize = source.rangeChunkSize; + if (!this._rangeChunkSize && !this._disableRange) { + this._disableRange = true; + } + this._abortController = new AbortController(); + this._isStreamingSupported = !source.disableStream; + this._isRangeSupported = !source.disableRange; + this._headers = createHeaders(this._stream.httpHeaders); + const url = source.url; + fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => { + if (!validateResponseStatus(response.status)) { + throw createResponseStatusError(response.status, url); + } + this._reader = response.body.getReader(); + this._headersCapability.resolve(); + const getResponseHeader = name => response.headers.get(name); + const { + allowRangeRequests, + suggestedLength + } = validateRangeRequestCapabilities({ + getResponseHeader, + isHttp: this._stream.isHttp, + rangeChunkSize: this._rangeChunkSize, + disableRange: this._disableRange + }); + this._isRangeSupported = allowRangeRequests; + this._contentLength = suggestedLength || this._contentLength; + this._filename = extractFilenameFromHeader(getResponseHeader); + if (!this._isStreamingSupported && this._isRangeSupported) { + this.cancel(new AbortException("Streaming is disabled.")); + } + }).catch(this._headersCapability.reject); + this.onProgress = null; + } + get headersReady() { + return this._headersCapability.promise; + } + get filename() { + return this._filename; + } + get contentLength() { + return this._contentLength; + } + get isRangeSupported() { + return this._isRangeSupported; + } + get isStreamingSupported() { + return this._isStreamingSupported; + } + async read() { + await this._headersCapability.promise; + const { + value, + done + } = await this._reader.read(); + if (done) { + return { + value, + done + }; + } + this._loaded += value.byteLength; + this.onProgress?.({ + loaded: this._loaded, + total: this._contentLength + }); + return { + value: getArrayBuffer(value), + done: false + }; + } + cancel(reason) { + this._reader?.cancel(reason); + this._abortController.abort(); + } +} +class PDFFetchStreamRangeReader { + constructor(stream, begin, end) { + this._stream = stream; + this._reader = null; + this._loaded = 0; + const source = stream.source; + this._withCredentials = source.withCredentials || false; + this._readCapability = Promise.withResolvers(); + this._isStreamingSupported = !source.disableStream; + this._abortController = new AbortController(); + this._headers = createHeaders(this._stream.httpHeaders); + this._headers.append("Range", `bytes=${begin}-${end - 1}`); + const url = source.url; + fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => { + if (!validateResponseStatus(response.status)) { + throw createResponseStatusError(response.status, url); + } + this._readCapability.resolve(); + this._reader = response.body.getReader(); + }).catch(this._readCapability.reject); + this.onProgress = null; + } + get isStreamingSupported() { + return this._isStreamingSupported; + } + async read() { + await this._readCapability.promise; + const { + value, + done + } = await this._reader.read(); + if (done) { + return { + value, + done + }; + } + this._loaded += value.byteLength; + this.onProgress?.({ + loaded: this._loaded + }); + return { + value: getArrayBuffer(value), + done: false + }; + } + cancel(reason) { + this._reader?.cancel(reason); + this._abortController.abort(); + } +} + +;// CONCATENATED MODULE: ./src/display/network.js + + const OK_RESPONSE = 200; const PARTIAL_CONTENT_RESPONSE = 206; -function getArrayBuffer(xhr) { +function network_getArrayBuffer(xhr) { const data = xhr.response; if (typeof data !== "string") { return data; } - return (0, _util.stringToBytes)(data).buffer; + return stringToBytes(data).buffer; } class NetworkManager { constructor(url, args = {}) { @@ -10536,7 +9920,7 @@ class NetworkManager { pendingRequest.onError?.(xhr.status); return; } - const chunk = getArrayBuffer(xhr); + const chunk = network_getArrayBuffer(xhr); if (xhrStatus === PARTIAL_CONTENT_RESPONSE) { const rangeHeader = xhr.getResponseHeader("Content-Range"); const matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader); @@ -10583,7 +9967,7 @@ class PDFNetworkStream { } } getFullReader() { - (0, _util.assert)(!this._fullRequestReader, "PDFNetworkStream.getFullReader can only be called once."); + assert(!this._fullRequestReader, "PDFNetworkStream.getFullReader can only be called once."); this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source); return this._fullRequestReader; } @@ -10600,7 +9984,6 @@ class PDFNetworkStream { } } } -exports.PDFNetworkStream = PDFNetworkStream; class PDFNetworkStreamFullRequestReader { constructor(manager, source) { this._manager = manager; @@ -10612,7 +9995,7 @@ class PDFNetworkStreamFullRequestReader { }; this._url = source.url; this._fullRequestId = manager.requestFull(args); - this._headersReceivedCapability = new _util.PromiseCapability(); + this._headersReceivedCapability = Promise.withResolvers(); this._disableRange = source.disableRange || false; this._contentLength = source.length; this._rangeChunkSize = source.rangeChunkSize; @@ -10631,13 +10014,11 @@ class PDFNetworkStreamFullRequestReader { _onHeadersReceived() { const fullRequestXhrId = this._fullRequestId; const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId); - const getResponseHeader = name => { - return fullRequestXhr.getResponseHeader(name); - }; + const getResponseHeader = name => fullRequestXhr.getResponseHeader(name); const { allowRangeRequests, suggestedLength - } = (0, _network_utils.validateRangeRequestCapabilities)({ + } = validateRangeRequestCapabilities({ getResponseHeader, isHttp: this._manager.isHttp, rangeChunkSize: this._rangeChunkSize, @@ -10647,7 +10028,7 @@ class PDFNetworkStreamFullRequestReader { this._isRangeSupported = true; } this._contentLength = suggestedLength || this._contentLength; - this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader); + this._filename = extractFilenameFromHeader(getResponseHeader); if (this._isRangeSupported) { this._manager.abortRequest(fullRequestXhrId); } @@ -10678,7 +10059,7 @@ class PDFNetworkStreamFullRequestReader { this._requests.length = 0; } _onError(status) { - this._storedError = (0, _network_utils.createResponseStatusError)(status, this._url); + this._storedError = createResponseStatusError(status, this._url); this._headersReceivedCapability.reject(this._storedError); for (const requestCapability of this._requests) { requestCapability.reject(this._storedError); @@ -10724,7 +10105,7 @@ class PDFNetworkStreamFullRequestReader { done: true }; } - const requestCapability = new _util.PromiseCapability(); + const requestCapability = Promise.withResolvers(); this._requests.push(requestCapability); return requestCapability.promise; } @@ -10786,7 +10167,7 @@ class PDFNetworkStreamRangeRequestReader { this._close(); } _onError(status) { - this._storedError = (0, _network_utils.createResponseStatusError)(status, this._url); + this._storedError = createResponseStatusError(status, this._url); for (const requestCapability of this._requests) { requestCapability.reject(this._storedError); } @@ -10821,7 +10202,7 @@ class PDFNetworkStreamRangeRequestReader { done: true }; } - const requestCapability = new _util.PromiseCapability(); + const requestCapability = Promise.withResolvers(); this._requests.push(requestCapability); return requestCapability.promise; } @@ -10841,38 +10222,34 @@ class PDFNetworkStreamRangeRequestReader { } } -/***/ }), -/* 23 */ -/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { +;// CONCATENATED MODULE: ./src/display/node_stream.js -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.PDFNodeStream = void 0; -var _util = __w_pdfjs_require__(1); -var _network_utils = __w_pdfjs_require__(20); -; -const fileUriRegex = /^file:\/\/\/[a-zA-Z]:\//; -function parseUrl(sourceUrl) { - const url = require("url"); - const parsedUrl = url.parse(sourceUrl); - if (parsedUrl.protocol === "file:" || parsedUrl.host) { - return parsedUrl; +const urlRegex = /^[a-z][a-z0-9\-+.]+:/i; +function parseUrlOrPath(sourceUrl) { + if (urlRegex.test(sourceUrl)) { + return new URL(sourceUrl); } - if (/^[a-z]:[/\\]/i.test(sourceUrl)) { - return url.parse(`file:///${sourceUrl}`); + const url = NodePackages.get("url"); + return new URL(url.pathToFileURL(sourceUrl)); +} +function createRequest(url, headers, callback) { + if (url.protocol === "http:") { + const http = NodePackages.get("http"); + return http.request(url, { + headers + }, callback); } - if (!parsedUrl.host) { - parsedUrl.protocol = "file:"; - } - return parsedUrl; + const https = NodePackages.get("https"); + return https.request(url, { + headers + }, callback); } class PDFNodeStream { constructor(source) { this.source = source; - this.url = parseUrl(source.url); + this.url = parseUrlOrPath(source.url); this.isHttp = this.url.protocol === "http:" || this.url.protocol === "https:"; this.isFsUrl = this.url.protocol === "file:"; this.httpHeaders = this.isHttp && source.httpHeaders || {}; @@ -10883,7 +10260,7 @@ class PDFNodeStream { return this._fullRequestReader?._loaded ?? 0; } getFullReader() { - (0, _util.assert)(!this._fullRequestReader, "PDFNodeStream.getFullReader can only be called once."); + assert(!this._fullRequestReader, "PDFNodeStream.getFullReader can only be called once."); this._fullRequestReader = this.isFsUrl ? new PDFNodeStreamFsFullReader(this) : new PDFNodeStreamFullReader(this); return this._fullRequestReader; } @@ -10902,7 +10279,6 @@ class PDFNodeStream { } } } -exports.PDFNodeStream = PDFNodeStream; class BaseFullReader { constructor(stream) { this._url = stream.url; @@ -10921,8 +10297,8 @@ class BaseFullReader { this._isStreamingSupported = !source.disableStream; this._isRangeSupported = !source.disableRange; this._readableStream = null; - this._readCapability = new _util.PromiseCapability(); - this._headersCapability = new _util.PromiseCapability(); + this._readCapability = Promise.withResolvers(); + this._headersCapability = Promise.withResolvers(); } get headersReady() { return this._headersCapability.promise; @@ -10952,7 +10328,7 @@ class BaseFullReader { } const chunk = this._readableStream.read(); if (chunk === null) { - this._readCapability = new _util.PromiseCapability(); + this._readCapability = Promise.withResolvers(); return this.read(); } this._loaded += chunk.length; @@ -10991,7 +10367,7 @@ class BaseFullReader { this._error(reason); }); if (!this._isStreamingSupported && this._isRangeSupported) { - this._error(new _util.AbortException("streaming is disabled")); + this._error(new AbortException("streaming is disabled")); } if (this._storedError) { this._readableStream.destroy(this._storedError); @@ -11006,7 +10382,7 @@ class BaseRangeReader { this.onProgress = null; this._loaded = 0; this._readableStream = null; - this._readCapability = new _util.PromiseCapability(); + this._readCapability = Promise.withResolvers(); const source = stream.source; this._isStreamingSupported = !source.disableStream; } @@ -11026,7 +10402,7 @@ class BaseRangeReader { } const chunk = this._readableStream.read(); if (chunk === null) { - this._readCapability = new _util.PromiseCapability(); + this._readCapability = Promise.withResolvers(); return this.read(); } this._loaded += chunk.length; @@ -11068,36 +10444,23 @@ class BaseRangeReader { } } } -function createRequestOptions(parsedUrl, headers) { - return { - protocol: parsedUrl.protocol, - auth: parsedUrl.auth, - host: parsedUrl.hostname, - port: parsedUrl.port, - path: parsedUrl.path, - method: "GET", - headers - }; -} class PDFNodeStreamFullReader extends BaseFullReader { constructor(stream) { super(stream); const handleResponse = response => { if (response.statusCode === 404) { - const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`); + const error = new MissingPDFException(`Missing PDF "${this._url}".`); this._storedError = error; this._headersCapability.reject(error); return; } this._headersCapability.resolve(); this._setReadableStream(response); - const getResponseHeader = name => { - return this._readableStream.headers[name.toLowerCase()]; - }; + const getResponseHeader = name => this._readableStream.headers[name.toLowerCase()]; const { allowRangeRequests, suggestedLength - } = (0, _network_utils.validateRangeRequestCapabilities)({ + } = validateRangeRequestCapabilities({ getResponseHeader, isHttp: stream.isHttp, rangeChunkSize: this._rangeChunkSize, @@ -11105,16 +10468,9 @@ class PDFNodeStreamFullReader extends BaseFullReader { }); this._isRangeSupported = allowRangeRequests; this._contentLength = suggestedLength || this._contentLength; - this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader); + this._filename = extractFilenameFromHeader(getResponseHeader); }; - this._request = null; - if (this._url.protocol === "http:") { - const http = require("http"); - this._request = http.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse); - } else { - const https = require("https"); - this._request = https.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse); - } + this._request = createRequest(this._url, stream.httpHeaders, handleResponse); this._request.on("error", reason => { this._storedError = reason; this._headersCapability.reject(reason); @@ -11136,20 +10492,13 @@ class PDFNodeStreamRangeReader extends BaseRangeReader { this._httpHeaders.Range = `bytes=${start}-${end - 1}`; const handleResponse = response => { if (response.statusCode === 404) { - const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`); + const error = new MissingPDFException(`Missing PDF "${this._url}".`); this._storedError = error; return; } this._setReadableStream(response); }; - this._request = null; - if (this._url.protocol === "http:") { - const http = require("http"); - this._request = http.request(createRequestOptions(this._url, this._httpHeaders), handleResponse); - } else { - const https = require("https"); - this._request = https.request(createRequestOptions(this._url, this._httpHeaders), handleResponse); - } + this._request = createRequest(this._url, this._httpHeaders, handleResponse); this._request.on("error", reason => { this._storedError = reason; }); @@ -11159,1297 +10508,404 @@ class PDFNodeStreamRangeReader extends BaseRangeReader { class PDFNodeStreamFsFullReader extends BaseFullReader { constructor(stream) { super(stream); - let path = decodeURIComponent(this._url.path); - if (fileUriRegex.test(this._url.href)) { - path = path.replace(/^\//, ""); - } - const fs = require("fs"); - fs.lstat(path, (error, stat) => { - if (error) { - if (error.code === "ENOENT") { - error = new _util.MissingPDFException(`Missing PDF "${path}".`); - } - this._storedError = error; - this._headersCapability.reject(error); - return; - } + const fs = NodePackages.get("fs"); + fs.promises.lstat(this._url).then(stat => { this._contentLength = stat.size; - this._setReadableStream(fs.createReadStream(path)); + this._setReadableStream(fs.createReadStream(this._url)); this._headersCapability.resolve(); + }, error => { + if (error.code === "ENOENT") { + error = new MissingPDFException(`Missing PDF "${this._url}".`); + } + this._storedError = error; + this._headersCapability.reject(error); }); } } class PDFNodeStreamFsRangeReader extends BaseRangeReader { constructor(stream, start, end) { super(stream); - let path = decodeURIComponent(this._url.path); - if (fileUriRegex.test(this._url.href)) { - path = path.replace(/^\//, ""); - } - const fs = require("fs"); - this._setReadableStream(fs.createReadStream(path, { + const fs = NodePackages.get("fs"); + this._setReadableStream(fs.createReadStream(this._url, { start, end: end - 1 })); } } -/***/ }), -/* 24 */ -/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { +;// CONCATENATED MODULE: ./src/display/text_layer.js - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.SVGGraphics = void 0; -var _display_utils = __w_pdfjs_require__(6); -var _util = __w_pdfjs_require__(1); -; -const SVG_DEFAULTS = { - fontStyle: "normal", - fontWeight: "normal", - fillColor: "#000000" -}; -const XML_NS = "http://www.w3.org/XML/1998/namespace"; -const XLINK_NS = "http://www.w3.org/1999/xlink"; -const LINE_CAP_STYLES = ["butt", "round", "square"]; -const LINE_JOIN_STYLES = ["miter", "round", "bevel"]; -const createObjectURL = function (data, contentType = "", forceDataSchema = false) { - if (URL.createObjectURL && typeof Blob !== "undefined" && !forceDataSchema) { - return URL.createObjectURL(new Blob([data], { - type: contentType - })); - } - const digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; - let buffer = `data:${contentType};base64,`; - for (let i = 0, ii = data.length; i < ii; i += 3) { - const b1 = data[i] & 0xff; - const b2 = data[i + 1] & 0xff; - const b3 = data[i + 2] & 0xff; - const d1 = b1 >> 2, - d2 = (b1 & 3) << 4 | b2 >> 4; - const d3 = i + 1 < ii ? (b2 & 0xf) << 2 | b3 >> 6 : 64; - const d4 = i + 2 < ii ? b3 & 0x3f : 64; - buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4]; - } - return buffer; -}; -const convertImgDataToPng = function () { - const PNG_HEADER = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); - const CHUNK_WRAPPER_SIZE = 12; - const crcTable = new Int32Array(256); - for (let i = 0; i < 256; i++) { - let c = i; - for (let h = 0; h < 8; h++) { - c = c & 1 ? 0xedb88320 ^ c >> 1 & 0x7fffffff : c >> 1 & 0x7fffffff; - } - crcTable[i] = c; - } - function crc32(data, start, end) { - let crc = -1; - for (let i = start; i < end; i++) { - const a = (crc ^ data[i]) & 0xff; - const b = crcTable[a]; - crc = crc >>> 8 ^ b; - } - return crc ^ -1; - } - function writePngChunk(type, body, data, offset) { - let p = offset; - const len = body.length; - data[p] = len >> 24 & 0xff; - data[p + 1] = len >> 16 & 0xff; - data[p + 2] = len >> 8 & 0xff; - data[p + 3] = len & 0xff; - p += 4; - data[p] = type.charCodeAt(0) & 0xff; - data[p + 1] = type.charCodeAt(1) & 0xff; - data[p + 2] = type.charCodeAt(2) & 0xff; - data[p + 3] = type.charCodeAt(3) & 0xff; - p += 4; - data.set(body, p); - p += body.length; - const crc = crc32(data, offset + 4, p); - data[p] = crc >> 24 & 0xff; - data[p + 1] = crc >> 16 & 0xff; - data[p + 2] = crc >> 8 & 0xff; - data[p + 3] = crc & 0xff; - } - function adler32(data, start, end) { - let a = 1; - let b = 0; - for (let i = start; i < end; ++i) { - a = (a + (data[i] & 0xff)) % 65521; - b = (b + a) % 65521; - } - return b << 16 | a; - } - function deflateSync(literals) { - if (!_util.isNodeJS) { - return deflateSyncUncompressed(literals); - } - try { - const input = parseInt(process.versions.node) >= 8 ? literals : Buffer.from(literals); - const output = require("zlib").deflateSync(input, { - level: 9 - }); - return output instanceof Uint8Array ? output : new Uint8Array(output); - } catch (e) { - (0, _util.warn)("Not compressing PNG because zlib.deflateSync is unavailable: " + e); - } - return deflateSyncUncompressed(literals); - } - function deflateSyncUncompressed(literals) { - let len = literals.length; - const maxBlockLength = 0xffff; - const deflateBlocks = Math.ceil(len / maxBlockLength); - const idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4); - let pi = 0; - idat[pi++] = 0x78; - idat[pi++] = 0x9c; - let pos = 0; - while (len > maxBlockLength) { - idat[pi++] = 0x00; - idat[pi++] = 0xff; - idat[pi++] = 0xff; - idat[pi++] = 0x00; - idat[pi++] = 0x00; - idat.set(literals.subarray(pos, pos + maxBlockLength), pi); - pi += maxBlockLength; - pos += maxBlockLength; - len -= maxBlockLength; - } - idat[pi++] = 0x01; - idat[pi++] = len & 0xff; - idat[pi++] = len >> 8 & 0xff; - idat[pi++] = ~len & 0xffff & 0xff; - idat[pi++] = (~len & 0xffff) >> 8 & 0xff; - idat.set(literals.subarray(pos), pi); - pi += literals.length - pos; - const adler = adler32(literals, 0, literals.length); - idat[pi++] = adler >> 24 & 0xff; - idat[pi++] = adler >> 16 & 0xff; - idat[pi++] = adler >> 8 & 0xff; - idat[pi++] = adler & 0xff; - return idat; - } - function encode(imgData, kind, forceDataSchema, isMask) { - const width = imgData.width; - const height = imgData.height; - let bitDepth, colorType, lineSize; - const bytes = imgData.data; - switch (kind) { - case _util.ImageKind.GRAYSCALE_1BPP: - colorType = 0; - bitDepth = 1; - lineSize = width + 7 >> 3; - break; - case _util.ImageKind.RGB_24BPP: - colorType = 2; - bitDepth = 8; - lineSize = width * 3; - break; - case _util.ImageKind.RGBA_32BPP: - colorType = 6; - bitDepth = 8; - lineSize = width * 4; - break; - default: - throw new Error("invalid format"); - } - const literals = new Uint8Array((1 + lineSize) * height); - let offsetLiterals = 0, - offsetBytes = 0; - for (let y = 0; y < height; ++y) { - literals[offsetLiterals++] = 0; - literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), offsetLiterals); - offsetBytes += lineSize; - offsetLiterals += lineSize; - } - if (kind === _util.ImageKind.GRAYSCALE_1BPP && isMask) { - offsetLiterals = 0; - for (let y = 0; y < height; y++) { - offsetLiterals++; - for (let i = 0; i < lineSize; i++) { - literals[offsetLiterals++] ^= 0xff; +const MAX_TEXT_DIVS_TO_RENDER = 100000; +const DEFAULT_FONT_SIZE = 30; +const DEFAULT_FONT_ASCENT = 0.8; +class TextLayer { + #capability = Promise.withResolvers(); + #container = null; + #disableProcessItems = false; + #fontInspectorEnabled = !!globalThis.FontInspector?.enabled; + #lang = null; + #layoutTextParams = null; + #pageHeight = 0; + #pageWidth = 0; + #reader = null; + #rootContainer = null; + #rotation = 0; + #scale = 0; + #styleCache = Object.create(null); + #textContentItemsStr = []; + #textContentSource = null; + #textDivs = []; + #textDivProperties = new WeakMap(); + #transform = null; + static #ascentCache = new Map(); + static #canvasContexts = new Map(); + static #minFontSize = null; + static #pendingTextLayers = new Set(); + constructor({ + textContentSource, + container, + viewport + }) { + if (textContentSource instanceof ReadableStream) { + this.#textContentSource = textContentSource; + } else if (typeof textContentSource === "object") { + this.#textContentSource = new ReadableStream({ + start(controller) { + controller.enqueue(textContentSource); + controller.close(); } - } - } - const ihdr = new Uint8Array([width >> 24 & 0xff, width >> 16 & 0xff, width >> 8 & 0xff, width & 0xff, height >> 24 & 0xff, height >> 16 & 0xff, height >> 8 & 0xff, height & 0xff, bitDepth, colorType, 0x00, 0x00, 0x00]); - const idat = deflateSync(literals); - const pngLength = PNG_HEADER.length + CHUNK_WRAPPER_SIZE * 3 + ihdr.length + idat.length; - const data = new Uint8Array(pngLength); - let offset = 0; - data.set(PNG_HEADER, offset); - offset += PNG_HEADER.length; - writePngChunk("IHDR", ihdr, data, offset); - offset += CHUNK_WRAPPER_SIZE + ihdr.length; - writePngChunk("IDATA", idat, data, offset); - offset += CHUNK_WRAPPER_SIZE + idat.length; - writePngChunk("IEND", new Uint8Array(0), data, offset); - return createObjectURL(data, "image/png", forceDataSchema); - } - return function convertImgDataToPng(imgData, forceDataSchema, isMask) { - const kind = imgData.kind === undefined ? _util.ImageKind.GRAYSCALE_1BPP : imgData.kind; - return encode(imgData, kind, forceDataSchema, isMask); - }; -}(); -class SVGExtraState { - constructor() { - this.fontSizeScale = 1; - this.fontWeight = SVG_DEFAULTS.fontWeight; - this.fontSize = 0; - this.textMatrix = _util.IDENTITY_MATRIX; - this.fontMatrix = _util.FONT_IDENTITY_MATRIX; - this.leading = 0; - this.textRenderingMode = _util.TextRenderingMode.FILL; - this.textMatrixScale = 1; - this.x = 0; - this.y = 0; - this.lineX = 0; - this.lineY = 0; - this.charSpacing = 0; - this.wordSpacing = 0; - this.textHScale = 1; - this.textRise = 0; - this.fillColor = SVG_DEFAULTS.fillColor; - this.strokeColor = "#000000"; - this.fillAlpha = 1; - this.strokeAlpha = 1; - this.lineWidth = 1; - this.lineJoin = ""; - this.lineCap = ""; - this.miterLimit = 0; - this.dashArray = []; - this.dashPhase = 0; - this.dependencies = []; - this.activeClipUrl = null; - this.clipGroup = null; - this.maskId = ""; - } - clone() { - return Object.create(this); - } - setCurrentPoint(x, y) { - this.x = x; - this.y = y; - } -} -function opListToTree(opList) { - let opTree = []; - const tmp = []; - for (const opListElement of opList) { - if (opListElement.fn === "save") { - opTree.push({ - fnId: 92, - fn: "group", - items: [] }); - tmp.push(opTree); - opTree = opTree.at(-1).items; - continue; - } - if (opListElement.fn === "restore") { - opTree = tmp.pop(); } else { - opTree.push(opListElement); + throw new Error('No "textContentSource" parameter specified.'); } - } - return opTree; -} -function pf(value) { - if (Number.isInteger(value)) { - return value.toString(); - } - const s = value.toFixed(10); - let i = s.length - 1; - if (s[i] !== "0") { - return s; - } - do { - i--; - } while (s[i] === "0"); - return s.substring(0, s[i] === "." ? i : i + 1); -} -function pm(m) { - if (m[4] === 0 && m[5] === 0) { - if (m[1] === 0 && m[2] === 0) { - if (m[0] === 1 && m[3] === 1) { - return ""; - } - return `scale(${pf(m[0])} ${pf(m[3])})`; - } - if (m[0] === m[3] && m[1] === -m[2]) { - const a = Math.acos(m[0]) * 180 / Math.PI; - return `rotate(${pf(a)})`; - } - } else if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) { - return `translate(${pf(m[4])} ${pf(m[5])})`; - } - return `matrix(${pf(m[0])} ${pf(m[1])} ${pf(m[2])} ${pf(m[3])} ${pf(m[4])} ` + `${pf(m[5])})`; -} -let clipCount = 0; -let maskCount = 0; -let shadingCount = 0; -class SVGGraphics { - constructor(commonObjs, objs, forceDataSchema = false) { - (0, _display_utils.deprecated)("The SVG back-end is no longer maintained and *may* be removed in the future."); - this.svgFactory = new _display_utils.DOMSVGFactory(); - this.current = new SVGExtraState(); - this.transformMatrix = _util.IDENTITY_MATRIX; - this.transformStack = []; - this.extraStack = []; - this.commonObjs = commonObjs; - this.objs = objs; - this.pendingClip = null; - this.pendingEOFill = false; - this.embedFonts = false; - this.embeddedFonts = Object.create(null); - this.cssStyle = null; - this.forceDataSchema = !!forceDataSchema; - this._operatorIdMapping = []; - for (const op in _util.OPS) { - this._operatorIdMapping[_util.OPS[op]] = op; - } - } - getObject(data, fallback = null) { - if (typeof data === "string") { - return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data); - } - return fallback; - } - save() { - this.transformStack.push(this.transformMatrix); - const old = this.current; - this.extraStack.push(old); - this.current = old.clone(); - } - restore() { - this.transformMatrix = this.transformStack.pop(); - this.current = this.extraStack.pop(); - this.pendingClip = null; - this.tgrp = null; - } - group(items) { - this.save(); - this.executeOpTree(items); - this.restore(); - } - loadDependencies(operatorList) { - const fnArray = operatorList.fnArray; - const argsArray = operatorList.argsArray; - for (let i = 0, ii = fnArray.length; i < ii; i++) { - if (fnArray[i] !== _util.OPS.dependency) { - continue; - } - for (const obj of argsArray[i]) { - const objsPool = obj.startsWith("g_") ? this.commonObjs : this.objs; - const promise = new Promise(resolve => { - objsPool.get(obj, resolve); - }); - this.current.dependencies.push(promise); - } - } - return Promise.all(this.current.dependencies); - } - transform(a, b, c, d, e, f) { - const transformMatrix = [a, b, c, d, e, f]; - this.transformMatrix = _util.Util.transform(this.transformMatrix, transformMatrix); - this.tgrp = null; - } - getSVG(operatorList, viewport) { - this.viewport = viewport; - const svgElement = this._initialize(viewport); - return this.loadDependencies(operatorList).then(() => { - this.transformMatrix = _util.IDENTITY_MATRIX; - this.executeOpTree(this.convertOpList(operatorList)); - return svgElement; + this.#container = this.#rootContainer = container; + this.#scale = viewport.scale * (globalThis.devicePixelRatio || 1); + this.#rotation = viewport.rotation; + this.#layoutTextParams = { + prevFontSize: null, + prevFontFamily: null, + div: null, + properties: null, + ctx: null + }; + const { + pageWidth, + pageHeight, + pageX, + pageY + } = viewport.rawDims; + this.#transform = [1, 0, 0, -1, -pageX, pageY + pageHeight]; + this.#pageWidth = pageWidth; + this.#pageHeight = pageHeight; + TextLayer.#ensureMinFontSizeComputed(); + setLayerDimensions(container, viewport); + this.#capability.promise.catch(() => {}).then(() => { + TextLayer.#pendingTextLayers.delete(this); + this.#layoutTextParams = null; + this.#styleCache = null; }); } - convertOpList(operatorList) { - const operatorIdMapping = this._operatorIdMapping; - const argsArray = operatorList.argsArray; - const fnArray = operatorList.fnArray; - const opList = []; - for (let i = 0, ii = fnArray.length; i < ii; i++) { - const fnId = fnArray[i]; - opList.push({ - fnId, - fn: operatorIdMapping[fnId], - args: argsArray[i] + render() { + const pump = () => { + this.#reader.read().then(({ + value, + done + }) => { + if (done) { + this.#capability.resolve(); + return; + } + this.#lang ??= value.lang; + Object.assign(this.#styleCache, value.styles); + this.#processItems(value.items); + pump(); + }, this.#capability.reject); + }; + this.#reader = this.#textContentSource.getReader(); + TextLayer.#pendingTextLayers.add(this); + pump(); + return this.#capability.promise; + } + update({ + viewport, + onBefore = null + }) { + const scale = viewport.scale * (globalThis.devicePixelRatio || 1); + const rotation = viewport.rotation; + if (rotation !== this.#rotation) { + onBefore?.(); + this.#rotation = rotation; + setLayerDimensions(this.#rootContainer, { + rotation }); } - return opListToTree(opList); - } - executeOpTree(opTree) { - for (const opTreeElement of opTree) { - const fn = opTreeElement.fn; - const fnId = opTreeElement.fnId; - const args = opTreeElement.args; - switch (fnId | 0) { - case _util.OPS.beginText: - this.beginText(); - break; - case _util.OPS.dependency: - break; - case _util.OPS.setLeading: - this.setLeading(args); - break; - case _util.OPS.setLeadingMoveText: - this.setLeadingMoveText(args[0], args[1]); - break; - case _util.OPS.setFont: - this.setFont(args); - break; - case _util.OPS.showText: - this.showText(args[0]); - break; - case _util.OPS.showSpacedText: - this.showText(args[0]); - break; - case _util.OPS.endText: - this.endText(); - break; - case _util.OPS.moveText: - this.moveText(args[0], args[1]); - break; - case _util.OPS.setCharSpacing: - this.setCharSpacing(args[0]); - break; - case _util.OPS.setWordSpacing: - this.setWordSpacing(args[0]); - break; - case _util.OPS.setHScale: - this.setHScale(args[0]); - break; - case _util.OPS.setTextMatrix: - this.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]); - break; - case _util.OPS.setTextRise: - this.setTextRise(args[0]); - break; - case _util.OPS.setTextRenderingMode: - this.setTextRenderingMode(args[0]); - break; - case _util.OPS.setLineWidth: - this.setLineWidth(args[0]); - break; - case _util.OPS.setLineJoin: - this.setLineJoin(args[0]); - break; - case _util.OPS.setLineCap: - this.setLineCap(args[0]); - break; - case _util.OPS.setMiterLimit: - this.setMiterLimit(args[0]); - break; - case _util.OPS.setFillRGBColor: - this.setFillRGBColor(args[0], args[1], args[2]); - break; - case _util.OPS.setStrokeRGBColor: - this.setStrokeRGBColor(args[0], args[1], args[2]); - break; - case _util.OPS.setStrokeColorN: - this.setStrokeColorN(args); - break; - case _util.OPS.setFillColorN: - this.setFillColorN(args); - break; - case _util.OPS.shadingFill: - this.shadingFill(args[0]); - break; - case _util.OPS.setDash: - this.setDash(args[0], args[1]); - break; - case _util.OPS.setRenderingIntent: - this.setRenderingIntent(args[0]); - break; - case _util.OPS.setFlatness: - this.setFlatness(args[0]); - break; - case _util.OPS.setGState: - this.setGState(args[0]); - break; - case _util.OPS.fill: - this.fill(); - break; - case _util.OPS.eoFill: - this.eoFill(); - break; - case _util.OPS.stroke: - this.stroke(); - break; - case _util.OPS.fillStroke: - this.fillStroke(); - break; - case _util.OPS.eoFillStroke: - this.eoFillStroke(); - break; - case _util.OPS.clip: - this.clip("nonzero"); - break; - case _util.OPS.eoClip: - this.clip("evenodd"); - break; - case _util.OPS.paintSolidColorImageMask: - this.paintSolidColorImageMask(); - break; - case _util.OPS.paintImageXObject: - this.paintImageXObject(args[0]); - break; - case _util.OPS.paintInlineImageXObject: - this.paintInlineImageXObject(args[0]); - break; - case _util.OPS.paintImageMaskXObject: - this.paintImageMaskXObject(args[0]); - break; - case _util.OPS.paintFormXObjectBegin: - this.paintFormXObjectBegin(args[0], args[1]); - break; - case _util.OPS.paintFormXObjectEnd: - this.paintFormXObjectEnd(); - break; - case _util.OPS.closePath: - this.closePath(); - break; - case _util.OPS.closeStroke: - this.closeStroke(); - break; - case _util.OPS.closeFillStroke: - this.closeFillStroke(); - break; - case _util.OPS.closeEOFillStroke: - this.closeEOFillStroke(); - break; - case _util.OPS.nextLine: - this.nextLine(); - break; - case _util.OPS.transform: - this.transform(args[0], args[1], args[2], args[3], args[4], args[5]); - break; - case _util.OPS.constructPath: - this.constructPath(args[0], args[1]); - break; - case _util.OPS.endPath: - this.endPath(); - break; - case 92: - this.group(opTreeElement.items); - break; - default: - (0, _util.warn)(`Unimplemented operator ${fn}`); - break; + if (scale !== this.#scale) { + onBefore?.(); + this.#scale = scale; + const params = { + prevFontSize: null, + prevFontFamily: null, + div: null, + properties: null, + ctx: TextLayer.#getCtx(this.#lang) + }; + for (const div of this.#textDivs) { + params.properties = this.#textDivProperties.get(div); + params.div = div; + this.#layout(params); } } } - setWordSpacing(wordSpacing) { - this.current.wordSpacing = wordSpacing; + cancel() { + const abortEx = new AbortException("TextLayer task cancelled."); + this.#reader?.cancel(abortEx).catch(() => {}); + this.#reader = null; + this.#capability.reject(abortEx); } - setCharSpacing(charSpacing) { - this.current.charSpacing = charSpacing; + get textDivs() { + return this.#textDivs; } - nextLine() { - this.moveText(0, this.current.leading); + get textContentItemsStr() { + return this.#textContentItemsStr; } - setTextMatrix(a, b, c, d, e, f) { - const current = this.current; - current.textMatrix = current.lineMatrix = [a, b, c, d, e, f]; - current.textMatrixScale = Math.hypot(a, b); - current.x = current.lineX = 0; - current.y = current.lineY = 0; - current.xcoords = []; - current.ycoords = []; - current.tspan = this.svgFactory.createElement("svg:tspan"); - current.tspan.setAttributeNS(null, "font-family", current.fontFamily); - current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`); - current.tspan.setAttributeNS(null, "y", pf(-current.y)); - current.txtElement = this.svgFactory.createElement("svg:text"); - current.txtElement.append(current.tspan); - } - beginText() { - const current = this.current; - current.x = current.lineX = 0; - current.y = current.lineY = 0; - current.textMatrix = _util.IDENTITY_MATRIX; - current.lineMatrix = _util.IDENTITY_MATRIX; - current.textMatrixScale = 1; - current.tspan = this.svgFactory.createElement("svg:tspan"); - current.txtElement = this.svgFactory.createElement("svg:text"); - current.txtgrp = this.svgFactory.createElement("svg:g"); - current.xcoords = []; - current.ycoords = []; - } - moveText(x, y) { - const current = this.current; - current.x = current.lineX += x; - current.y = current.lineY += y; - current.xcoords = []; - current.ycoords = []; - current.tspan = this.svgFactory.createElement("svg:tspan"); - current.tspan.setAttributeNS(null, "font-family", current.fontFamily); - current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`); - current.tspan.setAttributeNS(null, "y", pf(-current.y)); - } - showText(glyphs) { - const current = this.current; - const font = current.font; - const fontSize = current.fontSize; - if (fontSize === 0) { + #processItems(items) { + if (this.#disableProcessItems) { return; } - const fontSizeScale = current.fontSizeScale; - const charSpacing = current.charSpacing; - const wordSpacing = current.wordSpacing; - const fontDirection = current.fontDirection; - const textHScale = current.textHScale * fontDirection; - const vertical = font.vertical; - const spacingDir = vertical ? 1 : -1; - const defaultVMetrics = font.defaultVMetrics; - const widthAdvanceScale = fontSize * current.fontMatrix[0]; - let x = 0; - for (const glyph of glyphs) { - if (glyph === null) { - x += fontDirection * wordSpacing; - continue; - } else if (typeof glyph === "number") { - x += spacingDir * glyph * fontSize / 1000; - continue; + this.#layoutTextParams.ctx ??= TextLayer.#getCtx(this.#lang); + const textDivs = this.#textDivs, + textContentItemsStr = this.#textContentItemsStr; + for (const item of items) { + if (textDivs.length > MAX_TEXT_DIVS_TO_RENDER) { + warn("Ignoring additional textDivs for performance reasons."); + this.#disableProcessItems = true; + return; } - const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing; - const character = glyph.fontChar; - let scaledX, scaledY; - let width = glyph.width; - if (vertical) { - let vx; - const vmetric = glyph.vmetric || defaultVMetrics; - vx = glyph.vmetric ? vmetric[1] : width * 0.5; - vx = -vx * widthAdvanceScale; - const vy = vmetric[2] * widthAdvanceScale; - width = vmetric ? -vmetric[0] : width; - scaledX = vx / fontSizeScale; - scaledY = (x + vy) / fontSizeScale; - } else { - scaledX = x / fontSizeScale; - scaledY = 0; - } - if (glyph.isInFont || font.missingFile) { - current.xcoords.push(current.x + scaledX); - if (vertical) { - current.ycoords.push(-current.y + scaledY); + if (item.str === undefined) { + if (item.type === "beginMarkedContentProps" || item.type === "beginMarkedContent") { + const parent = this.#container; + this.#container = document.createElement("span"); + this.#container.classList.add("markedContent"); + if (item.id !== null) { + this.#container.setAttribute("id", `${item.id}`); + } + parent.append(this.#container); + } else if (item.type === "endMarkedContent") { + this.#container = this.#container.parentNode; } - current.tspan.textContent += character; - } else {} - const charWidth = vertical ? width * widthAdvanceScale - spacing * fontDirection : width * widthAdvanceScale + spacing * fontDirection; - x += charWidth; - } - current.tspan.setAttributeNS(null, "x", current.xcoords.map(pf).join(" ")); - if (vertical) { - current.tspan.setAttributeNS(null, "y", current.ycoords.map(pf).join(" ")); - } else { - current.tspan.setAttributeNS(null, "y", pf(-current.y)); - } - if (vertical) { - current.y -= x; - } else { - current.x += x * textHScale; - } - current.tspan.setAttributeNS(null, "font-family", current.fontFamily); - current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`); - if (current.fontStyle !== SVG_DEFAULTS.fontStyle) { - current.tspan.setAttributeNS(null, "font-style", current.fontStyle); - } - if (current.fontWeight !== SVG_DEFAULTS.fontWeight) { - current.tspan.setAttributeNS(null, "font-weight", current.fontWeight); - } - const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK; - if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) { - if (current.fillColor !== SVG_DEFAULTS.fillColor) { - current.tspan.setAttributeNS(null, "fill", current.fillColor); + continue; } - if (current.fillAlpha < 1) { - current.tspan.setAttributeNS(null, "fill-opacity", current.fillAlpha); + textContentItemsStr.push(item.str); + this.#appendText(item); + } + } + #appendText(geom) { + const textDiv = document.createElement("span"); + const textDivProperties = { + angle: 0, + canvasWidth: 0, + hasText: geom.str !== "", + hasEOL: geom.hasEOL, + fontSize: 0 + }; + this.#textDivs.push(textDiv); + const tx = Util.transform(this.#transform, geom.transform); + let angle = Math.atan2(tx[1], tx[0]); + const style = this.#styleCache[geom.fontName]; + if (style.vertical) { + angle += Math.PI / 2; + } + const fontFamily = this.#fontInspectorEnabled && style.fontSubstitution || style.fontFamily; + const fontHeight = Math.hypot(tx[2], tx[3]); + const fontAscent = fontHeight * TextLayer.#getAscent(fontFamily, this.#lang); + let left, top; + if (angle === 0) { + left = tx[4]; + top = tx[5] - fontAscent; + } else { + left = tx[4] + fontAscent * Math.sin(angle); + top = tx[5] - fontAscent * Math.cos(angle); + } + const scaleFactorStr = "calc(var(--scale-factor)*"; + const divStyle = textDiv.style; + if (this.#container === this.#rootContainer) { + divStyle.left = `${(100 * left / this.#pageWidth).toFixed(2)}%`; + divStyle.top = `${(100 * top / this.#pageHeight).toFixed(2)}%`; + } else { + divStyle.left = `${scaleFactorStr}${left.toFixed(2)}px)`; + divStyle.top = `${scaleFactorStr}${top.toFixed(2)}px)`; + } + divStyle.fontSize = `${scaleFactorStr}${(TextLayer.#minFontSize * fontHeight).toFixed(2)}px)`; + divStyle.fontFamily = fontFamily; + textDivProperties.fontSize = fontHeight; + textDiv.setAttribute("role", "presentation"); + textDiv.textContent = geom.str; + textDiv.dir = geom.dir; + if (this.#fontInspectorEnabled) { + textDiv.dataset.fontName = style.fontSubstitutionLoadedName || geom.fontName; + } + if (angle !== 0) { + textDivProperties.angle = angle * (180 / Math.PI); + } + let shouldScaleText = false; + if (geom.str.length > 1) { + shouldScaleText = true; + } else if (geom.str !== " " && geom.transform[0] !== geom.transform[3]) { + const absScaleX = Math.abs(geom.transform[0]), + absScaleY = Math.abs(geom.transform[3]); + if (absScaleX !== absScaleY && Math.max(absScaleX, absScaleY) / Math.min(absScaleX, absScaleY) > 1.5) { + shouldScaleText = true; } - } else if (current.textRenderingMode === _util.TextRenderingMode.ADD_TO_PATH) { - current.tspan.setAttributeNS(null, "fill", "transparent"); - } else { - current.tspan.setAttributeNS(null, "fill", "none"); } - if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) { - const lineWidthScale = 1 / (current.textMatrixScale || 1); - this._setStrokeAttributes(current.tspan, lineWidthScale); + if (shouldScaleText) { + textDivProperties.canvasWidth = style.vertical ? geom.height : geom.width; } - let textMatrix = current.textMatrix; - if (current.textRise !== 0) { - textMatrix = textMatrix.slice(); - textMatrix[5] += current.textRise; + this.#textDivProperties.set(textDiv, textDivProperties); + this.#layoutTextParams.div = textDiv; + this.#layoutTextParams.properties = textDivProperties; + this.#layout(this.#layoutTextParams); + if (textDivProperties.hasText) { + this.#container.append(textDiv); } - current.txtElement.setAttributeNS(null, "transform", `${pm(textMatrix)} scale(${pf(textHScale)}, -1)`); - current.txtElement.setAttributeNS(XML_NS, "xml:space", "preserve"); - current.txtElement.append(current.tspan); - current.txtgrp.append(current.txtElement); - this._ensureTransformGroup().append(current.txtElement); - } - setLeadingMoveText(x, y) { - this.setLeading(-y); - this.moveText(x, y); - } - addFontStyle(fontObj) { - if (!fontObj.data) { - throw new Error("addFontStyle: No font data available, " + 'ensure that the "fontExtraProperties" API parameter is set.'); - } - if (!this.cssStyle) { - this.cssStyle = this.svgFactory.createElement("svg:style"); - this.cssStyle.setAttributeNS(null, "type", "text/css"); - this.defs.append(this.cssStyle); - } - const url = createObjectURL(fontObj.data, fontObj.mimetype, this.forceDataSchema); - this.cssStyle.textContent += `@font-face { font-family: "${fontObj.loadedName}";` + ` src: url(${url}); }\n`; - } - setFont(details) { - const current = this.current; - const fontObj = this.commonObjs.get(details[0]); - let size = details[1]; - current.font = fontObj; - if (this.embedFonts && !fontObj.missingFile && !this.embeddedFonts[fontObj.loadedName]) { - this.addFontStyle(fontObj); - this.embeddedFonts[fontObj.loadedName] = fontObj; - } - current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX; - let bold = "normal"; - if (fontObj.black) { - bold = "900"; - } else if (fontObj.bold) { - bold = "bold"; - } - const italic = fontObj.italic ? "italic" : "normal"; - if (size < 0) { - size = -size; - current.fontDirection = -1; - } else { - current.fontDirection = 1; - } - current.fontSize = size; - current.fontFamily = fontObj.loadedName; - current.fontWeight = bold; - current.fontStyle = italic; - current.tspan = this.svgFactory.createElement("svg:tspan"); - current.tspan.setAttributeNS(null, "y", pf(-current.y)); - current.xcoords = []; - current.ycoords = []; - } - endText() { - const current = this.current; - if (current.textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG && current.txtElement?.hasChildNodes()) { - current.element = current.txtElement; - this.clip("nonzero"); - this.endPath(); + if (textDivProperties.hasEOL) { + const br = document.createElement("br"); + br.setAttribute("role", "presentation"); + this.#container.append(br); } } - setLineWidth(width) { - if (width > 0) { - this.current.lineWidth = width; - } - } - setLineCap(style) { - this.current.lineCap = LINE_CAP_STYLES[style]; - } - setLineJoin(style) { - this.current.lineJoin = LINE_JOIN_STYLES[style]; - } - setMiterLimit(limit) { - this.current.miterLimit = limit; - } - setStrokeAlpha(strokeAlpha) { - this.current.strokeAlpha = strokeAlpha; - } - setStrokeRGBColor(r, g, b) { - this.current.strokeColor = _util.Util.makeHexColor(r, g, b); - } - setFillAlpha(fillAlpha) { - this.current.fillAlpha = fillAlpha; - } - setFillRGBColor(r, g, b) { - this.current.fillColor = _util.Util.makeHexColor(r, g, b); - this.current.tspan = this.svgFactory.createElement("svg:tspan"); - this.current.xcoords = []; - this.current.ycoords = []; - } - setStrokeColorN(args) { - this.current.strokeColor = this._makeColorN_Pattern(args); - } - setFillColorN(args) { - this.current.fillColor = this._makeColorN_Pattern(args); - } - shadingFill(args) { + #layout(params) { const { - width, - height - } = this.viewport; - const inv = _util.Util.inverseTransform(this.transformMatrix); - const [x0, y0, x1, y1] = _util.Util.getAxialAlignedBoundingBox([0, 0, width, height], inv); - const rect = this.svgFactory.createElement("svg:rect"); - rect.setAttributeNS(null, "x", x0); - rect.setAttributeNS(null, "y", y0); - rect.setAttributeNS(null, "width", x1 - x0); - rect.setAttributeNS(null, "height", y1 - y0); - rect.setAttributeNS(null, "fill", this._makeShadingPattern(args)); - if (this.current.fillAlpha < 1) { - rect.setAttributeNS(null, "fill-opacity", this.current.fillAlpha); + div, + properties, + ctx, + prevFontSize, + prevFontFamily + } = params; + const { + style + } = div; + let transform = ""; + if (TextLayer.#minFontSize > 1) { + transform = `scale(${1 / TextLayer.#minFontSize})`; } - this._ensureTransformGroup().append(rect); - } - _makeColorN_Pattern(args) { - if (args[0] === "TilingPattern") { - return this._makeTilingPattern(args); - } - return this._makeShadingPattern(args); - } - _makeTilingPattern(args) { - const color = args[1]; - const operatorList = args[2]; - const matrix = args[3] || _util.IDENTITY_MATRIX; - const [x0, y0, x1, y1] = args[4]; - const xstep = args[5]; - const ystep = args[6]; - const paintType = args[7]; - const tilingId = `shading${shadingCount++}`; - const [tx0, ty0, tx1, ty1] = _util.Util.normalizeRect([..._util.Util.applyTransform([x0, y0], matrix), ..._util.Util.applyTransform([x1, y1], matrix)]); - const [xscale, yscale] = _util.Util.singularValueDecompose2dScale(matrix); - const txstep = xstep * xscale; - const tystep = ystep * yscale; - const tiling = this.svgFactory.createElement("svg:pattern"); - tiling.setAttributeNS(null, "id", tilingId); - tiling.setAttributeNS(null, "patternUnits", "userSpaceOnUse"); - tiling.setAttributeNS(null, "width", txstep); - tiling.setAttributeNS(null, "height", tystep); - tiling.setAttributeNS(null, "x", `${tx0}`); - tiling.setAttributeNS(null, "y", `${ty0}`); - const svg = this.svg; - const transformMatrix = this.transformMatrix; - const fillColor = this.current.fillColor; - const strokeColor = this.current.strokeColor; - const bbox = this.svgFactory.create(tx1 - tx0, ty1 - ty0); - this.svg = bbox; - this.transformMatrix = matrix; - if (paintType === 2) { - const cssColor = _util.Util.makeHexColor(...color); - this.current.fillColor = cssColor; - this.current.strokeColor = cssColor; - } - this.executeOpTree(this.convertOpList(operatorList)); - this.svg = svg; - this.transformMatrix = transformMatrix; - this.current.fillColor = fillColor; - this.current.strokeColor = strokeColor; - tiling.append(bbox.childNodes[0]); - this.defs.append(tiling); - return `url(#${tilingId})`; - } - _makeShadingPattern(args) { - if (typeof args === "string") { - args = this.objs.get(args); - } - switch (args[0]) { - case "RadialAxial": - const shadingId = `shading${shadingCount++}`; - const colorStops = args[3]; - let gradient; - switch (args[1]) { - case "axial": - const point0 = args[4]; - const point1 = args[5]; - gradient = this.svgFactory.createElement("svg:linearGradient"); - gradient.setAttributeNS(null, "id", shadingId); - gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse"); - gradient.setAttributeNS(null, "x1", point0[0]); - gradient.setAttributeNS(null, "y1", point0[1]); - gradient.setAttributeNS(null, "x2", point1[0]); - gradient.setAttributeNS(null, "y2", point1[1]); - break; - case "radial": - const focalPoint = args[4]; - const circlePoint = args[5]; - const focalRadius = args[6]; - const circleRadius = args[7]; - gradient = this.svgFactory.createElement("svg:radialGradient"); - gradient.setAttributeNS(null, "id", shadingId); - gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse"); - gradient.setAttributeNS(null, "cx", circlePoint[0]); - gradient.setAttributeNS(null, "cy", circlePoint[1]); - gradient.setAttributeNS(null, "r", circleRadius); - gradient.setAttributeNS(null, "fx", focalPoint[0]); - gradient.setAttributeNS(null, "fy", focalPoint[1]); - gradient.setAttributeNS(null, "fr", focalRadius); - break; - default: - throw new Error(`Unknown RadialAxial type: ${args[1]}`); - } - for (const colorStop of colorStops) { - const stop = this.svgFactory.createElement("svg:stop"); - stop.setAttributeNS(null, "offset", colorStop[0]); - stop.setAttributeNS(null, "stop-color", colorStop[1]); - gradient.append(stop); - } - this.defs.append(gradient); - return `url(#${shadingId})`; - case "Mesh": - (0, _util.warn)("Unimplemented pattern Mesh"); - return null; - case "Dummy": - return "hotpink"; - default: - throw new Error(`Unknown IR type: ${args[0]}`); - } - } - setDash(dashArray, dashPhase) { - this.current.dashArray = dashArray; - this.current.dashPhase = dashPhase; - } - constructPath(ops, args) { - const current = this.current; - let x = current.x, - y = current.y; - let d = []; - let j = 0; - for (const op of ops) { - switch (op | 0) { - case _util.OPS.rectangle: - x = args[j++]; - y = args[j++]; - const width = args[j++]; - const height = args[j++]; - const xw = x + width; - const yh = y + height; - d.push("M", pf(x), pf(y), "L", pf(xw), pf(y), "L", pf(xw), pf(yh), "L", pf(x), pf(yh), "Z"); - break; - case _util.OPS.moveTo: - x = args[j++]; - y = args[j++]; - d.push("M", pf(x), pf(y)); - break; - case _util.OPS.lineTo: - x = args[j++]; - y = args[j++]; - d.push("L", pf(x), pf(y)); - break; - case _util.OPS.curveTo: - x = args[j + 4]; - y = args[j + 5]; - d.push("C", pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]), pf(x), pf(y)); - j += 6; - break; - case _util.OPS.curveTo2: - d.push("C", pf(x), pf(y), pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3])); - x = args[j + 2]; - y = args[j + 3]; - j += 4; - break; - case _util.OPS.curveTo3: - x = args[j + 2]; - y = args[j + 3]; - d.push("C", pf(args[j]), pf(args[j + 1]), pf(x), pf(y), pf(x), pf(y)); - j += 4; - break; - case _util.OPS.closePath: - d.push("Z"); - break; + if (properties.canvasWidth !== 0 && properties.hasText) { + const { + fontFamily + } = style; + const { + canvasWidth, + fontSize + } = properties; + if (prevFontSize !== fontSize || prevFontFamily !== fontFamily) { + ctx.font = `${fontSize * this.#scale}px ${fontFamily}`; + params.prevFontSize = fontSize; + params.prevFontFamily = fontFamily; + } + const { + width + } = ctx.measureText(div.textContent); + if (width > 0) { + transform = `scaleX(${canvasWidth * this.#scale / width}) ${transform}`; } } - d = d.join(" "); - if (current.path && ops.length > 0 && ops[0] !== _util.OPS.rectangle && ops[0] !== _util.OPS.moveTo) { - d = current.path.getAttributeNS(null, "d") + d; - } else { - current.path = this.svgFactory.createElement("svg:path"); - this._ensureTransformGroup().append(current.path); + if (properties.angle !== 0) { + transform = `rotate(${properties.angle}deg) ${transform}`; + } + if (transform.length > 0) { + style.transform = transform; } - current.path.setAttributeNS(null, "d", d); - current.path.setAttributeNS(null, "fill", "none"); - current.element = current.path; - current.setCurrentPoint(x, y); } - endPath() { - const current = this.current; - current.path = null; - if (!this.pendingClip) { + static cleanup() { + if (this.#pendingTextLayers.size > 0) { return; } - if (!current.element) { - this.pendingClip = null; - return; + this.#ascentCache.clear(); + for (const { + canvas + } of this.#canvasContexts.values()) { + canvas.remove(); } - const clipId = `clippath${clipCount++}`; - const clipPath = this.svgFactory.createElement("svg:clipPath"); - clipPath.setAttributeNS(null, "id", clipId); - clipPath.setAttributeNS(null, "transform", pm(this.transformMatrix)); - const clipElement = current.element.cloneNode(true); - if (this.pendingClip === "evenodd") { - clipElement.setAttributeNS(null, "clip-rule", "evenodd"); - } else { - clipElement.setAttributeNS(null, "clip-rule", "nonzero"); - } - this.pendingClip = null; - clipPath.append(clipElement); - this.defs.append(clipPath); - if (current.activeClipUrl) { - current.clipGroup = null; - for (const prev of this.extraStack) { - prev.clipGroup = null; - } - clipPath.setAttributeNS(null, "clip-path", current.activeClipUrl); - } - current.activeClipUrl = `url(#${clipId})`; - this.tgrp = null; + this.#canvasContexts.clear(); } - clip(type) { - this.pendingClip = type; - } - closePath() { - const current = this.current; - if (current.path) { - const d = `${current.path.getAttributeNS(null, "d")}Z`; - current.path.setAttributeNS(null, "d", d); - } - } - setLeading(leading) { - this.current.leading = -leading; - } - setTextRise(textRise) { - this.current.textRise = textRise; - } - setTextRenderingMode(textRenderingMode) { - this.current.textRenderingMode = textRenderingMode; - } - setHScale(scale) { - this.current.textHScale = scale / 100; - } - setRenderingIntent(intent) {} - setFlatness(flatness) {} - setGState(states) { - for (const [key, value] of states) { - switch (key) { - case "LW": - this.setLineWidth(value); - break; - case "LC": - this.setLineCap(value); - break; - case "LJ": - this.setLineJoin(value); - break; - case "ML": - this.setMiterLimit(value); - break; - case "D": - this.setDash(value[0], value[1]); - break; - case "RI": - this.setRenderingIntent(value); - break; - case "FL": - this.setFlatness(value); - break; - case "Font": - this.setFont(value); - break; - case "CA": - this.setStrokeAlpha(value); - break; - case "ca": - this.setFillAlpha(value); - break; - default: - (0, _util.warn)(`Unimplemented graphic state operator ${key}`); - break; - } - } - } - fill() { - const current = this.current; - if (current.element) { - current.element.setAttributeNS(null, "fill", current.fillColor); - current.element.setAttributeNS(null, "fill-opacity", current.fillAlpha); - this.endPath(); - } - } - stroke() { - const current = this.current; - if (current.element) { - this._setStrokeAttributes(current.element); - current.element.setAttributeNS(null, "fill", "none"); - this.endPath(); - } - } - _setStrokeAttributes(element, lineWidthScale = 1) { - const current = this.current; - let dashArray = current.dashArray; - if (lineWidthScale !== 1 && dashArray.length > 0) { - dashArray = dashArray.map(function (value) { - return lineWidthScale * value; + static #getCtx(lang = null) { + let canvasContext = this.#canvasContexts.get(lang ||= ""); + if (!canvasContext) { + const canvas = document.createElement("canvas"); + canvas.className = "hiddenCanvasElement"; + canvas.lang = lang; + document.body.append(canvas); + canvasContext = canvas.getContext("2d", { + alpha: false, + willReadFrequently: true }); + this.#canvasContexts.set(lang, canvasContext); } - element.setAttributeNS(null, "stroke", current.strokeColor); - element.setAttributeNS(null, "stroke-opacity", current.strokeAlpha); - element.setAttributeNS(null, "stroke-miterlimit", pf(current.miterLimit)); - element.setAttributeNS(null, "stroke-linecap", current.lineCap); - element.setAttributeNS(null, "stroke-linejoin", current.lineJoin); - element.setAttributeNS(null, "stroke-width", pf(lineWidthScale * current.lineWidth) + "px"); - element.setAttributeNS(null, "stroke-dasharray", dashArray.map(pf).join(" ")); - element.setAttributeNS(null, "stroke-dashoffset", pf(lineWidthScale * current.dashPhase) + "px"); + return canvasContext; } - eoFill() { - this.current.element?.setAttributeNS(null, "fill-rule", "evenodd"); - this.fill(); - } - fillStroke() { - this.stroke(); - this.fill(); - } - eoFillStroke() { - this.current.element?.setAttributeNS(null, "fill-rule", "evenodd"); - this.fillStroke(); - } - closeStroke() { - this.closePath(); - this.stroke(); - } - closeFillStroke() { - this.closePath(); - this.fillStroke(); - } - closeEOFillStroke() { - this.closePath(); - this.eoFillStroke(); - } - paintSolidColorImageMask() { - const rect = this.svgFactory.createElement("svg:rect"); - rect.setAttributeNS(null, "x", "0"); - rect.setAttributeNS(null, "y", "0"); - rect.setAttributeNS(null, "width", "1px"); - rect.setAttributeNS(null, "height", "1px"); - rect.setAttributeNS(null, "fill", this.current.fillColor); - this._ensureTransformGroup().append(rect); - } - paintImageXObject(objId) { - const imgData = this.getObject(objId); - if (!imgData) { - (0, _util.warn)(`Dependent image with object ID ${objId} is not ready yet`); + static #ensureMinFontSizeComputed() { + if (this.#minFontSize !== null) { return; } - this.paintInlineImageXObject(imgData); + const div = document.createElement("div"); + div.style.opacity = 0; + div.style.lineHeight = 1; + div.style.fontSize = "1px"; + div.style.position = "absolute"; + div.textContent = "X"; + document.body.append(div); + this.#minFontSize = div.getBoundingClientRect().height; + div.remove(); } - paintInlineImageXObject(imgData, mask) { - const width = imgData.width; - const height = imgData.height; - const imgSrc = convertImgDataToPng(imgData, this.forceDataSchema, !!mask); - const cliprect = this.svgFactory.createElement("svg:rect"); - cliprect.setAttributeNS(null, "x", "0"); - cliprect.setAttributeNS(null, "y", "0"); - cliprect.setAttributeNS(null, "width", pf(width)); - cliprect.setAttributeNS(null, "height", pf(height)); - this.current.element = cliprect; - this.clip("nonzero"); - const imgEl = this.svgFactory.createElement("svg:image"); - imgEl.setAttributeNS(XLINK_NS, "xlink:href", imgSrc); - imgEl.setAttributeNS(null, "x", "0"); - imgEl.setAttributeNS(null, "y", pf(-height)); - imgEl.setAttributeNS(null, "width", pf(width) + "px"); - imgEl.setAttributeNS(null, "height", pf(height) + "px"); - imgEl.setAttributeNS(null, "transform", `scale(${pf(1 / width)} ${pf(-1 / height)})`); - if (mask) { - mask.append(imgEl); - } else { - this._ensureTransformGroup().append(imgEl); + static #getAscent(fontFamily, lang) { + const cachedAscent = this.#ascentCache.get(fontFamily); + if (cachedAscent) { + return cachedAscent; } - } - paintImageMaskXObject(img) { - const imgData = this.getObject(img.data, img); - if (imgData.bitmap) { - (0, _util.warn)("paintImageMaskXObject: ImageBitmap support is not implemented, " + "ensure that the `isOffscreenCanvasSupported` API parameter is disabled."); - return; + const ctx = this.#getCtx(lang); + const savedFont = ctx.font; + ctx.canvas.width = ctx.canvas.height = DEFAULT_FONT_SIZE; + ctx.font = `${DEFAULT_FONT_SIZE}px ${fontFamily}`; + const metrics = ctx.measureText(""); + let ascent = metrics.fontBoundingBoxAscent; + let descent = Math.abs(metrics.fontBoundingBoxDescent); + if (ascent) { + const ratio = ascent / (ascent + descent); + this.#ascentCache.set(fontFamily, ratio); + ctx.canvas.width = ctx.canvas.height = 0; + ctx.font = savedFont; + return ratio; } - const current = this.current; - const width = imgData.width; - const height = imgData.height; - const fillColor = current.fillColor; - current.maskId = `mask${maskCount++}`; - const mask = this.svgFactory.createElement("svg:mask"); - mask.setAttributeNS(null, "id", current.maskId); - const rect = this.svgFactory.createElement("svg:rect"); - rect.setAttributeNS(null, "x", "0"); - rect.setAttributeNS(null, "y", "0"); - rect.setAttributeNS(null, "width", pf(width)); - rect.setAttributeNS(null, "height", pf(height)); - rect.setAttributeNS(null, "fill", fillColor); - rect.setAttributeNS(null, "mask", `url(#${current.maskId})`); - this.defs.append(mask); - this._ensureTransformGroup().append(rect); - this.paintInlineImageXObject(imgData, mask); - } - paintFormXObjectBegin(matrix, bbox) { - if (Array.isArray(matrix) && matrix.length === 6) { - this.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); - } - if (bbox) { - const width = bbox[2] - bbox[0]; - const height = bbox[3] - bbox[1]; - const cliprect = this.svgFactory.createElement("svg:rect"); - cliprect.setAttributeNS(null, "x", bbox[0]); - cliprect.setAttributeNS(null, "y", bbox[1]); - cliprect.setAttributeNS(null, "width", pf(width)); - cliprect.setAttributeNS(null, "height", pf(height)); - this.current.element = cliprect; - this.clip("nonzero"); - this.endPath(); - } - } - paintFormXObjectEnd() {} - _initialize(viewport) { - const svg = this.svgFactory.create(viewport.width, viewport.height); - const definitions = this.svgFactory.createElement("svg:defs"); - svg.append(definitions); - this.defs = definitions; - const rootGroup = this.svgFactory.createElement("svg:g"); - rootGroup.setAttributeNS(null, "transform", pm(viewport.transform)); - svg.append(rootGroup); - this.svg = rootGroup; - return svg; - } - _ensureClipGroup() { - if (!this.current.clipGroup) { - const clipGroup = this.svgFactory.createElement("svg:g"); - clipGroup.setAttributeNS(null, "clip-path", this.current.activeClipUrl); - this.svg.append(clipGroup); - this.current.clipGroup = clipGroup; - } - return this.current.clipGroup; - } - _ensureTransformGroup() { - if (!this.tgrp) { - this.tgrp = this.svgFactory.createElement("svg:g"); - this.tgrp.setAttributeNS(null, "transform", pm(this.transformMatrix)); - if (this.current.activeClipUrl) { - this._ensureClipGroup().append(this.tgrp); - } else { - this.svg.append(this.tgrp); + ctx.strokeStyle = "red"; + ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE); + ctx.strokeText("g", 0, 0); + let pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data; + descent = 0; + for (let i = pixels.length - 1 - 3; i >= 0; i -= 4) { + if (pixels[i] > 0) { + descent = Math.ceil(i / 4 / DEFAULT_FONT_SIZE); + break; } } - return this.tgrp; + ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE); + ctx.strokeText("A", 0, DEFAULT_FONT_SIZE); + pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data; + ascent = 0; + for (let i = 0, ii = pixels.length; i < ii; i += 4) { + if (pixels[i] > 0) { + ascent = DEFAULT_FONT_SIZE - Math.floor(i / 4 / DEFAULT_FONT_SIZE); + break; + } + } + ctx.canvas.width = ctx.canvas.height = 0; + ctx.font = savedFont; + const ratio = ascent ? ascent / (ascent + descent) : DEFAULT_FONT_ASCENT; + this.#ascentCache.set(fontFamily, ratio); + return ratio; } } -exports.SVGGraphics = SVGGraphics; -/***/ }), -/* 25 */ -/***/ ((__unused_webpack_module, exports) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.XfaText = void 0; +;// CONCATENATED MODULE: ./src/display/xfa_text.js class XfaText { static textContent(xfa) { const items = []; @@ -12491,3795 +10947,1895 @@ class XfaText { return !(name === "textarea" || name === "input" || name === "option" || name === "select"); } } -exports.XfaText = XfaText; -/***/ }), -/* 26 */ -/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { +;// CONCATENATED MODULE: ./src/display/api.js -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.TextLayerRenderTask = void 0; -exports.renderTextLayer = renderTextLayer; -exports.updateTextLayer = updateTextLayer; -var _util = __w_pdfjs_require__(1); -var _display_utils = __w_pdfjs_require__(6); -const MAX_TEXT_DIVS_TO_RENDER = 100000; -const DEFAULT_FONT_SIZE = 30; -const DEFAULT_FONT_ASCENT = 0.8; -const ascentCache = new Map(); -function getCtx(size, isOffscreenCanvasSupported) { - let ctx; - if (isOffscreenCanvasSupported && _util.FeatureTest.isOffscreenCanvasSupported) { - ctx = new OffscreenCanvas(size, size).getContext("2d", { - alpha: false - }); - } else { - const canvas = document.createElement("canvas"); - canvas.width = canvas.height = size; - ctx = canvas.getContext("2d", { - alpha: false - }); - } - return ctx; -} -function getAscent(fontFamily, isOffscreenCanvasSupported) { - const cachedAscent = ascentCache.get(fontFamily); - if (cachedAscent) { - return cachedAscent; - } - const ctx = getCtx(DEFAULT_FONT_SIZE, isOffscreenCanvasSupported); - ctx.font = `${DEFAULT_FONT_SIZE}px ${fontFamily}`; - const metrics = ctx.measureText(""); - let ascent = metrics.fontBoundingBoxAscent; - let descent = Math.abs(metrics.fontBoundingBoxDescent); - if (ascent) { - const ratio = ascent / (ascent + descent); - ascentCache.set(fontFamily, ratio); - ctx.canvas.width = ctx.canvas.height = 0; - return ratio; - } - ctx.strokeStyle = "red"; - ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE); - ctx.strokeText("g", 0, 0); - let pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data; - descent = 0; - for (let i = pixels.length - 1 - 3; i >= 0; i -= 4) { - if (pixels[i] > 0) { - descent = Math.ceil(i / 4 / DEFAULT_FONT_SIZE); - break; - } - } - ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE); - ctx.strokeText("A", 0, DEFAULT_FONT_SIZE); - pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data; - ascent = 0; - for (let i = 0, ii = pixels.length; i < ii; i += 4) { - if (pixels[i] > 0) { - ascent = DEFAULT_FONT_SIZE - Math.floor(i / 4 / DEFAULT_FONT_SIZE); - break; - } - } - ctx.canvas.width = ctx.canvas.height = 0; - if (ascent) { - const ratio = ascent / (ascent + descent); - ascentCache.set(fontFamily, ratio); - return ratio; - } - ascentCache.set(fontFamily, DEFAULT_FONT_ASCENT); - return DEFAULT_FONT_ASCENT; -} -function appendText(task, geom, styles) { - const textDiv = document.createElement("span"); - const textDivProperties = { - angle: 0, - canvasWidth: 0, - hasText: geom.str !== "", - hasEOL: geom.hasEOL, - fontSize: 0 - }; - task._textDivs.push(textDiv); - const tx = _util.Util.transform(task._transform, geom.transform); - let angle = Math.atan2(tx[1], tx[0]); - const style = styles[geom.fontName]; - if (style.vertical) { - angle += Math.PI / 2; - } - const fontHeight = Math.hypot(tx[2], tx[3]); - const fontAscent = fontHeight * getAscent(style.fontFamily, task._isOffscreenCanvasSupported); - let left, top; - if (angle === 0) { - left = tx[4]; - top = tx[5] - fontAscent; - } else { - left = tx[4] + fontAscent * Math.sin(angle); - top = tx[5] - fontAscent * Math.cos(angle); - } - const scaleFactorStr = "calc(var(--scale-factor)*"; - const divStyle = textDiv.style; - if (task._container === task._rootContainer) { - divStyle.left = `${(100 * left / task._pageWidth).toFixed(2)}%`; - divStyle.top = `${(100 * top / task._pageHeight).toFixed(2)}%`; - } else { - divStyle.left = `${scaleFactorStr}${left.toFixed(2)}px)`; - divStyle.top = `${scaleFactorStr}${top.toFixed(2)}px)`; - } - divStyle.fontSize = `${scaleFactorStr}${fontHeight.toFixed(2)}px)`; - divStyle.fontFamily = style.fontFamily; - textDivProperties.fontSize = fontHeight; - textDiv.setAttribute("role", "presentation"); - textDiv.textContent = geom.str; - textDiv.dir = geom.dir; - if (task._fontInspectorEnabled) { - textDiv.dataset.fontName = geom.fontName; - } - if (angle !== 0) { - textDivProperties.angle = angle * (180 / Math.PI); - } - let shouldScaleText = false; - if (geom.str.length > 1) { - shouldScaleText = true; - } else if (geom.str !== " " && geom.transform[0] !== geom.transform[3]) { - const absScaleX = Math.abs(geom.transform[0]), - absScaleY = Math.abs(geom.transform[3]); - if (absScaleX !== absScaleY && Math.max(absScaleX, absScaleY) / Math.min(absScaleX, absScaleY) > 1.5) { - shouldScaleText = true; - } - } - if (shouldScaleText) { - textDivProperties.canvasWidth = style.vertical ? geom.height : geom.width; - } - task._textDivProperties.set(textDiv, textDivProperties); - if (task._isReadableStream) { - task._layoutText(textDiv); - } -} -function layout(params) { - const { - div, - scale, - properties, - ctx, - prevFontSize, - prevFontFamily - } = params; - const { - style - } = div; - let transform = ""; - if (properties.canvasWidth !== 0 && properties.hasText) { - const { - fontFamily - } = style; - const { - canvasWidth, - fontSize - } = properties; - if (prevFontSize !== fontSize || prevFontFamily !== fontFamily) { - ctx.font = `${fontSize * scale}px ${fontFamily}`; - params.prevFontSize = fontSize; - params.prevFontFamily = fontFamily; - } - const { - width - } = ctx.measureText(div.textContent); - if (width > 0) { - transform = `scaleX(${canvasWidth * scale / width})`; - } - } - if (properties.angle !== 0) { - transform = `rotate(${properties.angle}deg) ${transform}`; - } - if (transform.length > 0) { - style.transform = transform; - } -} -function render(task) { - if (task._canceled) { - return; - } - const textDivs = task._textDivs; - const capability = task._capability; - const textDivsLength = textDivs.length; - if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) { - capability.resolve(); - return; - } - if (!task._isReadableStream) { - for (const textDiv of textDivs) { - task._layoutText(textDiv); - } - } - capability.resolve(); -} -class TextLayerRenderTask { - constructor({ - textContentSource, - container, - viewport, - textDivs, - textDivProperties, - textContentItemsStr, - isOffscreenCanvasSupported - }) { - this._textContentSource = textContentSource; - this._isReadableStream = textContentSource instanceof ReadableStream; - this._container = this._rootContainer = container; - this._textDivs = textDivs || []; - this._textContentItemsStr = textContentItemsStr || []; - this._isOffscreenCanvasSupported = isOffscreenCanvasSupported; - this._fontInspectorEnabled = !!globalThis.FontInspector?.enabled; - this._reader = null; - this._textDivProperties = textDivProperties || new WeakMap(); - this._canceled = false; - this._capability = new _util.PromiseCapability(); - this._layoutTextParams = { - prevFontSize: null, - prevFontFamily: null, - div: null, - scale: viewport.scale * (globalThis.devicePixelRatio || 1), - properties: null, - ctx: getCtx(0, isOffscreenCanvasSupported) + + + + + + + + + + + + + +const DEFAULT_RANGE_CHUNK_SIZE = 65536; +const RENDERING_CANCELLED_TIMEOUT = 100; +const DELAYED_CLEANUP_TIMEOUT = 5000; +const DefaultCanvasFactory = isNodeJS ? NodeCanvasFactory : DOMCanvasFactory; +const DefaultCMapReaderFactory = isNodeJS ? NodeCMapReaderFactory : DOMCMapReaderFactory; +const DefaultFilterFactory = isNodeJS ? NodeFilterFactory : DOMFilterFactory; +const DefaultStandardFontDataFactory = isNodeJS ? NodeStandardFontDataFactory : DOMStandardFontDataFactory; +function getDocument(src = {}) { + if (typeof src === "string" || src instanceof URL) { + src = { + url: src }; - const { - pageWidth, - pageHeight, - pageX, - pageY - } = viewport.rawDims; - this._transform = [1, 0, 0, -1, -pageX, pageY + pageHeight]; - this._pageWidth = pageWidth; - this._pageHeight = pageHeight; - (0, _display_utils.setLayerDimensions)(container, viewport); - this._capability.promise.finally(() => { - this._layoutTextParams = null; - }).catch(() => {}); + } else if (src instanceof ArrayBuffer || ArrayBuffer.isView(src)) { + src = { + data: src + }; + } + const task = new PDFDocumentLoadingTask(); + const { + docId + } = task; + const url = src.url ? getUrlProp(src.url) : null; + const data = src.data ? getDataProp(src.data) : null; + const httpHeaders = src.httpHeaders || null; + const withCredentials = src.withCredentials === true; + const password = src.password ?? null; + const rangeTransport = src.range instanceof PDFDataRangeTransport ? src.range : null; + const rangeChunkSize = Number.isInteger(src.rangeChunkSize) && src.rangeChunkSize > 0 ? src.rangeChunkSize : DEFAULT_RANGE_CHUNK_SIZE; + let worker = src.worker instanceof PDFWorker ? src.worker : null; + const verbosity = src.verbosity; + const docBaseUrl = typeof src.docBaseUrl === "string" && !isDataScheme(src.docBaseUrl) ? src.docBaseUrl : null; + const cMapUrl = typeof src.cMapUrl === "string" ? src.cMapUrl : null; + const cMapPacked = src.cMapPacked !== false; + const CMapReaderFactory = src.CMapReaderFactory || DefaultCMapReaderFactory; + const standardFontDataUrl = typeof src.standardFontDataUrl === "string" ? src.standardFontDataUrl : null; + const StandardFontDataFactory = src.StandardFontDataFactory || DefaultStandardFontDataFactory; + const ignoreErrors = src.stopAtErrors !== true; + const maxImageSize = Number.isInteger(src.maxImageSize) && src.maxImageSize > -1 ? src.maxImageSize : -1; + const isEvalSupported = src.isEvalSupported !== false; + const isOffscreenCanvasSupported = typeof src.isOffscreenCanvasSupported === "boolean" ? src.isOffscreenCanvasSupported : !isNodeJS; + const canvasMaxAreaInBytes = Number.isInteger(src.canvasMaxAreaInBytes) ? src.canvasMaxAreaInBytes : -1; + const disableFontFace = typeof src.disableFontFace === "boolean" ? src.disableFontFace : isNodeJS; + const fontExtraProperties = src.fontExtraProperties === true; + const enableXfa = src.enableXfa === true; + const ownerDocument = src.ownerDocument || globalThis.document; + const disableRange = src.disableRange === true; + const disableStream = src.disableStream === true; + const disableAutoFetch = src.disableAutoFetch === true; + const pdfBug = src.pdfBug === true; + const enableHWA = src.enableHWA === true; + const length = rangeTransport ? rangeTransport.length : src.length ?? NaN; + const useSystemFonts = typeof src.useSystemFonts === "boolean" ? src.useSystemFonts : !isNodeJS && !disableFontFace; + const useWorkerFetch = typeof src.useWorkerFetch === "boolean" ? src.useWorkerFetch : CMapReaderFactory === DOMCMapReaderFactory && StandardFontDataFactory === DOMStandardFontDataFactory && cMapUrl && standardFontDataUrl && isValidFetchUrl(cMapUrl, document.baseURI) && isValidFetchUrl(standardFontDataUrl, document.baseURI); + const canvasFactory = src.canvasFactory || new DefaultCanvasFactory({ + ownerDocument, + enableHWA + }); + const filterFactory = src.filterFactory || new DefaultFilterFactory({ + docId, + ownerDocument + }); + const styleElement = null; + setVerbosityLevel(verbosity); + const transportFactory = { + canvasFactory, + filterFactory + }; + if (!useWorkerFetch) { + transportFactory.cMapReaderFactory = new CMapReaderFactory({ + baseUrl: cMapUrl, + isCompressed: cMapPacked + }); + transportFactory.standardFontDataFactory = new StandardFontDataFactory({ + baseUrl: standardFontDataUrl + }); + } + if (!worker) { + const workerParams = { + verbosity, + port: GlobalWorkerOptions.workerPort + }; + worker = workerParams.port ? PDFWorker.fromPort(workerParams) : new PDFWorker(workerParams); + task._worker = worker; + } + const docParams = { + docId, + apiVersion: "4.6.82", + data, + password, + disableAutoFetch, + rangeChunkSize, + length, + docBaseUrl, + enableXfa, + evaluatorOptions: { + maxImageSize, + disableFontFace, + ignoreErrors, + isEvalSupported, + isOffscreenCanvasSupported, + canvasMaxAreaInBytes, + fontExtraProperties, + useSystemFonts, + cMapUrl: useWorkerFetch ? cMapUrl : null, + standardFontDataUrl: useWorkerFetch ? standardFontDataUrl : null + } + }; + const transportParams = { + disableFontFace, + fontExtraProperties, + ownerDocument, + pdfBug, + styleElement, + loadingParams: { + disableAutoFetch, + enableXfa + } + }; + worker.promise.then(function () { + if (task.destroyed) { + throw new Error("Loading aborted"); + } + if (worker.destroyed) { + throw new Error("Worker was destroyed"); + } + const workerIdPromise = worker.messageHandler.sendWithPromise("GetDocRequest", docParams, data ? [data.buffer] : null); + let networkStream; + if (rangeTransport) { + networkStream = new PDFDataTransportStream(rangeTransport, { + disableRange, + disableStream + }); + } else if (!data) { + if (!url) { + throw new Error("getDocument - no `url` parameter provided."); + } + const createPDFNetworkStream = params => { + if (isNodeJS) { + const isFetchSupported = function () { + return typeof fetch !== "undefined" && typeof Response !== "undefined" && "body" in Response.prototype; + }; + return isFetchSupported() && isValidFetchUrl(params.url) ? new PDFFetchStream(params) : new PDFNodeStream(params); + } + return isValidFetchUrl(params.url) ? new PDFFetchStream(params) : new PDFNetworkStream(params); + }; + networkStream = createPDFNetworkStream({ + url, + length, + httpHeaders, + withCredentials, + rangeChunkSize, + disableRange, + disableStream + }); + } + return workerIdPromise.then(workerId => { + if (task.destroyed) { + throw new Error("Loading aborted"); + } + if (worker.destroyed) { + throw new Error("Worker was destroyed"); + } + const messageHandler = new MessageHandler(docId, workerId, worker.port); + const transport = new WorkerTransport(messageHandler, task, networkStream, transportParams, transportFactory); + task._transport = transport; + messageHandler.send("Ready", null); + }); + }).catch(task._capability.reject); + return task; +} +function getUrlProp(val) { + if (val instanceof URL) { + return val.href; + } + try { + return new URL(val, window.location).href; + } catch { + if (isNodeJS && typeof val === "string") { + return val; + } + } + throw new Error("Invalid PDF url data: " + "either string or URL-object is expected in the url property."); +} +function getDataProp(val) { + if (isNodeJS && typeof Buffer !== "undefined" && val instanceof Buffer) { + throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`."); + } + if (val instanceof Uint8Array && val.byteLength === val.buffer.byteLength) { + return val; + } + if (typeof val === "string") { + return stringToBytes(val); + } + if (val instanceof ArrayBuffer || ArrayBuffer.isView(val) || typeof val === "object" && !isNaN(val?.length)) { + return new Uint8Array(val); + } + throw new Error("Invalid PDF binary data: either TypedArray, " + "string, or array-like object is expected in the data property."); +} +function isRefProxy(ref) { + return typeof ref === "object" && Number.isInteger(ref?.num) && ref.num >= 0 && Number.isInteger(ref?.gen) && ref.gen >= 0; +} +class PDFDocumentLoadingTask { + static #docId = 0; + constructor() { + this._capability = Promise.withResolvers(); + this._transport = null; + this._worker = null; + this.docId = `d${PDFDocumentLoadingTask.#docId++}`; + this.destroyed = false; + this.onPassword = null; + this.onProgress = null; } get promise() { return this._capability.promise; } - cancel() { - this._canceled = true; - if (this._reader) { - this._reader.cancel(new _util.AbortException("TextLayer task cancelled.")).catch(() => {}); - this._reader = null; - } - this._capability.reject(new _util.AbortException("TextLayer task cancelled.")); - } - _processItems(items, styleCache) { - for (const item of items) { - if (item.str === undefined) { - if (item.type === "beginMarkedContentProps" || item.type === "beginMarkedContent") { - const parent = this._container; - this._container = document.createElement("span"); - this._container.classList.add("markedContent"); - if (item.id !== null) { - this._container.setAttribute("id", `${item.id}`); - } - parent.append(this._container); - } else if (item.type === "endMarkedContent") { - this._container = this._container.parentNode; - } - continue; + async destroy() { + this.destroyed = true; + try { + if (this._worker?.port) { + this._worker._pendingDestroy = true; } - this._textContentItemsStr.push(item.str); - appendText(this, item, styleCache); + await this._transport?.destroy(); + } catch (ex) { + if (this._worker?.port) { + delete this._worker._pendingDestroy; + } + throw ex; } - } - _layoutText(textDiv) { - const textDivProperties = this._layoutTextParams.properties = this._textDivProperties.get(textDiv); - this._layoutTextParams.div = textDiv; - layout(this._layoutTextParams); - if (textDivProperties.hasText) { - this._container.append(textDiv); - } - if (textDivProperties.hasEOL) { - const br = document.createElement("br"); - br.setAttribute("role", "presentation"); - this._container.append(br); - } - } - _render() { - const capability = new _util.PromiseCapability(); - let styleCache = Object.create(null); - if (this._isReadableStream) { - const pump = () => { - this._reader.read().then(({ - value, - done - }) => { - if (done) { - capability.resolve(); - return; - } - Object.assign(styleCache, value.styles); - this._processItems(value.items, styleCache); - pump(); - }, capability.reject); - }; - this._reader = this._textContentSource.getReader(); - pump(); - } else if (this._textContentSource) { - const { - items, - styles - } = this._textContentSource; - this._processItems(items, styles); - capability.resolve(); - } else { - throw new Error('No "textContentSource" parameter specified.'); - } - capability.promise.then(() => { - styleCache = null; - render(this); - }, this._capability.reject); - } -} -exports.TextLayerRenderTask = TextLayerRenderTask; -function renderTextLayer(params) { - if (!params.textContentSource && (params.textContent || params.textContentStream)) { - (0, _display_utils.deprecated)("The TextLayerRender `textContent`/`textContentStream` parameters " + "will be removed in the future, please use `textContentSource` instead."); - params.textContentSource = params.textContent || params.textContentStream; - } - const { - container, - viewport - } = params; - const style = getComputedStyle(container); - const visibility = style.getPropertyValue("visibility"); - const scaleFactor = parseFloat(style.getPropertyValue("--scale-factor")); - if (visibility === "visible" && (!scaleFactor || Math.abs(scaleFactor - viewport.scale) > 1e-5)) { - console.error("The `--scale-factor` CSS-variable must be set, " + "to the same value as `viewport.scale`, " + "either on the `container`-element itself or higher up in the DOM."); - } - const task = new TextLayerRenderTask(params); - task._render(); - return task; -} -function updateTextLayer({ - container, - viewport, - textDivs, - textDivProperties, - isOffscreenCanvasSupported, - mustRotate = true, - mustRescale = true -}) { - if (mustRotate) { - (0, _display_utils.setLayerDimensions)(container, { - rotation: viewport.rotation - }); - } - if (mustRescale) { - const ctx = getCtx(0, isOffscreenCanvasSupported); - const scale = viewport.scale * (globalThis.devicePixelRatio || 1); - const params = { - prevFontSize: null, - prevFontFamily: null, - div: null, - scale, - properties: null, - ctx - }; - for (const div of textDivs) { - params.properties = textDivProperties.get(div); - params.div = div; - layout(params); + this._transport = null; + if (this._worker) { + this._worker.destroy(); + this._worker = null; } } } - -/***/ }), -/* 27 */ -/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.AnnotationEditorLayer = void 0; -var _util = __w_pdfjs_require__(1); -var _editor = __w_pdfjs_require__(4); -var _freetext = __w_pdfjs_require__(28); -var _ink = __w_pdfjs_require__(33); -var _display_utils = __w_pdfjs_require__(6); -var _stamp = __w_pdfjs_require__(34); -class AnnotationEditorLayer { - #accessibilityManager; - #allowClick = false; - #annotationLayer = null; - #boundPointerup = this.pointerup.bind(this); - #boundPointerdown = this.pointerdown.bind(this); - #editors = new Map(); - #hadPointerDown = false; - #isCleaningUp = false; - #isDisabling = false; - #uiManager; - static _initialized = false; - constructor({ - uiManager, - pageIndex, - div, - accessibilityManager, - annotationLayer, - viewport, - l10n - }) { - const editorTypes = [_freetext.FreeTextEditor, _ink.InkEditor, _stamp.StampEditor]; - if (!AnnotationEditorLayer._initialized) { - AnnotationEditorLayer._initialized = true; - for (const editorType of editorTypes) { - editorType.initialize(l10n); +class PDFDataRangeTransport { + constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) { + this.length = length; + this.initialData = initialData; + this.progressiveDone = progressiveDone; + this.contentDispositionFilename = contentDispositionFilename; + this._rangeListeners = []; + this._progressListeners = []; + this._progressiveReadListeners = []; + this._progressiveDoneListeners = []; + this._readyCapability = Promise.withResolvers(); + } + addRangeListener(listener) { + this._rangeListeners.push(listener); + } + addProgressListener(listener) { + this._progressListeners.push(listener); + } + addProgressiveReadListener(listener) { + this._progressiveReadListeners.push(listener); + } + addProgressiveDoneListener(listener) { + this._progressiveDoneListeners.push(listener); + } + onDataRange(begin, chunk) { + for (const listener of this._rangeListeners) { + listener(begin, chunk); + } + } + onDataProgress(loaded, total) { + this._readyCapability.promise.then(() => { + for (const listener of this._progressListeners) { + listener(loaded, total); } - } - uiManager.registerEditorTypes(editorTypes); - this.#uiManager = uiManager; - this.pageIndex = pageIndex; - this.div = div; - this.#accessibilityManager = accessibilityManager; - this.#annotationLayer = annotationLayer; - this.viewport = viewport; - this.#uiManager.addLayer(this); - } - get isEmpty() { - return this.#editors.size === 0; - } - updateToolbar(mode) { - this.#uiManager.updateToolbar(mode); - } - updateMode(mode = this.#uiManager.getMode()) { - this.#cleanup(); - if (mode === _util.AnnotationEditorType.INK) { - this.addInkEditorIfNeeded(false); - this.disableClick(); - } else { - this.enableClick(); - } - if (mode !== _util.AnnotationEditorType.NONE) { - this.div.classList.toggle("freeTextEditing", mode === _util.AnnotationEditorType.FREETEXT); - this.div.classList.toggle("inkEditing", mode === _util.AnnotationEditorType.INK); - this.div.classList.toggle("stampEditing", mode === _util.AnnotationEditorType.STAMP); - this.div.hidden = false; - } - } - addInkEditorIfNeeded(isCommitting) { - if (!isCommitting && this.#uiManager.getMode() !== _util.AnnotationEditorType.INK) { - return; - } - if (!isCommitting) { - for (const editor of this.#editors.values()) { - if (editor.isEmpty()) { - editor.setInBackground(); - return; - } - } - } - const editor = this.#createAndAddNewEditor({ - offsetX: 0, - offsetY: 0 - }, false); - editor.setInBackground(); - } - setEditingState(isEditing) { - this.#uiManager.setEditingState(isEditing); - } - addCommands(params) { - this.#uiManager.addCommands(params); - } - enable() { - this.div.style.pointerEvents = "auto"; - const annotationElementIds = new Set(); - for (const editor of this.#editors.values()) { - editor.enableEditing(); - if (editor.annotationElementId) { - annotationElementIds.add(editor.annotationElementId); - } - } - if (!this.#annotationLayer) { - return; - } - const editables = this.#annotationLayer.getEditableAnnotations(); - for (const editable of editables) { - editable.hide(); - if (this.#uiManager.isDeletedAnnotationElement(editable.data.id)) { - continue; - } - if (annotationElementIds.has(editable.data.id)) { - continue; - } - const editor = this.deserialize(editable); - if (!editor) { - continue; - } - this.addOrRebuild(editor); - editor.enableEditing(); - } - } - disable() { - this.#isDisabling = true; - this.div.style.pointerEvents = "none"; - const hiddenAnnotationIds = new Set(); - for (const editor of this.#editors.values()) { - editor.disableEditing(); - if (!editor.annotationElementId || editor.serialize() !== null) { - hiddenAnnotationIds.add(editor.annotationElementId); - continue; - } - this.getEditableAnnotation(editor.annotationElementId)?.show(); - editor.remove(); - } - if (this.#annotationLayer) { - const editables = this.#annotationLayer.getEditableAnnotations(); - for (const editable of editables) { - const { - id - } = editable.data; - if (hiddenAnnotationIds.has(id) || this.#uiManager.isDeletedAnnotationElement(id)) { - continue; - } - editable.show(); - } - } - this.#cleanup(); - if (this.isEmpty) { - this.div.hidden = true; - } - this.#isDisabling = false; - } - getEditableAnnotation(id) { - return this.#annotationLayer?.getEditableAnnotation(id) || null; - } - setActiveEditor(editor) { - const currentActive = this.#uiManager.getActive(); - if (currentActive === editor) { - return; - } - this.#uiManager.setActiveEditor(editor); - } - enableClick() { - this.div.addEventListener("pointerdown", this.#boundPointerdown); - this.div.addEventListener("pointerup", this.#boundPointerup); - } - disableClick() { - this.div.removeEventListener("pointerdown", this.#boundPointerdown); - this.div.removeEventListener("pointerup", this.#boundPointerup); - } - attach(editor) { - this.#editors.set(editor.id, editor); - const { - annotationElementId - } = editor; - if (annotationElementId && this.#uiManager.isDeletedAnnotationElement(annotationElementId)) { - this.#uiManager.removeDeletedAnnotationElement(editor); - } - } - detach(editor) { - this.#editors.delete(editor.id); - this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv); - if (!this.#isDisabling && editor.annotationElementId) { - this.#uiManager.addDeletedAnnotationElement(editor); - } - } - remove(editor) { - this.detach(editor); - this.#uiManager.removeEditor(editor); - if (editor.div.contains(document.activeElement)) { - setTimeout(() => { - this.#uiManager.focusMainContainer(); - }, 0); - } - editor.div.remove(); - editor.isAttachedToDOM = false; - if (!this.#isCleaningUp) { - this.addInkEditorIfNeeded(false); - } - } - changeParent(editor) { - if (editor.parent === this) { - return; - } - if (editor.annotationElementId) { - this.#uiManager.addDeletedAnnotationElement(editor.annotationElementId); - _editor.AnnotationEditor.deleteAnnotationElement(editor); - editor.annotationElementId = null; - } - this.attach(editor); - editor.parent?.detach(editor); - editor.setParent(this); - if (editor.div && editor.isAttachedToDOM) { - editor.div.remove(); - this.div.append(editor.div); - } - } - add(editor) { - this.changeParent(editor); - this.#uiManager.addEditor(editor); - this.attach(editor); - if (!editor.isAttachedToDOM) { - const div = editor.render(); - this.div.append(div); - editor.isAttachedToDOM = true; - } - editor.fixAndSetPosition(); - editor.onceAdded(); - this.#uiManager.addToAnnotationStorage(editor); - } - moveEditorInDOM(editor) { - if (!editor.isAttachedToDOM) { - return; - } - const { - activeElement - } = document; - if (editor.div.contains(activeElement)) { - editor._focusEventsAllowed = false; - setTimeout(() => { - if (!editor.div.contains(document.activeElement)) { - editor.div.addEventListener("focusin", () => { - editor._focusEventsAllowed = true; - }, { - once: true - }); - activeElement.focus(); - } else { - editor._focusEventsAllowed = true; - } - }, 0); - } - editor._structTreeParentId = this.#accessibilityManager?.moveElementInDOM(this.div, editor.div, editor.contentDiv, true); - } - addOrRebuild(editor) { - if (editor.needsToBeRebuilt()) { - editor.rebuild(); - } else { - this.add(editor); - } - } - addUndoableEditor(editor) { - const cmd = () => editor._uiManager.rebuild(editor); - const undo = () => { - editor.remove(); - }; - this.addCommands({ - cmd, - undo, - mustExec: false }); } - getNextId() { - return this.#uiManager.getId(); - } - #createNewEditor(params) { - switch (this.#uiManager.getMode()) { - case _util.AnnotationEditorType.FREETEXT: - return new _freetext.FreeTextEditor(params); - case _util.AnnotationEditorType.INK: - return new _ink.InkEditor(params); - case _util.AnnotationEditorType.STAMP: - return new _stamp.StampEditor(params); - } - return null; - } - pasteEditor(mode, params) { - this.#uiManager.updateToolbar(mode); - this.#uiManager.updateMode(mode); - const { - offsetX, - offsetY - } = this.#getCenterPoint(); - const id = this.getNextId(); - const editor = this.#createNewEditor({ - parent: this, - id, - x: offsetX, - y: offsetY, - uiManager: this.#uiManager, - isCentered: true, - ...params + onDataProgressiveRead(chunk) { + this._readyCapability.promise.then(() => { + for (const listener of this._progressiveReadListeners) { + listener(chunk); + } }); - if (editor) { - this.add(editor); - } } - deserialize(data) { - switch (data.annotationType ?? data.annotationEditorType) { - case _util.AnnotationEditorType.FREETEXT: - return _freetext.FreeTextEditor.deserialize(data, this, this.#uiManager); - case _util.AnnotationEditorType.INK: - return _ink.InkEditor.deserialize(data, this, this.#uiManager); - case _util.AnnotationEditorType.STAMP: - return _stamp.StampEditor.deserialize(data, this, this.#uiManager); - } - return null; - } - #createAndAddNewEditor(event, isCentered) { - const id = this.getNextId(); - const editor = this.#createNewEditor({ - parent: this, - id, - x: event.offsetX, - y: event.offsetY, - uiManager: this.#uiManager, - isCentered + onDataProgressiveDone() { + this._readyCapability.promise.then(() => { + for (const listener of this._progressiveDoneListeners) { + listener(); + } }); - if (editor) { - this.add(editor); - } - return editor; } - #getCenterPoint() { + transportReady() { + this._readyCapability.resolve(); + } + requestDataRange(begin, end) { + unreachable("Abstract method PDFDataRangeTransport.requestDataRange"); + } + abort() {} +} +class PDFDocumentProxy { + constructor(pdfInfo, transport) { + this._pdfInfo = pdfInfo; + this._transport = transport; + } + get annotationStorage() { + return this._transport.annotationStorage; + } + get filterFactory() { + return this._transport.filterFactory; + } + get numPages() { + return this._pdfInfo.numPages; + } + get fingerprints() { + return this._pdfInfo.fingerprints; + } + get isPureXfa() { + return shadow(this, "isPureXfa", !!this._transport._htmlForXfa); + } + get allXfaHtml() { + return this._transport._htmlForXfa; + } + getPage(pageNumber) { + return this._transport.getPage(pageNumber); + } + getPageIndex(ref) { + return this._transport.getPageIndex(ref); + } + getDestinations() { + return this._transport.getDestinations(); + } + getDestination(id) { + return this._transport.getDestination(id); + } + getPageLabels() { + return this._transport.getPageLabels(); + } + getPageLayout() { + return this._transport.getPageLayout(); + } + getPageMode() { + return this._transport.getPageMode(); + } + getViewerPreferences() { + return this._transport.getViewerPreferences(); + } + getOpenAction() { + return this._transport.getOpenAction(); + } + getAttachments() { + return this._transport.getAttachments(); + } + getJSActions() { + return this._transport.getDocJSActions(); + } + getOutline() { + return this._transport.getOutline(); + } + getOptionalContentConfig({ + intent = "display" + } = {}) { const { - x, - y, - width, - height - } = this.div.getBoundingClientRect(); - const tlX = Math.max(0, x); - const tlY = Math.max(0, y); - const brX = Math.min(window.innerWidth, x + width); - const brY = Math.min(window.innerHeight, y + height); - const centerX = (tlX + brX) / 2 - x; - const centerY = (tlY + brY) / 2 - y; - const [offsetX, offsetY] = this.viewport.rotation % 180 === 0 ? [centerX, centerY] : [centerY, centerX]; - return { - offsetX, - offsetY - }; + renderingIntent + } = this._transport.getRenderingIntent(intent); + return this._transport.getOptionalContentConfig(renderingIntent); } - addNewEditor() { - this.#createAndAddNewEditor(this.#getCenterPoint(), true); + getPermissions() { + return this._transport.getPermissions(); } - setSelected(editor) { - this.#uiManager.setSelected(editor); + getMetadata() { + return this._transport.getMetadata(); } - toggleSelected(editor) { - this.#uiManager.toggleSelected(editor); + getMarkInfo() { + return this._transport.getMarkInfo(); } - isSelected(editor) { - return this.#uiManager.isSelected(editor); + getData() { + return this._transport.getData(); } - unselect(editor) { - this.#uiManager.unselect(editor); + saveDocument() { + return this._transport.saveDocument(); } - pointerup(event) { - const { - isMac - } = _util.FeatureTest.platform; - if (event.button !== 0 || event.ctrlKey && isMac) { - return; - } - if (event.target !== this.div) { - return; - } - if (!this.#hadPointerDown) { - return; - } - this.#hadPointerDown = false; - if (!this.#allowClick) { - this.#allowClick = true; - return; - } - if (this.#uiManager.getMode() === _util.AnnotationEditorType.STAMP) { - this.#uiManager.unselectAll(); - return; - } - this.#createAndAddNewEditor(event, false); + getDownloadInfo() { + return this._transport.downloadInfoCapability.promise; } - pointerdown(event) { - if (this.#hadPointerDown) { - this.#hadPointerDown = false; - return; - } - const { - isMac - } = _util.FeatureTest.platform; - if (event.button !== 0 || event.ctrlKey && isMac) { - return; - } - if (event.target !== this.div) { - return; - } - this.#hadPointerDown = true; - const editor = this.#uiManager.getActive(); - this.#allowClick = !editor || editor.isEmpty(); - } - findNewParent(editor, x, y) { - const layer = this.#uiManager.findParent(x, y); - if (layer === null || layer === this) { - return false; - } - layer.changeParent(editor); - return true; + cleanup(keepLoadedFonts = false) { + return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa); } destroy() { - if (this.#uiManager.getActive()?.parent === this) { - this.#uiManager.commitOrRemove(); - this.#uiManager.setActiveEditor(null); - } - for (const editor of this.#editors.values()) { - this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv); - editor.setParent(null); - editor.isAttachedToDOM = false; - editor.div.remove(); - } - this.div = null; - this.#editors.clear(); - this.#uiManager.removeLayer(this); + return this.loadingTask.destroy(); } - #cleanup() { - this.#isCleaningUp = true; - for (const editor of this.#editors.values()) { - if (editor.isEmpty()) { - editor.remove(); - } - } - this.#isCleaningUp = false; + cachedPageNumber(ref) { + return this._transport.cachedPageNumber(ref); + } + get loadingParams() { + return this._transport.loadingParams; + } + get loadingTask() { + return this._transport.loadingTask; + } + getFieldObjects() { + return this._transport.getFieldObjects(); + } + hasJSActions() { + return this._transport.hasJSActions(); + } + getCalculationOrderIds() { + return this._transport.getCalculationOrderIds(); + } +} +class PDFPageProxy { + #delayedCleanupTimeout = null; + #pendingCleanup = false; + constructor(pageIndex, pageInfo, transport, pdfBug = false) { + this._pageIndex = pageIndex; + this._pageInfo = pageInfo; + this._transport = transport; + this._stats = pdfBug ? new StatTimer() : null; + this._pdfBug = pdfBug; + this.commonObjs = transport.commonObjs; + this.objs = new PDFObjects(); + this._maybeCleanupAfterRender = false; + this._intentStates = new Map(); + this.destroyed = false; + } + get pageNumber() { + return this._pageIndex + 1; + } + get rotate() { + return this._pageInfo.rotate; + } + get ref() { + return this._pageInfo.ref; + } + get userUnit() { + return this._pageInfo.userUnit; + } + get view() { + return this._pageInfo.view; + } + getViewport({ + scale, + rotation = this.rotate, + offsetX = 0, + offsetY = 0, + dontFlip = false + } = {}) { + return new PageViewport({ + viewBox: this.view, + scale, + rotation, + offsetX, + offsetY, + dontFlip + }); + } + getAnnotations({ + intent = "display" + } = {}) { + const { + renderingIntent + } = this._transport.getRenderingIntent(intent); + return this._transport.getAnnotations(this._pageIndex, renderingIntent); + } + getJSActions() { + return this._transport.getPageJSActions(this._pageIndex); + } + get filterFactory() { + return this._transport.filterFactory; + } + get isPureXfa() { + return shadow(this, "isPureXfa", !!this._transport._htmlForXfa); + } + async getXfa() { + return this._transport._htmlForXfa?.children[this._pageIndex] || null; } render({ - viewport + canvasContext, + viewport, + intent = "display", + annotationMode = AnnotationMode.ENABLE, + transform = null, + background = null, + optionalContentConfigPromise = null, + annotationCanvasMap = null, + pageColors = null, + printAnnotationStorage = null, + isEditing = false }) { - this.viewport = viewport; - (0, _display_utils.setLayerDimensions)(this.div, viewport); - for (const editor of this.#uiManager.getEditors(this.pageIndex)) { - this.add(editor); - } - this.updateMode(); - } - update({ - viewport - }) { - this.#uiManager.commitOrRemove(); - this.viewport = viewport; - (0, _display_utils.setLayerDimensions)(this.div, { - rotation: viewport.rotation - }); - this.updateMode(); - } - get pageDimensions() { + this._stats?.time("Overall"); + const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, isEditing); const { - pageWidth, - pageHeight - } = this.viewport.rawDims; - return [pageWidth, pageHeight]; - } -} -exports.AnnotationEditorLayer = AnnotationEditorLayer; - -/***/ }), -/* 28 */ -/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.FreeTextEditor = void 0; -var _util = __w_pdfjs_require__(1); -var _tools = __w_pdfjs_require__(5); -var _editor = __w_pdfjs_require__(4); -var _annotation_layer = __w_pdfjs_require__(29); -class FreeTextEditor extends _editor.AnnotationEditor { - #boundEditorDivBlur = this.editorDivBlur.bind(this); - #boundEditorDivFocus = this.editorDivFocus.bind(this); - #boundEditorDivInput = this.editorDivInput.bind(this); - #boundEditorDivKeydown = this.editorDivKeydown.bind(this); - #color; - #content = ""; - #editorDivId = `${this.id}-editor`; - #fontSize; - #initialData = null; - static _freeTextDefaultContent = ""; - static _internalPadding = 0; - static _defaultColor = null; - static _defaultFontSize = 10; - static get _keyboardManager() { - const proto = FreeTextEditor.prototype; - const arrowChecker = self => self.isEmpty(); - const small = _tools.AnnotationEditorUIManager.TRANSLATE_SMALL; - const big = _tools.AnnotationEditorUIManager.TRANSLATE_BIG; - return (0, _util.shadow)(this, "_keyboardManager", new _tools.KeyboardManager([[["ctrl+s", "mac+meta+s", "ctrl+p", "mac+meta+p"], proto.commitOrRemove, { - bubbles: true - }], [["ctrl+Enter", "mac+meta+Enter", "Escape", "mac+Escape"], proto.commitOrRemove], [["ArrowLeft", "mac+ArrowLeft"], proto._translateEmpty, { - args: [-small, 0], - checker: arrowChecker - }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], proto._translateEmpty, { - args: [-big, 0], - checker: arrowChecker - }], [["ArrowRight", "mac+ArrowRight"], proto._translateEmpty, { - args: [small, 0], - checker: arrowChecker - }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], proto._translateEmpty, { - args: [big, 0], - checker: arrowChecker - }], [["ArrowUp", "mac+ArrowUp"], proto._translateEmpty, { - args: [0, -small], - checker: arrowChecker - }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], proto._translateEmpty, { - args: [0, -big], - checker: arrowChecker - }], [["ArrowDown", "mac+ArrowDown"], proto._translateEmpty, { - args: [0, small], - checker: arrowChecker - }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], proto._translateEmpty, { - args: [0, big], - checker: arrowChecker - }]])); - } - static _type = "freetext"; - constructor(params) { - super({ - ...params, - name: "freeTextEditor" - }); - this.#color = params.color || FreeTextEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor; - this.#fontSize = params.fontSize || FreeTextEditor._defaultFontSize; - } - static initialize(l10n) { - _editor.AnnotationEditor.initialize(l10n, { - strings: ["free_text2_default_content", "editor_free_text2_aria_label"] - }); - const style = getComputedStyle(document.documentElement); - this._internalPadding = parseFloat(style.getPropertyValue("--freetext-padding")); - } - static updateDefaultParams(type, value) { - switch (type) { - case _util.AnnotationEditorParamsType.FREETEXT_SIZE: - FreeTextEditor._defaultFontSize = value; - break; - case _util.AnnotationEditorParamsType.FREETEXT_COLOR: - FreeTextEditor._defaultColor = value; - break; + renderingIntent, + cacheKey + } = intentArgs; + this.#pendingCleanup = false; + this.#abortDelayedCleanup(); + optionalContentConfigPromise ||= this._transport.getOptionalContentConfig(renderingIntent); + let intentState = this._intentStates.get(cacheKey); + if (!intentState) { + intentState = Object.create(null); + this._intentStates.set(cacheKey, intentState); } - } - updateParams(type, value) { - switch (type) { - case _util.AnnotationEditorParamsType.FREETEXT_SIZE: - this.#updateFontSize(value); - break; - case _util.AnnotationEditorParamsType.FREETEXT_COLOR: - this.#updateColor(value); - break; + if (intentState.streamReaderCancelTimeout) { + clearTimeout(intentState.streamReaderCancelTimeout); + intentState.streamReaderCancelTimeout = null; } - } - static get defaultPropertiesToUpdate() { - return [[_util.AnnotationEditorParamsType.FREETEXT_SIZE, FreeTextEditor._defaultFontSize], [_util.AnnotationEditorParamsType.FREETEXT_COLOR, FreeTextEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor]]; - } - get propertiesToUpdate() { - return [[_util.AnnotationEditorParamsType.FREETEXT_SIZE, this.#fontSize], [_util.AnnotationEditorParamsType.FREETEXT_COLOR, this.#color]]; - } - #updateFontSize(fontSize) { - const setFontsize = size => { - this.editorDiv.style.fontSize = `calc(${size}px * var(--scale-factor))`; - this.translate(0, -(size - this.#fontSize) * this.parentScale); - this.#fontSize = size; - this.#setEditorDimensions(); + const intentPrint = !!(renderingIntent & RenderingIntentFlag.PRINT); + if (!intentState.displayReadyCapability) { + intentState.displayReadyCapability = Promise.withResolvers(); + intentState.operatorList = { + fnArray: [], + argsArray: [], + lastChunk: false, + separateAnnots: null + }; + this._stats?.time("Page Request"); + this._pumpOperatorList(intentArgs); + } + const complete = error => { + intentState.renderTasks.delete(internalRenderTask); + if (this._maybeCleanupAfterRender || intentPrint) { + this.#pendingCleanup = true; + } + this.#tryCleanup(!intentPrint); + if (error) { + internalRenderTask.capability.reject(error); + this._abortOperatorList({ + intentState, + reason: error instanceof Error ? error : new Error(error) + }); + } else { + internalRenderTask.capability.resolve(); + } + if (this._stats) { + this._stats.timeEnd("Rendering"); + this._stats.timeEnd("Overall"); + if (globalThis.Stats?.enabled) { + globalThis.Stats.add(this.pageNumber, this._stats); + } + } }; - const savedFontsize = this.#fontSize; - this.addCommands({ - cmd: () => { - setFontsize(fontSize); + const internalRenderTask = new InternalRenderTask({ + callback: complete, + params: { + canvasContext, + viewport, + transform, + background }, - undo: () => { - setFontsize(savedFontsize); - }, - mustExec: true, - type: _util.AnnotationEditorParamsType.FREETEXT_SIZE, - overwriteIfSameType: true, - keepUndo: true + objs: this.objs, + commonObjs: this.commonObjs, + annotationCanvasMap, + operatorList: intentState.operatorList, + pageIndex: this._pageIndex, + canvasFactory: this._transport.canvasFactory, + filterFactory: this._transport.filterFactory, + useRequestAnimationFrame: !intentPrint, + pdfBug: this._pdfBug, + pageColors }); - } - #updateColor(color) { - const savedColor = this.#color; - this.addCommands({ - cmd: () => { - this.#color = this.editorDiv.style.color = color; - }, - undo: () => { - this.#color = this.editorDiv.style.color = savedColor; - }, - mustExec: true, - type: _util.AnnotationEditorParamsType.FREETEXT_COLOR, - overwriteIfSameType: true, - keepUndo: true - }); - } - _translateEmpty(x, y) { - this._uiManager.translateSelectedEditors(x, y, true); - } - getInitialTranslation() { - const scale = this.parentScale; - return [-FreeTextEditor._internalPadding * scale, -(FreeTextEditor._internalPadding + this.#fontSize) * scale]; - } - rebuild() { - if (!this.parent) { - return; - } - super.rebuild(); - if (this.div === null) { - return; - } - if (!this.isAttachedToDOM) { - this.parent.add(this); - } - } - enableEditMode() { - if (this.isInEditMode()) { - return; - } - this.parent.setEditingState(false); - this.parent.updateToolbar(_util.AnnotationEditorType.FREETEXT); - super.enableEditMode(); - this.overlayDiv.classList.remove("enabled"); - this.editorDiv.contentEditable = true; - this._isDraggable = false; - this.div.removeAttribute("aria-activedescendant"); - this.editorDiv.addEventListener("keydown", this.#boundEditorDivKeydown); - this.editorDiv.addEventListener("focus", this.#boundEditorDivFocus); - this.editorDiv.addEventListener("blur", this.#boundEditorDivBlur); - this.editorDiv.addEventListener("input", this.#boundEditorDivInput); - } - disableEditMode() { - if (!this.isInEditMode()) { - return; - } - this.parent.setEditingState(true); - super.disableEditMode(); - this.overlayDiv.classList.add("enabled"); - this.editorDiv.contentEditable = false; - this.div.setAttribute("aria-activedescendant", this.#editorDivId); - this._isDraggable = true; - this.editorDiv.removeEventListener("keydown", this.#boundEditorDivKeydown); - this.editorDiv.removeEventListener("focus", this.#boundEditorDivFocus); - this.editorDiv.removeEventListener("blur", this.#boundEditorDivBlur); - this.editorDiv.removeEventListener("input", this.#boundEditorDivInput); - this.div.focus({ - preventScroll: true - }); - this.isEditing = false; - this.parent.div.classList.add("freeTextEditing"); - } - focusin(event) { - if (!this._focusEventsAllowed) { - return; - } - super.focusin(event); - if (event.target !== this.editorDiv) { - this.editorDiv.focus(); - } - } - onceAdded() { - if (this.width) { - this.#cheatInitialRect(); - return; - } - this.enableEditMode(); - this.editorDiv.focus(); - if (this._initialOptions?.isCentered) { - this.center(); - } - this._initialOptions = null; - } - isEmpty() { - return !this.editorDiv || this.editorDiv.innerText.trim() === ""; - } - remove() { - this.isEditing = false; - if (this.parent) { - this.parent.setEditingState(true); - this.parent.div.classList.add("freeTextEditing"); - } - super.remove(); - } - #extractText() { - const divs = this.editorDiv.getElementsByTagName("div"); - if (divs.length === 0) { - return this.editorDiv.innerText; - } - const buffer = []; - for (const div of divs) { - buffer.push(div.innerText.replace(/\r\n?|\n/, "")); - } - return buffer.join("\n"); - } - #setEditorDimensions() { - const [parentWidth, parentHeight] = this.parentDimensions; - let rect; - if (this.isAttachedToDOM) { - rect = this.div.getBoundingClientRect(); - } else { - const { - currentLayer, - div - } = this; - const savedDisplay = div.style.display; - div.style.display = "hidden"; - currentLayer.div.append(this.div); - rect = div.getBoundingClientRect(); - div.remove(); - div.style.display = savedDisplay; - } - if (this.rotation % 180 === this.parentRotation % 180) { - this.width = rect.width / parentWidth; - this.height = rect.height / parentHeight; - } else { - this.width = rect.height / parentWidth; - this.height = rect.width / parentHeight; - } - this.fixAndSetPosition(); - } - commit() { - if (!this.isInEditMode()) { - return; - } - super.commit(); - this.disableEditMode(); - const savedText = this.#content; - const newText = this.#content = this.#extractText().trimEnd(); - if (savedText === newText) { - return; - } - const setText = text => { - this.#content = text; - if (!text) { - this.remove(); + (intentState.renderTasks ||= new Set()).add(internalRenderTask); + const renderTask = internalRenderTask.task; + Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => { + if (this.destroyed) { + complete(); return; } - this.#setContent(); - this._uiManager.rebuild(this); - this.#setEditorDimensions(); - }; - this.addCommands({ - cmd: () => { - setText(newText); - }, - undo: () => { - setText(savedText); - }, - mustExec: false - }); - this.#setEditorDimensions(); - } - shouldGetKeyboardEvents() { - return this.isInEditMode(); - } - enterInEditMode() { - this.enableEditMode(); - this.editorDiv.focus(); - } - dblclick(event) { - this.enterInEditMode(); - } - keydown(event) { - if (event.target === this.div && event.key === "Enter") { - this.enterInEditMode(); - event.preventDefault(); - } - } - editorDivKeydown(event) { - FreeTextEditor._keyboardManager.exec(this, event); - } - editorDivFocus(event) { - this.isEditing = true; - } - editorDivBlur(event) { - this.isEditing = false; - } - editorDivInput(event) { - this.parent.div.classList.toggle("freeTextEditing", this.isEmpty()); - } - disableEditing() { - this.editorDiv.setAttribute("role", "comment"); - this.editorDiv.removeAttribute("aria-multiline"); - } - enableEditing() { - this.editorDiv.setAttribute("role", "textbox"); - this.editorDiv.setAttribute("aria-multiline", true); - } - render() { - if (this.div) { - return this.div; - } - let baseX, baseY; - if (this.width) { - baseX = this.x; - baseY = this.y; - } - super.render(); - this.editorDiv = document.createElement("div"); - this.editorDiv.className = "internal"; - this.editorDiv.setAttribute("id", this.#editorDivId); - this.enableEditing(); - _editor.AnnotationEditor._l10nPromise.get("editor_free_text2_aria_label").then(msg => this.editorDiv?.setAttribute("aria-label", msg)); - _editor.AnnotationEditor._l10nPromise.get("free_text2_default_content").then(msg => this.editorDiv?.setAttribute("default-content", msg)); - this.editorDiv.contentEditable = true; - const { - style - } = this.editorDiv; - style.fontSize = `calc(${this.#fontSize}px * var(--scale-factor))`; - style.color = this.#color; - this.div.append(this.editorDiv); - this.overlayDiv = document.createElement("div"); - this.overlayDiv.classList.add("overlay", "enabled"); - this.div.append(this.overlayDiv); - (0, _tools.bindEvents)(this, this.div, ["dblclick", "keydown"]); - if (this.width) { - const [parentWidth, parentHeight] = this.parentDimensions; - if (this.annotationElementId) { - const { - position - } = this.#initialData; - let [tx, ty] = this.getInitialTranslation(); - [tx, ty] = this.pageTranslationToScreen(tx, ty); - const [pageWidth, pageHeight] = this.pageDimensions; - const [pageX, pageY] = this.pageTranslation; - let posX, posY; - switch (this.rotation) { - case 0: - posX = baseX + (position[0] - pageX) / pageWidth; - posY = baseY + this.height - (position[1] - pageY) / pageHeight; - break; - case 90: - posX = baseX + (position[0] - pageX) / pageWidth; - posY = baseY - (position[1] - pageY) / pageHeight; - [tx, ty] = [ty, -tx]; - break; - case 180: - posX = baseX - this.width + (position[0] - pageX) / pageWidth; - posY = baseY - (position[1] - pageY) / pageHeight; - [tx, ty] = [-tx, -ty]; - break; - case 270: - posX = baseX + (position[0] - pageX - this.height * pageHeight) / pageWidth; - posY = baseY + (position[1] - pageY - this.width * pageWidth) / pageHeight; - [tx, ty] = [-ty, tx]; - break; - } - this.setAt(posX * parentWidth, posY * parentHeight, tx, ty); - } else { - this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight); + this._stats?.time("Rendering"); + if (!(optionalContentConfig.renderingIntent & renderingIntent)) { + throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` " + "and `PDFDocumentProxy.getOptionalContentConfig` methods."); } - this.#setContent(); - this._isDraggable = true; - this.editorDiv.contentEditable = false; - } else { - this._isDraggable = false; - this.editorDiv.contentEditable = true; - } - return this.div; + internalRenderTask.initializeGraphics({ + transparency, + optionalContentConfig + }); + internalRenderTask.operatorListChanged(); + }).catch(complete); + return renderTask; } - #setContent() { - this.editorDiv.replaceChildren(); - if (!this.#content) { - return; - } - for (const line of this.#content.split("\n")) { - const div = document.createElement("div"); - div.append(line ? document.createTextNode(line) : document.createElement("br")); - this.editorDiv.append(div); - } - } - get contentDiv() { - return this.editorDiv; - } - static deserialize(data, parent, uiManager) { - let initialData = null; - if (data instanceof _annotation_layer.FreeTextAnnotationElement) { - const { - data: { - defaultAppearanceData: { - fontSize, - fontColor - }, - rect, - rotation, - id - }, - textContent, - textPosition, - parent: { - page: { - pageNumber - } - } - } = data; - if (!textContent || textContent.length === 0) { - return null; - } - initialData = data = { - annotationType: _util.AnnotationEditorType.FREETEXT, - color: Array.from(fontColor), - fontSize, - value: textContent.join("\n"), - position: textPosition, - pageIndex: pageNumber - 1, - rect, - rotation, - id, - deleted: false - }; - } - const editor = super.deserialize(data, parent, uiManager); - editor.#fontSize = data.fontSize; - editor.#color = _util.Util.makeHexColor(...data.color); - editor.#content = data.value; - editor.annotationElementId = data.id || null; - editor.#initialData = initialData; - return editor; - } - serialize(isForCopying = false) { - if (this.isEmpty()) { - return null; - } - if (this.deleted) { - return { - pageIndex: this.pageIndex, - id: this.annotationElementId, - deleted: true - }; - } - const padding = FreeTextEditor._internalPadding * this.parentScale; - const rect = this.getRect(padding, padding); - const color = _editor.AnnotationEditor._colorManager.convert(this.isAttachedToDOM ? getComputedStyle(this.editorDiv).color : this.#color); - const serialized = { - annotationType: _util.AnnotationEditorType.FREETEXT, - color, - fontSize: this.#fontSize, - value: this.#content, - pageIndex: this.pageIndex, - rect, - rotation: this.rotation, - structTreeParentId: this._structTreeParentId - }; - if (isForCopying) { - return serialized; - } - if (this.annotationElementId && !this.#hasElementChanged(serialized)) { - return null; - } - serialized.id = this.annotationElementId; - return serialized; - } - #hasElementChanged(serialized) { - const { - value, - fontSize, - color, - rect, - pageIndex - } = this.#initialData; - return serialized.value !== value || serialized.fontSize !== fontSize || serialized.rect.some((x, i) => Math.abs(x - rect[i]) >= 1) || serialized.color.some((c, i) => c !== color[i]) || serialized.pageIndex !== pageIndex; - } - #cheatInitialRect(delayed = false) { - if (!this.annotationElementId) { - return; - } - this.#setEditorDimensions(); - if (!delayed && (this.width === 0 || this.height === 0)) { - setTimeout(() => this.#cheatInitialRect(true), 0); - return; - } - const padding = FreeTextEditor._internalPadding * this.parentScale; - this.#initialData.rect = this.getRect(padding, padding); - } -} -exports.FreeTextEditor = FreeTextEditor; - -/***/ }), -/* 29 */ -/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.StampAnnotationElement = exports.InkAnnotationElement = exports.FreeTextAnnotationElement = exports.AnnotationLayer = void 0; -var _util = __w_pdfjs_require__(1); -var _display_utils = __w_pdfjs_require__(6); -var _annotation_storage = __w_pdfjs_require__(3); -var _scripting_utils = __w_pdfjs_require__(30); -var _displayL10n_utils = __w_pdfjs_require__(31); -var _xfa_layer = __w_pdfjs_require__(32); -const DEFAULT_TAB_INDEX = 1000; -const DEFAULT_FONT_SIZE = 9; -const GetElementsByNameSet = new WeakSet(); -function getRectDims(rect) { - return { - width: rect[2] - rect[0], - height: rect[3] - rect[1] - }; -} -class AnnotationElementFactory { - static create(parameters) { - const subtype = parameters.data.annotationType; - switch (subtype) { - case _util.AnnotationType.LINK: - return new LinkAnnotationElement(parameters); - case _util.AnnotationType.TEXT: - return new TextAnnotationElement(parameters); - case _util.AnnotationType.WIDGET: - const fieldType = parameters.data.fieldType; - switch (fieldType) { - case "Tx": - return new TextWidgetAnnotationElement(parameters); - case "Btn": - if (parameters.data.radioButton) { - return new RadioButtonWidgetAnnotationElement(parameters); - } else if (parameters.data.checkBox) { - return new CheckboxWidgetAnnotationElement(parameters); - } - return new PushButtonWidgetAnnotationElement(parameters); - case "Ch": - return new ChoiceWidgetAnnotationElement(parameters); - case "Sig": - return new SignatureWidgetAnnotationElement(parameters); - } - return new WidgetAnnotationElement(parameters); - case _util.AnnotationType.POPUP: - return new PopupAnnotationElement(parameters); - case _util.AnnotationType.FREETEXT: - return new FreeTextAnnotationElement(parameters); - case _util.AnnotationType.LINE: - return new LineAnnotationElement(parameters); - case _util.AnnotationType.SQUARE: - return new SquareAnnotationElement(parameters); - case _util.AnnotationType.CIRCLE: - return new CircleAnnotationElement(parameters); - case _util.AnnotationType.POLYLINE: - return new PolylineAnnotationElement(parameters); - case _util.AnnotationType.CARET: - return new CaretAnnotationElement(parameters); - case _util.AnnotationType.INK: - return new InkAnnotationElement(parameters); - case _util.AnnotationType.POLYGON: - return new PolygonAnnotationElement(parameters); - case _util.AnnotationType.HIGHLIGHT: - return new HighlightAnnotationElement(parameters); - case _util.AnnotationType.UNDERLINE: - return new UnderlineAnnotationElement(parameters); - case _util.AnnotationType.SQUIGGLY: - return new SquigglyAnnotationElement(parameters); - case _util.AnnotationType.STRIKEOUT: - return new StrikeOutAnnotationElement(parameters); - case _util.AnnotationType.STAMP: - return new StampAnnotationElement(parameters); - case _util.AnnotationType.FILEATTACHMENT: - return new FileAttachmentAnnotationElement(parameters); - default: - return new AnnotationElement(parameters); - } - } -} -class AnnotationElement { - #hasBorder = false; - constructor(parameters, { - isRenderable = false, - ignoreBorder = false, - createQuadrilaterals = false + getOperatorList({ + intent = "display", + annotationMode = AnnotationMode.ENABLE, + printAnnotationStorage = null, + isEditing = false } = {}) { - this.isRenderable = isRenderable; - this.data = parameters.data; - this.layer = parameters.layer; - this.linkService = parameters.linkService; - this.downloadManager = parameters.downloadManager; - this.imageResourcesPath = parameters.imageResourcesPath; - this.renderForms = parameters.renderForms; - this.svgFactory = parameters.svgFactory; - this.annotationStorage = parameters.annotationStorage; - this.enableScripting = parameters.enableScripting; - this.hasJSActions = parameters.hasJSActions; - this._fieldObjects = parameters.fieldObjects; - this.parent = parameters.parent; - if (isRenderable) { - this.container = this._createContainer(ignoreBorder); - } - if (createQuadrilaterals) { - this._createQuadrilaterals(); - } - } - static _hasPopupData({ - titleObj, - contentsObj, - richText - }) { - return !!(titleObj?.str || contentsObj?.str || richText?.str); - } - get hasPopupData() { - return AnnotationElement._hasPopupData(this.data); - } - _createContainer(ignoreBorder) { - const { - data, - parent: { - page, - viewport - } - } = this; - const container = document.createElement("section"); - container.setAttribute("data-annotation-id", data.id); - if (!(this instanceof WidgetAnnotationElement)) { - container.tabIndex = DEFAULT_TAB_INDEX; - } - container.style.zIndex = this.parent.zIndex++; - if (this.data.popupRef) { - container.setAttribute("aria-haspopup", "dialog"); - } - if (data.noRotate) { - container.classList.add("norotate"); - } - const { - pageWidth, - pageHeight, - pageX, - pageY - } = viewport.rawDims; - if (!data.rect || this instanceof PopupAnnotationElement) { - const { - rotation - } = data; - if (!data.hasOwnCanvas && rotation !== 0) { - this.setRotation(rotation, container); - } - return container; - } - const { - width, - height - } = getRectDims(data.rect); - const rect = _util.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]]); - if (!ignoreBorder && data.borderStyle.width > 0) { - container.style.borderWidth = `${data.borderStyle.width}px`; - const horizontalRadius = data.borderStyle.horizontalCornerRadius; - const verticalRadius = data.borderStyle.verticalCornerRadius; - if (horizontalRadius > 0 || verticalRadius > 0) { - const radius = `calc(${horizontalRadius}px * var(--scale-factor)) / calc(${verticalRadius}px * var(--scale-factor))`; - container.style.borderRadius = radius; - } else if (this instanceof RadioButtonWidgetAnnotationElement) { - const radius = `calc(${width}px * var(--scale-factor)) / calc(${height}px * var(--scale-factor))`; - container.style.borderRadius = radius; - } - switch (data.borderStyle.style) { - case _util.AnnotationBorderStyleType.SOLID: - container.style.borderStyle = "solid"; - break; - case _util.AnnotationBorderStyleType.DASHED: - container.style.borderStyle = "dashed"; - break; - case _util.AnnotationBorderStyleType.BEVELED: - (0, _util.warn)("Unimplemented border style: beveled"); - break; - case _util.AnnotationBorderStyleType.INSET: - (0, _util.warn)("Unimplemented border style: inset"); - break; - case _util.AnnotationBorderStyleType.UNDERLINE: - container.style.borderBottomStyle = "solid"; - break; - default: - break; - } - const borderColor = data.borderColor || null; - if (borderColor) { - this.#hasBorder = true; - container.style.borderColor = _util.Util.makeHexColor(borderColor[0] | 0, borderColor[1] | 0, borderColor[2] | 0); - } else { - container.style.borderWidth = 0; + function operatorListChanged() { + if (intentState.operatorList.lastChunk) { + intentState.opListReadCapability.resolve(intentState.operatorList); + intentState.renderTasks.delete(opListTask); } } - container.style.left = `${100 * (rect[0] - pageX) / pageWidth}%`; - container.style.top = `${100 * (rect[1] - pageY) / pageHeight}%`; - const { - rotation - } = data; - if (data.hasOwnCanvas || rotation === 0) { - container.style.width = `${100 * width / pageWidth}%`; - container.style.height = `${100 * height / pageHeight}%`; - } else { - this.setRotation(rotation, container); + const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, isEditing, true); + let intentState = this._intentStates.get(intentArgs.cacheKey); + if (!intentState) { + intentState = Object.create(null); + this._intentStates.set(intentArgs.cacheKey, intentState); } - return container; - } - setRotation(angle, container = this.container) { - if (!this.data.rect) { - return; - } - const { - pageWidth, - pageHeight - } = this.parent.viewport.rawDims; - const { - width, - height - } = getRectDims(this.data.rect); - let elementWidth, elementHeight; - if (angle % 180 === 0) { - elementWidth = 100 * width / pageWidth; - elementHeight = 100 * height / pageHeight; - } else { - elementWidth = 100 * height / pageWidth; - elementHeight = 100 * width / pageHeight; - } - container.style.width = `${elementWidth}%`; - container.style.height = `${elementHeight}%`; - container.setAttribute("data-main-rotation", (360 - angle) % 360); - } - get _commonActions() { - const setColor = (jsName, styleName, event) => { - const color = event.detail[jsName]; - const colorType = color[0]; - const colorArray = color.slice(1); - event.target.style[styleName] = _scripting_utils.ColorConverters[`${colorType}_HTML`](colorArray); - this.annotationStorage.setValue(this.data.id, { - [styleName]: _scripting_utils.ColorConverters[`${colorType}_rgb`](colorArray) - }); - }; - return (0, _util.shadow)(this, "_commonActions", { - display: event => { - const { - display - } = event.detail; - const hidden = display % 2 === 1; - this.container.style.visibility = hidden ? "hidden" : "visible"; - this.annotationStorage.setValue(this.data.id, { - noView: hidden, - noPrint: display === 1 || display === 2 - }); - }, - print: event => { - this.annotationStorage.setValue(this.data.id, { - noPrint: !event.detail.print - }); - }, - hidden: event => { - const { - hidden - } = event.detail; - this.container.style.visibility = hidden ? "hidden" : "visible"; - this.annotationStorage.setValue(this.data.id, { - noPrint: hidden, - noView: hidden - }); - }, - focus: event => { - setTimeout(() => event.target.focus({ - preventScroll: false - }), 0); - }, - userName: event => { - event.target.title = event.detail.userName; - }, - readonly: event => { - event.target.disabled = event.detail.readonly; - }, - required: event => { - this._setRequired(event.target, event.detail.required); - }, - bgColor: event => { - setColor("bgColor", "backgroundColor", event); - }, - fillColor: event => { - setColor("fillColor", "backgroundColor", event); - }, - fgColor: event => { - setColor("fgColor", "color", event); - }, - textColor: event => { - setColor("textColor", "color", event); - }, - borderColor: event => { - setColor("borderColor", "borderColor", event); - }, - strokeColor: event => { - setColor("strokeColor", "borderColor", event); - }, - rotation: event => { - const angle = event.detail.rotation; - this.setRotation(angle); - this.annotationStorage.setValue(this.data.id, { - rotation: angle - }); - } - }); - } - _dispatchEventFromSandbox(actions, jsEvent) { - const commonActions = this._commonActions; - for (const name of Object.keys(jsEvent.detail)) { - const action = actions[name] || commonActions[name]; - action?.(jsEvent); - } - } - _setDefaultPropertiesFromJS(element) { - if (!this.enableScripting) { - return; - } - const storedData = this.annotationStorage.getRawValue(this.data.id); - if (!storedData) { - return; - } - const commonActions = this._commonActions; - for (const [actionName, detail] of Object.entries(storedData)) { - const action = commonActions[actionName]; - if (action) { - const eventProxy = { - detail: { - [actionName]: detail - }, - target: element - }; - action(eventProxy); - delete storedData[actionName]; - } - } - } - _createQuadrilaterals() { - if (!this.container) { - return; - } - const { - quadPoints - } = this.data; - if (!quadPoints) { - return; - } - const [rectBlX, rectBlY, rectTrX, rectTrY] = this.data.rect; - if (quadPoints.length === 1) { - const [, { - x: trX, - y: trY - }, { - x: blX, - y: blY - }] = quadPoints[0]; - if (rectTrX === trX && rectTrY === trY && rectBlX === blX && rectBlY === blY) { - return; - } - } - const { - style - } = this.container; - let svgBuffer; - if (this.#hasBorder) { - const { - borderColor, - borderWidth - } = style; - style.borderWidth = 0; - svgBuffer = ["url('data:image/svg+xml;utf8,", ``, ``]; - this.container.classList.add("hasBorder"); - } - const width = rectTrX - rectBlX; - const height = rectTrY - rectBlY; - const { - svgFactory - } = this; - const svg = svgFactory.createElement("svg"); - svg.classList.add("quadrilateralsContainer"); - svg.setAttribute("width", 0); - svg.setAttribute("height", 0); - const defs = svgFactory.createElement("defs"); - svg.append(defs); - const clipPath = svgFactory.createElement("clipPath"); - const id = `clippath_${this.data.id}`; - clipPath.setAttribute("id", id); - clipPath.setAttribute("clipPathUnits", "objectBoundingBox"); - defs.append(clipPath); - for (const [, { - x: trX, - y: trY - }, { - x: blX, - y: blY - }] of quadPoints) { - const rect = svgFactory.createElement("rect"); - const x = (blX - rectBlX) / width; - const y = (rectTrY - trY) / height; - const rectWidth = (trX - blX) / width; - const rectHeight = (trY - blY) / height; - rect.setAttribute("x", x); - rect.setAttribute("y", y); - rect.setAttribute("width", rectWidth); - rect.setAttribute("height", rectHeight); - clipPath.append(rect); - svgBuffer?.push(``); - } - if (this.#hasBorder) { - svgBuffer.push(`')`); - style.backgroundImage = svgBuffer.join(""); - } - this.container.append(svg); - this.container.style.clipPath = `url(#${id})`; - } - _createPopup() { - const { - container, - data - } = this; - container.setAttribute("aria-haspopup", "dialog"); - const popup = new PopupAnnotationElement({ - data: { - color: data.color, - titleObj: data.titleObj, - modificationDate: data.modificationDate, - contentsObj: data.contentsObj, - richText: data.richText, - parentRect: data.rect, - borderStyle: 0, - id: `popup_${data.id}`, - rotation: data.rotation - }, - parent: this.parent, - elements: [this] - }); - this.parent.div.append(popup.render()); - } - render() { - (0, _util.unreachable)("Abstract method `AnnotationElement.render` called"); - } - _getElementsByName(name, skipId = null) { - const fields = []; - if (this._fieldObjects) { - const fieldObj = this._fieldObjects[name]; - if (fieldObj) { - for (const { - page, - id, - exportValues - } of fieldObj) { - if (page === -1) { - continue; - } - if (id === skipId) { - continue; - } - const exportValue = typeof exportValues === "string" ? exportValues : null; - const domElement = document.querySelector(`[data-element-id="${id}"]`); - if (domElement && !GetElementsByNameSet.has(domElement)) { - (0, _util.warn)(`_getElementsByName - element not allowed: ${id}`); - continue; - } - fields.push({ - id, - exportValue, - domElement - }); - } - } - return fields; - } - for (const domElement of document.getElementsByName(name)) { - const { - exportValue - } = domElement; - const id = domElement.getAttribute("data-element-id"); - if (id === skipId) { - continue; - } - if (!GetElementsByNameSet.has(domElement)) { - continue; - } - fields.push({ - id, - exportValue, - domElement - }); - } - return fields; - } - show() { - if (this.container) { - this.container.hidden = false; - } - this.popup?.maybeShow(); - } - hide() { - if (this.container) { - this.container.hidden = true; - } - this.popup?.forceHide(); - } - getElementsToTriggerPopup() { - return this.container; - } - addHighlightArea() { - const triggers = this.getElementsToTriggerPopup(); - if (Array.isArray(triggers)) { - for (const element of triggers) { - element.classList.add("highlightArea"); - } - } else { - triggers.classList.add("highlightArea"); - } - } - _editOnDoubleClick() { - const { - annotationEditorType: mode, - data: { - id: editId - } - } = this; - this.container.addEventListener("dblclick", () => { - this.linkService.eventBus?.dispatch("switchannotationeditormode", { - source: this, - mode, - editId - }); - }); - } -} -class LinkAnnotationElement extends AnnotationElement { - constructor(parameters, options = null) { - super(parameters, { - isRenderable: true, - ignoreBorder: !!options?.ignoreBorder, - createQuadrilaterals: true - }); - this.isTooltipOnly = parameters.data.isTooltipOnly; - } - render() { - const { - data, - linkService - } = this; - const link = document.createElement("a"); - link.setAttribute("data-element-id", data.id); - let isBound = false; - if (data.url) { - linkService.addLinkAttributes(link, data.url, data.newWindow); - isBound = true; - } else if (data.action) { - this._bindNamedAction(link, data.action); - isBound = true; - } else if (data.attachment) { - this._bindAttachment(link, data.attachment); - isBound = true; - } else if (data.setOCGState) { - this.#bindSetOCGState(link, data.setOCGState); - isBound = true; - } else if (data.dest) { - this._bindLink(link, data.dest); - isBound = true; - } else { - if (data.actions && (data.actions.Action || data.actions["Mouse Up"] || data.actions["Mouse Down"]) && this.enableScripting && this.hasJSActions) { - this._bindJSAction(link, data); - isBound = true; - } - if (data.resetForm) { - this._bindResetFormAction(link, data.resetForm); - isBound = true; - } else if (this.isTooltipOnly && !isBound) { - this._bindLink(link, ""); - isBound = true; - } - } - this.container.classList.add("linkAnnotation"); - if (isBound) { - this.container.append(link); - } - return this.container; - } - #setInternalLink() { - this.container.setAttribute("data-internal-link", ""); - } - _bindLink(link, destination) { - link.href = this.linkService.getDestinationHash(destination); - link.onclick = () => { - if (destination) { - this.linkService.goToDestination(destination); - } - return false; - }; - if (destination || destination === "") { - this.#setInternalLink(); - } - } - _bindNamedAction(link, action) { - link.href = this.linkService.getAnchorUrl(""); - link.onclick = () => { - this.linkService.executeNamedAction(action); - return false; - }; - this.#setInternalLink(); - } - _bindAttachment(link, attachment) { - link.href = this.linkService.getAnchorUrl(""); - link.onclick = () => { - this.downloadManager?.openOrDownloadData(this.container, attachment.content, attachment.filename); - return false; - }; - this.#setInternalLink(); - } - #bindSetOCGState(link, action) { - link.href = this.linkService.getAnchorUrl(""); - link.onclick = () => { - this.linkService.executeSetOCGState(action); - return false; - }; - this.#setInternalLink(); - } - _bindJSAction(link, data) { - link.href = this.linkService.getAnchorUrl(""); - const map = new Map([["Action", "onclick"], ["Mouse Up", "onmouseup"], ["Mouse Down", "onmousedown"]]); - for (const name of Object.keys(data.actions)) { - const jsName = map.get(name); - if (!jsName) { - continue; - } - link[jsName] = () => { - this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { - source: this, - detail: { - id: data.id, - name - } - }); - return false; + let opListTask; + if (!intentState.opListReadCapability) { + opListTask = Object.create(null); + opListTask.operatorListChanged = operatorListChanged; + intentState.opListReadCapability = Promise.withResolvers(); + (intentState.renderTasks ||= new Set()).add(opListTask); + intentState.operatorList = { + fnArray: [], + argsArray: [], + lastChunk: false, + separateAnnots: null }; + this._stats?.time("Page Request"); + this._pumpOperatorList(intentArgs); } - if (!link.onclick) { - link.onclick = () => false; - } - this.#setInternalLink(); + return intentState.opListReadCapability.promise; } - _bindResetFormAction(link, resetForm) { - const otherClickAction = link.onclick; - if (!otherClickAction) { - link.href = this.linkService.getAnchorUrl(""); - } - this.#setInternalLink(); - if (!this._fieldObjects) { - (0, _util.warn)(`_bindResetFormAction - "resetForm" action not supported, ` + "ensure that the `fieldObjects` parameter is provided."); - if (!otherClickAction) { - link.onclick = () => false; + streamTextContent({ + includeMarkedContent = false, + disableNormalization = false + } = {}) { + const TEXT_CONTENT_CHUNK_SIZE = 100; + return this._transport.messageHandler.sendWithStream("GetTextContent", { + pageIndex: this._pageIndex, + includeMarkedContent: includeMarkedContent === true, + disableNormalization: disableNormalization === true + }, { + highWaterMark: TEXT_CONTENT_CHUNK_SIZE, + size(textContent) { + return textContent.items.length; } + }); + } + getTextContent(params = {}) { + if (this._transport._htmlForXfa) { + return this.getXfa().then(xfa => XfaText.textContent(xfa)); + } + const readableStream = this.streamTextContent(params); + return new Promise(function (resolve, reject) { + function pump() { + reader.read().then(function ({ + value, + done + }) { + if (done) { + resolve(textContent); + return; + } + textContent.lang ??= value.lang; + Object.assign(textContent.styles, value.styles); + textContent.items.push(...value.items); + pump(); + }, reject); + } + const reader = readableStream.getReader(); + const textContent = { + items: [], + styles: Object.create(null), + lang: null + }; + pump(); + }); + } + getStructTree() { + return this._transport.getStructTree(this._pageIndex); + } + _destroy() { + this.destroyed = true; + const waitOn = []; + for (const intentState of this._intentStates.values()) { + this._abortOperatorList({ + intentState, + reason: new Error("Page was destroyed."), + force: true + }); + if (intentState.opListReadCapability) { + continue; + } + for (const internalRenderTask of intentState.renderTasks) { + waitOn.push(internalRenderTask.completed); + internalRenderTask.cancel(); + } + } + this.objs.clear(); + this.#pendingCleanup = false; + this.#abortDelayedCleanup(); + return Promise.all(waitOn); + } + cleanup(resetStats = false) { + this.#pendingCleanup = true; + const success = this.#tryCleanup(false); + if (resetStats && success) { + this._stats &&= new StatTimer(); + } + return success; + } + #tryCleanup(delayed = false) { + this.#abortDelayedCleanup(); + if (!this.#pendingCleanup || this.destroyed) { + return false; + } + if (delayed) { + this.#delayedCleanupTimeout = setTimeout(() => { + this.#delayedCleanupTimeout = null; + this.#tryCleanup(false); + }, DELAYED_CLEANUP_TIMEOUT); + return false; + } + for (const { + renderTasks, + operatorList + } of this._intentStates.values()) { + if (renderTasks.size > 0 || !operatorList.lastChunk) { + return false; + } + } + this._intentStates.clear(); + this.objs.clear(); + this.#pendingCleanup = false; + return true; + } + #abortDelayedCleanup() { + if (this.#delayedCleanupTimeout) { + clearTimeout(this.#delayedCleanupTimeout); + this.#delayedCleanupTimeout = null; + } + } + _startRenderPage(transparency, cacheKey) { + const intentState = this._intentStates.get(cacheKey); + if (!intentState) { return; } - link.onclick = () => { - otherClickAction?.(); - const { - fields: resetFormFields, - refs: resetFormRefs, - include - } = resetForm; - const allFields = []; - if (resetFormFields.length !== 0 || resetFormRefs.length !== 0) { - const fieldIds = new Set(resetFormRefs); - for (const fieldName of resetFormFields) { - const fields = this._fieldObjects[fieldName] || []; - for (const { - id - } of fields) { - fieldIds.add(id); - } - } - for (const fields of Object.values(this._fieldObjects)) { - for (const field of fields) { - if (fieldIds.has(field.id) === include) { - allFields.push(field); - } - } - } - } else { - for (const fields of Object.values(this._fieldObjects)) { - allFields.push(...fields); - } - } - const storage = this.annotationStorage; - const allIds = []; - for (const field of allFields) { - const { - id - } = field; - allIds.push(id); - switch (field.type) { - case "text": - { - const value = field.defaultValue || ""; - storage.setValue(id, { - value - }); - break; - } - case "checkbox": - case "radiobutton": - { - const value = field.defaultValue === field.exportValues; - storage.setValue(id, { - value - }); - break; - } - case "combobox": - case "listbox": - { - const value = field.defaultValue || ""; - storage.setValue(id, { - value - }); - break; - } - default: - continue; - } - const domElement = document.querySelector(`[data-element-id="${id}"]`); - if (!domElement) { - continue; - } else if (!GetElementsByNameSet.has(domElement)) { - (0, _util.warn)(`_bindResetFormAction - element not allowed: ${id}`); - continue; - } - domElement.dispatchEvent(new Event("resetform")); - } - if (this.enableScripting) { - this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { - source: this, - detail: { - id: "app", - ids: allIds, - name: "ResetForm" - } - }); - } - return false; - }; + this._stats?.timeEnd("Page Request"); + intentState.displayReadyCapability?.resolve(transparency); } -} -class TextAnnotationElement extends AnnotationElement { - constructor(parameters) { - super(parameters, { - isRenderable: true - }); - } - render() { - this.container.classList.add("textAnnotation"); - const image = document.createElement("img"); - image.src = this.imageResourcesPath + "annotation-" + this.data.name.toLowerCase() + ".svg"; - image.alt = "[{{type}} Annotation]"; - image.dataset.l10nId = "text_annotation_type"; - image.dataset.l10nArgs = JSON.stringify({ - type: this.data.name - }); - if (!this.data.popupRef && this.hasPopupData) { - this._createPopup(); + _renderPageChunk(operatorListChunk, intentState) { + for (let i = 0, ii = operatorListChunk.length; i < ii; i++) { + intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]); + intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]); } - this.container.append(image); - return this.container; - } -} -class WidgetAnnotationElement extends AnnotationElement { - render() { - if (this.data.alternativeText) { - this.container.title = this.data.alternativeText; + intentState.operatorList.lastChunk = operatorListChunk.lastChunk; + intentState.operatorList.separateAnnots = operatorListChunk.separateAnnots; + for (const internalRenderTask of intentState.renderTasks) { + internalRenderTask.operatorListChanged(); } - return this.container; - } - showElementAndHideCanvas(element) { - if (this.data.hasOwnCanvas) { - if (element.previousSibling?.nodeName === "CANVAS") { - element.previousSibling.hidden = true; - } - element.hidden = false; + if (operatorListChunk.lastChunk) { + this.#tryCleanup(true); } } - _getKeyModifier(event) { + _pumpOperatorList({ + renderingIntent, + cacheKey, + annotationStorageSerializable, + modifiedIds + }) { const { - isWin, - isMac - } = _util.FeatureTest.platform; - return isWin && event.ctrlKey || isMac && event.metaKey; - } - _setEventListener(element, elementData, baseName, eventName, valueGetter) { - if (baseName.includes("mouse")) { - element.addEventListener(baseName, event => { - this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { - source: this, - detail: { - id: this.data.id, - name: eventName, - value: valueGetter(event), - shift: event.shiftKey, - modifier: this._getKeyModifier(event) - } - }); - }); - } else { - element.addEventListener(baseName, event => { - if (baseName === "blur") { - if (!elementData.focused || !event.relatedTarget) { - return; - } - elementData.focused = false; - } else if (baseName === "focus") { - if (elementData.focused) { - return; - } - elementData.focused = true; - } - if (!valueGetter) { + map, + transfer + } = annotationStorageSerializable; + const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", { + pageIndex: this._pageIndex, + intent: renderingIntent, + cacheKey, + annotationStorage: map, + modifiedIds + }, transfer); + const reader = readableStream.getReader(); + const intentState = this._intentStates.get(cacheKey); + intentState.streamReader = reader; + const pump = () => { + reader.read().then(({ + value, + done + }) => { + if (done) { + intentState.streamReader = null; return; } - this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { - source: this, - detail: { - id: this.data.id, - name: eventName, - value: valueGetter(event) - } - }); - }); - } - } - _setEventListeners(element, elementData, names, getter) { - for (const [baseName, eventName] of names) { - if (eventName === "Action" || this.data.actions?.[eventName]) { - if (eventName === "Focus" || eventName === "Blur") { - elementData ||= { - focused: false - }; + if (this._transport.destroyed) { + return; } - this._setEventListener(element, elementData, baseName, eventName, getter); - if (eventName === "Focus" && !this.data.actions?.Blur) { - this._setEventListener(element, elementData, "blur", "Blur", null); - } else if (eventName === "Blur" && !this.data.actions?.Focus) { - this._setEventListener(element, elementData, "focus", "Focus", null); + this._renderPageChunk(value, intentState); + pump(); + }, reason => { + intentState.streamReader = null; + if (this._transport.destroyed) { + return; } - } - } - } - _setBackgroundColor(element) { - const color = this.data.backgroundColor || null; - element.style.backgroundColor = color === null ? "transparent" : _util.Util.makeHexColor(color[0], color[1], color[2]); - } - _setTextStyle(element) { - const TEXT_ALIGNMENT = ["left", "center", "right"]; - const { - fontColor - } = this.data.defaultAppearanceData; - const fontSize = this.data.defaultAppearanceData.fontSize || DEFAULT_FONT_SIZE; - const style = element.style; - let computedFontSize; - const BORDER_SIZE = 2; - const roundToOneDecimal = x => Math.round(10 * x) / 10; - if (this.data.multiLine) { - const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE); - const numberOfLines = Math.round(height / (_util.LINE_FACTOR * fontSize)) || 1; - const lineHeight = height / numberOfLines; - computedFontSize = Math.min(fontSize, roundToOneDecimal(lineHeight / _util.LINE_FACTOR)); - } else { - const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE); - computedFontSize = Math.min(fontSize, roundToOneDecimal(height / _util.LINE_FACTOR)); - } - style.fontSize = `calc(${computedFontSize}px * var(--scale-factor))`; - style.color = _util.Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]); - if (this.data.textAlignment !== null) { - style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment]; - } - } - _setRequired(element, isRequired) { - if (isRequired) { - element.setAttribute("required", true); - } else { - element.removeAttribute("required"); - } - element.setAttribute("aria-required", isRequired); - } -} -class TextWidgetAnnotationElement extends WidgetAnnotationElement { - constructor(parameters) { - const isRenderable = parameters.renderForms || !parameters.data.hasAppearance && !!parameters.data.fieldValue; - super(parameters, { - isRenderable - }); - } - setPropertyOnSiblings(base, key, value, keyInStorage) { - const storage = this.annotationStorage; - for (const element of this._getElementsByName(base.name, base.id)) { - if (element.domElement) { - element.domElement[key] = value; - } - storage.setValue(element.id, { - [keyInStorage]: value - }); - } - } - render() { - const storage = this.annotationStorage; - const id = this.data.id; - this.container.classList.add("textWidgetAnnotation"); - let element = null; - if (this.renderForms) { - const storedData = storage.getValue(id, { - value: this.data.fieldValue - }); - let textContent = storedData.value || ""; - const maxLen = storage.getValue(id, { - charLimit: this.data.maxLen - }).charLimit; - if (maxLen && textContent.length > maxLen) { - textContent = textContent.slice(0, maxLen); - } - let fieldFormattedValues = storedData.formattedValue || this.data.textContent?.join("\n") || null; - if (fieldFormattedValues && this.data.comb) { - fieldFormattedValues = fieldFormattedValues.replaceAll(/\s+/g, ""); - } - const elementData = { - userValue: textContent, - formattedValue: fieldFormattedValues, - lastCommittedValue: null, - commitKey: 1, - focused: false - }; - if (this.data.multiLine) { - element = document.createElement("textarea"); - element.textContent = fieldFormattedValues ?? textContent; - if (this.data.doNotScroll) { - element.style.overflowY = "hidden"; + if (intentState.operatorList) { + intentState.operatorList.lastChunk = true; + for (const internalRenderTask of intentState.renderTasks) { + internalRenderTask.operatorListChanged(); + } + this.#tryCleanup(true); } - } else { - element = document.createElement("input"); - element.type = "text"; - element.setAttribute("value", fieldFormattedValues ?? textContent); - if (this.data.doNotScroll) { - element.style.overflowX = "hidden"; + if (intentState.displayReadyCapability) { + intentState.displayReadyCapability.reject(reason); + } else if (intentState.opListReadCapability) { + intentState.opListReadCapability.reject(reason); + } else { + throw reason; } - } - if (this.data.hasOwnCanvas) { - element.hidden = true; - } - GetElementsByNameSet.add(element); - element.setAttribute("data-element-id", id); - element.disabled = this.data.readOnly; - element.name = this.data.fieldName; - element.tabIndex = DEFAULT_TAB_INDEX; - this._setRequired(element, this.data.required); - if (maxLen) { - element.maxLength = maxLen; - } - element.addEventListener("input", event => { - storage.setValue(id, { - value: event.target.value - }); - this.setPropertyOnSiblings(element, "value", event.target.value, "value"); - elementData.formattedValue = null; - }); - element.addEventListener("resetform", event => { - const defaultValue = this.data.defaultFieldValue ?? ""; - element.value = elementData.userValue = defaultValue; - elementData.formattedValue = null; - }); - let blurListener = event => { - const { - formattedValue - } = elementData; - if (formattedValue !== null && formattedValue !== undefined) { - event.target.value = formattedValue; - } - event.target.scrollLeft = 0; - }; - if (this.enableScripting && this.hasJSActions) { - element.addEventListener("focus", event => { - if (elementData.focused) { - return; - } - const { - target - } = event; - if (elementData.userValue) { - target.value = elementData.userValue; - } - elementData.lastCommittedValue = target.value; - elementData.commitKey = 1; - elementData.focused = true; - }); - element.addEventListener("updatefromsandbox", jsEvent => { - this.showElementAndHideCanvas(jsEvent.target); - const actions = { - value(event) { - elementData.userValue = event.detail.value ?? ""; - storage.setValue(id, { - value: elementData.userValue.toString() - }); - event.target.value = elementData.userValue; - }, - formattedValue(event) { - const { - formattedValue - } = event.detail; - elementData.formattedValue = formattedValue; - if (formattedValue !== null && formattedValue !== undefined && event.target !== document.activeElement) { - event.target.value = formattedValue; - } - storage.setValue(id, { - formattedValue - }); - }, - selRange(event) { - event.target.setSelectionRange(...event.detail.selRange); - }, - charLimit: event => { - const { - charLimit - } = event.detail; - const { - target - } = event; - if (charLimit === 0) { - target.removeAttribute("maxLength"); - return; - } - target.setAttribute("maxLength", charLimit); - let value = elementData.userValue; - if (!value || value.length <= charLimit) { - return; - } - value = value.slice(0, charLimit); - target.value = elementData.userValue = value; - storage.setValue(id, { - value - }); - this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { - source: this, - detail: { - id, - name: "Keystroke", - value, - willCommit: true, - commitKey: 1, - selStart: target.selectionStart, - selEnd: target.selectionEnd - } - }); - } - }; - this._dispatchEventFromSandbox(actions, jsEvent); - }); - element.addEventListener("keydown", event => { - elementData.commitKey = 1; - let commitKey = -1; - if (event.key === "Escape") { - commitKey = 0; - } else if (event.key === "Enter" && !this.data.multiLine) { - commitKey = 2; - } else if (event.key === "Tab") { - elementData.commitKey = 3; - } - if (commitKey === -1) { - return; - } - const { - value - } = event.target; - if (elementData.lastCommittedValue === value) { - return; - } - elementData.lastCommittedValue = value; - elementData.userValue = value; - this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { - source: this, - detail: { - id, - name: "Keystroke", - value, - willCommit: true, - commitKey, - selStart: event.target.selectionStart, - selEnd: event.target.selectionEnd - } - }); - }); - const _blurListener = blurListener; - blurListener = null; - element.addEventListener("blur", event => { - if (!elementData.focused || !event.relatedTarget) { - return; - } - elementData.focused = false; - const { - value - } = event.target; - elementData.userValue = value; - if (elementData.lastCommittedValue !== value) { - this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { - source: this, - detail: { - id, - name: "Keystroke", - value, - willCommit: true, - commitKey: elementData.commitKey, - selStart: event.target.selectionStart, - selEnd: event.target.selectionEnd - } - }); - } - _blurListener(event); - }); - if (this.data.actions?.Keystroke) { - element.addEventListener("beforeinput", event => { - elementData.lastCommittedValue = null; - const { - data, - target - } = event; - const { - value, - selectionStart, - selectionEnd - } = target; - let selStart = selectionStart, - selEnd = selectionEnd; - switch (event.inputType) { - case "deleteWordBackward": - { - const match = value.substring(0, selectionStart).match(/\w*[^\w]*$/); - if (match) { - selStart -= match[0].length; - } - break; - } - case "deleteWordForward": - { - const match = value.substring(selectionStart).match(/^[^\w]*\w*/); - if (match) { - selEnd += match[0].length; - } - break; - } - case "deleteContentBackward": - if (selectionStart === selectionEnd) { - selStart -= 1; - } - break; - case "deleteContentForward": - if (selectionStart === selectionEnd) { - selEnd += 1; - } - break; - } - event.preventDefault(); - this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { - source: this, - detail: { - id, - name: "Keystroke", - value, - change: data || "", - willCommit: false, - selStart, - selEnd - } - }); - }); - } - this._setEventListeners(element, elementData, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.value); - } - if (blurListener) { - element.addEventListener("blur", blurListener); - } - if (this.data.comb) { - const fieldWidth = this.data.rect[2] - this.data.rect[0]; - const combWidth = fieldWidth / maxLen; - element.classList.add("comb"); - element.style.letterSpacing = `calc(${combWidth}px * var(--scale-factor) - 1ch)`; - } - } else { - element = document.createElement("div"); - element.textContent = this.data.fieldValue; - element.style.verticalAlign = "middle"; - element.style.display = "table-cell"; - } - this._setTextStyle(element); - this._setBackgroundColor(element); - this._setDefaultPropertiesFromJS(element); - this.container.append(element); - return this.container; - } -} -class SignatureWidgetAnnotationElement extends WidgetAnnotationElement { - constructor(parameters) { - super(parameters, { - isRenderable: !!parameters.data.hasOwnCanvas - }); - } -} -class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement { - constructor(parameters) { - super(parameters, { - isRenderable: parameters.renderForms - }); - } - render() { - const storage = this.annotationStorage; - const data = this.data; - const id = data.id; - let value = storage.getValue(id, { - value: data.exportValue === data.fieldValue - }).value; - if (typeof value === "string") { - value = value !== "Off"; - storage.setValue(id, { - value - }); - } - this.container.classList.add("buttonWidgetAnnotation", "checkBox"); - const element = document.createElement("input"); - GetElementsByNameSet.add(element); - element.setAttribute("data-element-id", id); - element.disabled = data.readOnly; - this._setRequired(element, this.data.required); - element.type = "checkbox"; - element.name = data.fieldName; - if (value) { - element.setAttribute("checked", true); - } - element.setAttribute("exportValue", data.exportValue); - element.tabIndex = DEFAULT_TAB_INDEX; - element.addEventListener("change", event => { - const { - name, - checked - } = event.target; - for (const checkbox of this._getElementsByName(name, id)) { - const curChecked = checked && checkbox.exportValue === data.exportValue; - if (checkbox.domElement) { - checkbox.domElement.checked = curChecked; - } - storage.setValue(checkbox.id, { - value: curChecked - }); - } - storage.setValue(id, { - value: checked - }); - }); - element.addEventListener("resetform", event => { - const defaultValue = data.defaultFieldValue || "Off"; - event.target.checked = defaultValue === data.exportValue; - }); - if (this.enableScripting && this.hasJSActions) { - element.addEventListener("updatefromsandbox", jsEvent => { - const actions = { - value(event) { - event.target.checked = event.detail.value !== "Off"; - storage.setValue(id, { - value: event.target.checked - }); - } - }; - this._dispatchEventFromSandbox(actions, jsEvent); - }); - 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); - } - this._setBackgroundColor(element); - this._setDefaultPropertiesFromJS(element); - this.container.append(element); - return this.container; - } -} -class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement { - constructor(parameters) { - super(parameters, { - isRenderable: parameters.renderForms - }); - } - render() { - this.container.classList.add("buttonWidgetAnnotation", "radioButton"); - const storage = this.annotationStorage; - const data = this.data; - const id = data.id; - let value = storage.getValue(id, { - value: data.fieldValue === data.buttonValue - }).value; - if (typeof value === "string") { - value = value !== data.buttonValue; - storage.setValue(id, { - value - }); - } - const element = document.createElement("input"); - GetElementsByNameSet.add(element); - element.setAttribute("data-element-id", id); - element.disabled = data.readOnly; - this._setRequired(element, this.data.required); - element.type = "radio"; - element.name = data.fieldName; - if (value) { - element.setAttribute("checked", true); - } - element.tabIndex = DEFAULT_TAB_INDEX; - element.addEventListener("change", event => { - const { - name, - checked - } = event.target; - for (const radio of this._getElementsByName(name, id)) { - storage.setValue(radio.id, { - value: false - }); - } - storage.setValue(id, { - value: checked - }); - }); - element.addEventListener("resetform", event => { - const defaultValue = data.defaultFieldValue; - event.target.checked = defaultValue !== null && defaultValue !== undefined && defaultValue === data.buttonValue; - }); - if (this.enableScripting && this.hasJSActions) { - const pdfButtonValue = data.buttonValue; - element.addEventListener("updatefromsandbox", jsEvent => { - const actions = { - value: event => { - const checked = pdfButtonValue === event.detail.value; - for (const radio of this._getElementsByName(event.target.name)) { - const curChecked = checked && radio.id === id; - if (radio.domElement) { - radio.domElement.checked = curChecked; - } - storage.setValue(radio.id, { - value: curChecked - }); - } - } - }; - this._dispatchEventFromSandbox(actions, jsEvent); - }); - 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); - } - this._setBackgroundColor(element); - this._setDefaultPropertiesFromJS(element); - this.container.append(element); - return this.container; - } -} -class PushButtonWidgetAnnotationElement extends LinkAnnotationElement { - constructor(parameters) { - super(parameters, { - ignoreBorder: parameters.data.hasAppearance - }); - } - render() { - const container = super.render(); - container.classList.add("buttonWidgetAnnotation", "pushButton"); - if (this.data.alternativeText) { - container.title = this.data.alternativeText; - } - const linkElement = container.lastChild; - if (this.enableScripting && this.hasJSActions && linkElement) { - this._setDefaultPropertiesFromJS(linkElement); - linkElement.addEventListener("updatefromsandbox", jsEvent => { - this._dispatchEventFromSandbox({}, jsEvent); - }); - } - return container; - } -} -class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement { - constructor(parameters) { - super(parameters, { - isRenderable: parameters.renderForms - }); - } - render() { - this.container.classList.add("choiceWidgetAnnotation"); - const storage = this.annotationStorage; - const id = this.data.id; - const storedData = storage.getValue(id, { - value: this.data.fieldValue - }); - const selectElement = document.createElement("select"); - GetElementsByNameSet.add(selectElement); - selectElement.setAttribute("data-element-id", id); - selectElement.disabled = this.data.readOnly; - this._setRequired(selectElement, this.data.required); - selectElement.name = this.data.fieldName; - selectElement.tabIndex = DEFAULT_TAB_INDEX; - let addAnEmptyEntry = this.data.combo && this.data.options.length > 0; - if (!this.data.combo) { - selectElement.size = this.data.options.length; - if (this.data.multiSelect) { - selectElement.multiple = true; - } - } - selectElement.addEventListener("resetform", event => { - const defaultValue = this.data.defaultFieldValue; - for (const option of selectElement.options) { - option.selected = option.value === defaultValue; - } - }); - for (const option of this.data.options) { - const optionElement = document.createElement("option"); - optionElement.textContent = option.displayValue; - optionElement.value = option.exportValue; - if (storedData.value.includes(option.exportValue)) { - optionElement.setAttribute("selected", true); - addAnEmptyEntry = false; - } - selectElement.append(optionElement); - } - let removeEmptyEntry = null; - if (addAnEmptyEntry) { - const noneOptionElement = document.createElement("option"); - noneOptionElement.value = " "; - noneOptionElement.setAttribute("hidden", true); - noneOptionElement.setAttribute("selected", true); - selectElement.prepend(noneOptionElement); - removeEmptyEntry = () => { - noneOptionElement.remove(); - selectElement.removeEventListener("input", removeEmptyEntry); - removeEmptyEntry = null; - }; - selectElement.addEventListener("input", removeEmptyEntry); - } - const getValue = isExport => { - const name = isExport ? "value" : "textContent"; - const { - options, - multiple - } = selectElement; - if (!multiple) { - return options.selectedIndex === -1 ? null : options[options.selectedIndex][name]; - } - return Array.prototype.filter.call(options, option => option.selected).map(option => option[name]); - }; - let selectedValues = getValue(false); - const getItems = event => { - const options = event.target.options; - return Array.prototype.map.call(options, option => { - return { - displayValue: option.textContent, - exportValue: option.value - }; }); }; - if (this.enableScripting && this.hasJSActions) { - selectElement.addEventListener("updatefromsandbox", jsEvent => { - const actions = { - value(event) { - removeEmptyEntry?.(); - const value = event.detail.value; - const values = new Set(Array.isArray(value) ? value : [value]); - for (const option of selectElement.options) { - option.selected = values.has(option.value); - } - storage.setValue(id, { - value: getValue(true) - }); - selectedValues = getValue(false); - }, - multipleSelection(event) { - selectElement.multiple = true; - }, - remove(event) { - const options = selectElement.options; - const index = event.detail.remove; - options[index].selected = false; - selectElement.remove(index); - if (options.length > 0) { - const i = Array.prototype.findIndex.call(options, option => option.selected); - if (i === -1) { - options[0].selected = true; - } - } - storage.setValue(id, { - value: getValue(true), - items: getItems(event) - }); - selectedValues = getValue(false); - }, - clear(event) { - while (selectElement.length !== 0) { - selectElement.remove(0); - } - storage.setValue(id, { - value: null, - items: [] - }); - selectedValues = getValue(false); - }, - insert(event) { - const { - index, - displayValue, - exportValue - } = event.detail.insert; - const selectChild = selectElement.children[index]; - const optionElement = document.createElement("option"); - optionElement.textContent = displayValue; - optionElement.value = exportValue; - if (selectChild) { - selectChild.before(optionElement); - } else { - selectElement.append(optionElement); - } - storage.setValue(id, { - value: getValue(true), - items: getItems(event) - }); - selectedValues = getValue(false); - }, - items(event) { - const { - items - } = event.detail; - while (selectElement.length !== 0) { - selectElement.remove(0); - } - for (const item of items) { - const { - displayValue, - exportValue - } = item; - const optionElement = document.createElement("option"); - optionElement.textContent = displayValue; - optionElement.value = exportValue; - selectElement.append(optionElement); - } - if (selectElement.options.length > 0) { - selectElement.options[0].selected = true; - } - storage.setValue(id, { - value: getValue(true), - items: getItems(event) - }); - selectedValues = getValue(false); - }, - indices(event) { - const indices = new Set(event.detail.indices); - for (const option of event.target.options) { - option.selected = indices.has(option.index); - } - storage.setValue(id, { - value: getValue(true) - }); - selectedValues = getValue(false); - }, - editable(event) { - event.target.disabled = !event.detail.editable; - } - }; - this._dispatchEventFromSandbox(actions, jsEvent); - }); - selectElement.addEventListener("input", event => { - const exportValue = getValue(true); - storage.setValue(id, { - value: exportValue - }); - event.preventDefault(); - this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { - source: this, - detail: { - id, - name: "Keystroke", - value: selectedValues, - changeEx: exportValue, - willCommit: false, - commitKey: 1, - keyDown: false - } - }); - }); - 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); - } else { - selectElement.addEventListener("input", function (event) { - storage.setValue(id, { - value: getValue(true) - }); - }); - } - if (this.data.combo) { - this._setTextStyle(selectElement); - } else {} - this._setBackgroundColor(selectElement); - this._setDefaultPropertiesFromJS(selectElement); - this.container.append(selectElement); - return this.container; + pump(); } -} -class PopupAnnotationElement extends AnnotationElement { - constructor(parameters) { - const { - data, - elements - } = parameters; - super(parameters, { - isRenderable: AnnotationElement._hasPopupData(data) - }); - this.elements = elements; - } - render() { - this.container.classList.add("popupAnnotation"); - const popup = new PopupElement({ - container: this.container, - color: this.data.color, - titleObj: this.data.titleObj, - modificationDate: this.data.modificationDate, - contentsObj: this.data.contentsObj, - richText: this.data.richText, - rect: this.data.rect, - parentRect: this.data.parentRect || null, - parent: this.parent, - elements: this.elements, - open: this.data.open - }); - const elementIds = []; - for (const element of this.elements) { - element.popup = popup; - elementIds.push(element.data.id); - element.addHighlightArea(); - } - this.container.setAttribute("aria-controls", elementIds.map(id => `${_util.AnnotationPrefix}${id}`).join(",")); - return this.container; - } -} -class PopupElement { - #dateTimePromise = null; - #boundKeyDown = this.#keyDown.bind(this); - #boundHide = this.#hide.bind(this); - #boundShow = this.#show.bind(this); - #boundToggle = this.#toggle.bind(this); - #color = null; - #container = null; - #contentsObj = null; - #elements = null; - #parent = null; - #parentRect = null; - #pinned = false; - #popup = null; - #rect = null; - #richText = null; - #titleObj = null; - #wasVisible = false; - constructor({ - container, - color, - elements, - titleObj, - modificationDate, - contentsObj, - richText, - parent, - rect, - parentRect, - open + _abortOperatorList({ + intentState, + reason, + force = false }) { - this.#container = container; - this.#titleObj = titleObj; - this.#contentsObj = contentsObj; - this.#richText = richText; - this.#parent = parent; - this.#color = color; - this.#rect = rect; - this.#parentRect = parentRect; - this.#elements = elements; - const dateObject = _display_utils.PDFDateString.toDateObject(modificationDate); - if (dateObject) { - this.#dateTimePromise = parent.l10n.get("annotation_date_string", { - date: dateObject.toLocaleDateString(), - time: dateObject.toLocaleTimeString() - }); - } - this.trigger = elements.flatMap(e => e.getElementsToTriggerPopup()); - for (const element of this.trigger) { - element.addEventListener("click", this.#boundToggle); - element.addEventListener("mouseenter", this.#boundShow); - element.addEventListener("mouseleave", this.#boundHide); - element.classList.add("popupTriggerArea"); - } - for (const element of elements) { - element.container?.addEventListener("keydown", this.#boundKeyDown); - } - this.#container.hidden = true; - if (open) { - this.#toggle(); - } - } - render() { - if (this.#popup) { + if (!intentState.streamReader) { return; } - const { - page: { - view - }, - viewport: { - rawDims: { - pageWidth, - pageHeight, - pageX, - pageY + if (intentState.streamReaderCancelTimeout) { + clearTimeout(intentState.streamReaderCancelTimeout); + intentState.streamReaderCancelTimeout = null; + } + if (!force) { + if (intentState.renderTasks.size > 0) { + return; + } + if (reason instanceof RenderingCancelledException) { + let delay = RENDERING_CANCELLED_TIMEOUT; + if (reason.extraDelay > 0 && reason.extraDelay < 1000) { + delay += reason.extraDelay; } - } - } = this.#parent; - const popup = this.#popup = document.createElement("div"); - popup.className = "popup"; - if (this.#color) { - const baseColor = popup.style.outlineColor = _util.Util.makeHexColor(...this.#color); - if (CSS.supports("background-color", "color-mix(in srgb, red 30%, white)")) { - popup.style.backgroundColor = `color-mix(in srgb, ${baseColor} 30%, white)`; - } else { - const BACKGROUND_ENLIGHT = 0.7; - popup.style.backgroundColor = _util.Util.makeHexColor(...this.#color.map(c => Math.floor(BACKGROUND_ENLIGHT * (255 - c) + c))); + intentState.streamReaderCancelTimeout = setTimeout(() => { + intentState.streamReaderCancelTimeout = null; + this._abortOperatorList({ + intentState, + reason, + force: true + }); + }, delay); + return; } } - const header = document.createElement("span"); - header.className = "header"; - const title = document.createElement("h1"); - header.append(title); - ({ - dir: title.dir, - str: title.textContent - } = this.#titleObj); - popup.append(header); - if (this.#dateTimePromise) { - const modificationDate = document.createElement("span"); - modificationDate.classList.add("popupDate"); - this.#dateTimePromise.then(localized => { - modificationDate.textContent = localized; - }); - header.append(modificationDate); + intentState.streamReader.cancel(new AbortException(reason.message)).catch(() => {}); + intentState.streamReader = null; + if (this._transport.destroyed) { + return; } - const contentsObj = this.#contentsObj; - const richText = this.#richText; - if (richText?.str && (!contentsObj?.str || contentsObj.str === richText.str)) { - _xfa_layer.XfaLayer.render({ - xfaHtml: richText.html, - intent: "richText", - div: popup - }); - popup.lastChild.classList.add("richText", "popupContent"); - } else { - const contents = this._formatContents(contentsObj); - popup.append(contents); - } - let useParentRect = !!this.#parentRect; - let rect = useParentRect ? this.#parentRect : this.#rect; - for (const element of this.#elements) { - if (!rect || _util.Util.intersect(element.data.rect, rect) !== null) { - rect = element.data.rect; - useParentRect = true; + for (const [curCacheKey, curIntentState] of this._intentStates) { + if (curIntentState === intentState) { + this._intentStates.delete(curCacheKey); break; } } - const normalizedRect = _util.Util.normalizeRect([rect[0], view[3] - rect[1] + view[1], rect[2], view[3] - rect[3] + view[1]]); - const HORIZONTAL_SPACE_AFTER_ANNOTATION = 5; - const parentWidth = useParentRect ? rect[2] - rect[0] + HORIZONTAL_SPACE_AFTER_ANNOTATION : 0; - const popupLeft = normalizedRect[0] + parentWidth; - const popupTop = normalizedRect[1]; - const { - style - } = this.#container; - style.left = `${100 * (popupLeft - pageX) / pageWidth}%`; - style.top = `${100 * (popupTop - pageY) / pageHeight}%`; - this.#container.append(popup); + this.cleanup(); } - _formatContents({ - str, - dir - }) { - const p = document.createElement("p"); - p.classList.add("popupContent"); - p.dir = dir; - const lines = str.split(/(?:\r\n?|\n)/); - for (let i = 0, ii = lines.length; i < ii; ++i) { - const line = lines[i]; - p.append(document.createTextNode(line)); - if (i < ii - 1) { - p.append(document.createElement("br")); - } - } - return p; - } - #keyDown(event) { - if (event.altKey || event.shiftKey || event.ctrlKey || event.metaKey) { - return; - } - if (event.key === "Enter" || event.key === "Escape" && this.#pinned) { - this.#toggle(); - } - } - #toggle() { - this.#pinned = !this.#pinned; - if (this.#pinned) { - this.#show(); - this.#container.addEventListener("click", this.#boundToggle); - this.#container.addEventListener("keydown", this.#boundKeyDown); - } else { - this.#hide(); - this.#container.removeEventListener("click", this.#boundToggle); - this.#container.removeEventListener("keydown", this.#boundKeyDown); - } - } - #show() { - if (!this.#popup) { - this.render(); - } - if (!this.isVisible) { - this.#container.hidden = false; - this.#container.style.zIndex = parseInt(this.#container.style.zIndex) + 1000; - } else if (this.#pinned) { - this.#container.classList.add("focused"); - } - } - #hide() { - this.#container.classList.remove("focused"); - if (this.#pinned || !this.isVisible) { - return; - } - this.#container.hidden = true; - this.#container.style.zIndex = parseInt(this.#container.style.zIndex) - 1000; - } - forceHide() { - this.#wasVisible = this.isVisible; - if (!this.#wasVisible) { - return; - } - this.#container.hidden = true; - } - maybeShow() { - if (!this.#wasVisible) { - return; - } - this.#wasVisible = false; - this.#container.hidden = false; - } - get isVisible() { - return this.#container.hidden === false; + get stats() { + return this._stats; } } -class FreeTextAnnotationElement extends AnnotationElement { - constructor(parameters) { - super(parameters, { - isRenderable: true, - ignoreBorder: true - }); - this.textContent = parameters.data.textContent; - this.textPosition = parameters.data.textPosition; - this.annotationEditorType = _util.AnnotationEditorType.FREETEXT; - } - render() { - this.container.classList.add("freeTextAnnotation"); - if (this.textContent) { - const content = document.createElement("div"); - content.classList.add("annotationTextContent"); - content.setAttribute("role", "comment"); - for (const line of this.textContent) { - const lineSpan = document.createElement("span"); - lineSpan.textContent = line; - content.append(lineSpan); - } - this.container.append(content); - } - if (!this.data.popupRef && this.hasPopupData) { - this._createPopup(); - } - this._editOnDoubleClick(); - return this.container; - } -} -exports.FreeTextAnnotationElement = FreeTextAnnotationElement; -class LineAnnotationElement extends AnnotationElement { - #line = null; - constructor(parameters) { - super(parameters, { - isRenderable: true, - ignoreBorder: true - }); - } - render() { - this.container.classList.add("lineAnnotation"); - const data = this.data; - const { - width, - height - } = getRectDims(data.rect); - const svg = this.svgFactory.create(width, height, true); - const line = this.#line = this.svgFactory.createElement("svg:line"); - line.setAttribute("x1", data.rect[2] - data.lineCoordinates[0]); - line.setAttribute("y1", data.rect[3] - data.lineCoordinates[1]); - line.setAttribute("x2", data.rect[2] - data.lineCoordinates[2]); - line.setAttribute("y2", data.rect[3] - data.lineCoordinates[3]); - line.setAttribute("stroke-width", data.borderStyle.width || 1); - line.setAttribute("stroke", "transparent"); - line.setAttribute("fill", "transparent"); - svg.append(line); - this.container.append(svg); - if (!data.popupRef && this.hasPopupData) { - this._createPopup(); - } - return this.container; - } - getElementsToTriggerPopup() { - return this.#line; - } - addHighlightArea() { - this.container.classList.add("highlightArea"); - } -} -class SquareAnnotationElement extends AnnotationElement { - #square = null; - constructor(parameters) { - super(parameters, { - isRenderable: true, - ignoreBorder: true - }); - } - render() { - this.container.classList.add("squareAnnotation"); - const data = this.data; - const { - width, - height - } = getRectDims(data.rect); - const svg = this.svgFactory.create(width, height, true); - const borderWidth = data.borderStyle.width; - const square = this.#square = this.svgFactory.createElement("svg:rect"); - square.setAttribute("x", borderWidth / 2); - square.setAttribute("y", borderWidth / 2); - square.setAttribute("width", width - borderWidth); - square.setAttribute("height", height - borderWidth); - square.setAttribute("stroke-width", borderWidth || 1); - square.setAttribute("stroke", "transparent"); - square.setAttribute("fill", "transparent"); - svg.append(square); - this.container.append(svg); - if (!data.popupRef && this.hasPopupData) { - this._createPopup(); - } - return this.container; - } - getElementsToTriggerPopup() { - return this.#square; - } - addHighlightArea() { - this.container.classList.add("highlightArea"); - } -} -class CircleAnnotationElement extends AnnotationElement { - #circle = null; - constructor(parameters) { - super(parameters, { - isRenderable: true, - ignoreBorder: true - }); - } - render() { - this.container.classList.add("circleAnnotation"); - const data = this.data; - const { - width, - height - } = getRectDims(data.rect); - const svg = this.svgFactory.create(width, height, true); - const borderWidth = data.borderStyle.width; - const circle = this.#circle = this.svgFactory.createElement("svg:ellipse"); - circle.setAttribute("cx", width / 2); - circle.setAttribute("cy", height / 2); - circle.setAttribute("rx", width / 2 - borderWidth / 2); - circle.setAttribute("ry", height / 2 - borderWidth / 2); - circle.setAttribute("stroke-width", borderWidth || 1); - circle.setAttribute("stroke", "transparent"); - circle.setAttribute("fill", "transparent"); - svg.append(circle); - this.container.append(svg); - if (!data.popupRef && this.hasPopupData) { - this._createPopup(); - } - return this.container; - } - getElementsToTriggerPopup() { - return this.#circle; - } - addHighlightArea() { - this.container.classList.add("highlightArea"); - } -} -class PolylineAnnotationElement extends AnnotationElement { - #polyline = null; - constructor(parameters) { - super(parameters, { - isRenderable: true, - ignoreBorder: true - }); - this.containerClassName = "polylineAnnotation"; - this.svgElementName = "svg:polyline"; - } - render() { - this.container.classList.add(this.containerClassName); - const data = this.data; - const { - width, - height - } = getRectDims(data.rect); - const svg = this.svgFactory.create(width, height, true); - let points = []; - for (const coordinate of data.vertices) { - const x = coordinate.x - data.rect[0]; - const y = data.rect[3] - coordinate.y; - points.push(x + "," + y); - } - points = points.join(" "); - const polyline = this.#polyline = this.svgFactory.createElement(this.svgElementName); - polyline.setAttribute("points", points); - polyline.setAttribute("stroke-width", data.borderStyle.width || 1); - polyline.setAttribute("stroke", "transparent"); - polyline.setAttribute("fill", "transparent"); - svg.append(polyline); - this.container.append(svg); - if (!data.popupRef && this.hasPopupData) { - this._createPopup(); - } - return this.container; - } - getElementsToTriggerPopup() { - return this.#polyline; - } - addHighlightArea() { - this.container.classList.add("highlightArea"); - } -} -class PolygonAnnotationElement extends PolylineAnnotationElement { - constructor(parameters) { - super(parameters); - this.containerClassName = "polygonAnnotation"; - this.svgElementName = "svg:polygon"; - } -} -class CaretAnnotationElement extends AnnotationElement { - constructor(parameters) { - super(parameters, { - isRenderable: true, - ignoreBorder: true - }); - } - render() { - this.container.classList.add("caretAnnotation"); - if (!this.data.popupRef && this.hasPopupData) { - this._createPopup(); - } - return this.container; - } -} -class InkAnnotationElement extends AnnotationElement { - #polylines = []; - constructor(parameters) { - super(parameters, { - isRenderable: true, - ignoreBorder: true - }); - this.containerClassName = "inkAnnotation"; - this.svgElementName = "svg:polyline"; - this.annotationEditorType = _util.AnnotationEditorType.INK; - } - render() { - this.container.classList.add(this.containerClassName); - const data = this.data; - const { - width, - height - } = getRectDims(data.rect); - const svg = this.svgFactory.create(width, height, true); - for (const inkList of data.inkLists) { - let points = []; - for (const coordinate of inkList) { - const x = coordinate.x - data.rect[0]; - const y = data.rect[3] - coordinate.y; - points.push(`${x},${y}`); - } - points = points.join(" "); - const polyline = this.svgFactory.createElement(this.svgElementName); - this.#polylines.push(polyline); - polyline.setAttribute("points", points); - polyline.setAttribute("stroke-width", data.borderStyle.width || 1); - polyline.setAttribute("stroke", "transparent"); - polyline.setAttribute("fill", "transparent"); - if (!data.popupRef && this.hasPopupData) { - this._createPopup(); - } - svg.append(polyline); - } - this.container.append(svg); - return this.container; - } - getElementsToTriggerPopup() { - return this.#polylines; - } - addHighlightArea() { - this.container.classList.add("highlightArea"); - } -} -exports.InkAnnotationElement = InkAnnotationElement; -class HighlightAnnotationElement extends AnnotationElement { - constructor(parameters) { - super(parameters, { - isRenderable: true, - ignoreBorder: true, - createQuadrilaterals: true - }); - } - render() { - if (!this.data.popupRef && this.hasPopupData) { - this._createPopup(); - } - this.container.classList.add("highlightAnnotation"); - return this.container; - } -} -class UnderlineAnnotationElement extends AnnotationElement { - constructor(parameters) { - super(parameters, { - isRenderable: true, - ignoreBorder: true, - createQuadrilaterals: true - }); - } - render() { - if (!this.data.popupRef && this.hasPopupData) { - this._createPopup(); - } - this.container.classList.add("underlineAnnotation"); - return this.container; - } -} -class SquigglyAnnotationElement extends AnnotationElement { - constructor(parameters) { - super(parameters, { - isRenderable: true, - ignoreBorder: true, - createQuadrilaterals: true - }); - } - render() { - if (!this.data.popupRef && this.hasPopupData) { - this._createPopup(); - } - this.container.classList.add("squigglyAnnotation"); - return this.container; - } -} -class StrikeOutAnnotationElement extends AnnotationElement { - constructor(parameters) { - super(parameters, { - isRenderable: true, - ignoreBorder: true, - createQuadrilaterals: true - }); - } - render() { - if (!this.data.popupRef && this.hasPopupData) { - this._createPopup(); - } - this.container.classList.add("strikeoutAnnotation"); - return this.container; - } -} -class StampAnnotationElement extends AnnotationElement { - constructor(parameters) { - super(parameters, { - isRenderable: true, - ignoreBorder: true - }); - } - render() { - this.container.classList.add("stampAnnotation"); - if (!this.data.popupRef && this.hasPopupData) { - this._createPopup(); - } - return this.container; - } -} -exports.StampAnnotationElement = StampAnnotationElement; -class FileAttachmentAnnotationElement extends AnnotationElement { - #trigger = null; - constructor(parameters) { - super(parameters, { - isRenderable: true - }); - const { - filename, - content - } = this.data.file; - this.filename = (0, _display_utils.getFilenameFromUrl)(filename, true); - this.content = content; - this.linkService.eventBus?.dispatch("fileattachmentannotation", { - source: this, - filename, - content - }); - } - render() { - this.container.classList.add("fileAttachmentAnnotation"); - const { - container, - data - } = this; - let trigger; - if (data.hasAppearance || data.fillAlpha === 0) { - trigger = document.createElement("div"); - } else { - trigger = document.createElement("img"); - trigger.src = `${this.imageResourcesPath}annotation-${/paperclip/i.test(data.name) ? "paperclip" : "pushpin"}.svg`; - if (data.fillAlpha && data.fillAlpha < 1) { - trigger.style = `filter: opacity(${Math.round(data.fillAlpha * 100)}%);`; - } - } - trigger.addEventListener("dblclick", this.#download.bind(this)); - this.#trigger = trigger; - const { - isMac - } = _util.FeatureTest.platform; - container.addEventListener("keydown", evt => { - if (evt.key === "Enter" && (isMac ? evt.metaKey : evt.ctrlKey)) { - this.#download(); - } - }); - if (!data.popupRef && this.hasPopupData) { - this._createPopup(); - } else { - trigger.classList.add("popupTriggerArea"); - } - container.append(trigger); - return container; - } - getElementsToTriggerPopup() { - return this.#trigger; - } - addHighlightArea() { - this.container.classList.add("highlightArea"); - } - #download() { - this.downloadManager?.openOrDownloadData(this.container, this.content, this.filename); - } -} -class AnnotationLayer { - #accessibilityManager = null; - #annotationCanvasMap = null; - #editableAnnotations = new Map(); - constructor({ - div, - accessibilityManager, - annotationCanvasMap, - l10n, - page, - viewport - }) { - this.div = div; - this.#accessibilityManager = accessibilityManager; - this.#annotationCanvasMap = annotationCanvasMap; - this.l10n = l10n; - this.page = page; - this.viewport = viewport; - this.zIndex = 0; - this.l10n ||= _displayL10n_utils.NullL10n; - } - #appendElement(element, id) { - const contentElement = element.firstChild || element; - contentElement.id = `${_util.AnnotationPrefix}${id}`; - this.div.append(element); - this.#accessibilityManager?.moveElementInDOM(this.div, element, contentElement, false); - } - async render(params) { - const { - annotations - } = params; - const layer = this.div; - (0, _display_utils.setLayerDimensions)(layer, this.viewport); - const popupToElements = new Map(); - const elementParams = { - data: null, - layer, - linkService: params.linkService, - downloadManager: params.downloadManager, - imageResourcesPath: params.imageResourcesPath || "", - renderForms: params.renderForms !== false, - svgFactory: new _display_utils.DOMSVGFactory(), - annotationStorage: params.annotationStorage || new _annotation_storage.AnnotationStorage(), - enableScripting: params.enableScripting === true, - hasJSActions: params.hasJSActions, - fieldObjects: params.fieldObjects, - parent: this, - elements: null +class LoopbackPort { + #listeners = new Set(); + #deferred = Promise.resolve(); + postMessage(obj, transfer) { + const event = { + data: structuredClone(obj, transfer ? { + transfer + } : null) }; - for (const data of annotations) { - if (data.noHTML) { - continue; + this.#deferred.then(() => { + for (const listener of this.#listeners) { + listener.call(this, event); } - const isPopupAnnotation = data.annotationType === _util.AnnotationType.POPUP; - if (!isPopupAnnotation) { - const { - width, - height - } = getRectDims(data.rect); - if (width <= 0 || height <= 0) { - continue; - } - } else { - const elements = popupToElements.get(data.id); - if (!elements) { - continue; - } - elementParams.elements = elements; - } - elementParams.data = data; - const element = AnnotationElementFactory.create(elementParams); - if (!element.isRenderable) { - continue; - } - if (!isPopupAnnotation && data.popupRef) { - const elements = popupToElements.get(data.popupRef); - if (!elements) { - popupToElements.set(data.popupRef, [element]); - } else { - elements.push(element); - } - } - if (element.annotationEditorType > 0) { - this.#editableAnnotations.set(element.data.id, element); - } - const rendered = element.render(); - if (data.hidden) { - rendered.style.visibility = "hidden"; - } - this.#appendElement(rendered, data.id); - } - this.#setAnnotationCanvasMap(); - await this.l10n.translate(layer); - } - update({ - viewport - }) { - const layer = this.div; - this.viewport = viewport; - (0, _display_utils.setLayerDimensions)(layer, { - rotation: viewport.rotation }); - this.#setAnnotationCanvasMap(); - layer.hidden = false; } - #setAnnotationCanvasMap() { - if (!this.#annotationCanvasMap) { - return; - } - const layer = this.div; - for (const [id, canvas] of this.#annotationCanvasMap) { - const element = layer.querySelector(`[data-annotation-id="${id}"]`); - if (!element) { - continue; - } - const { - firstChild - } = element; - if (!firstChild) { - element.append(canvas); - } else if (firstChild.nodeName === "CANVAS") { - firstChild.replaceWith(canvas); - } else { - firstChild.before(canvas); - } - } - this.#annotationCanvasMap.clear(); + addEventListener(name, listener) { + this.#listeners.add(listener); } - getEditableAnnotations() { - return Array.from(this.#editableAnnotations.values()); + removeEventListener(name, listener) { + this.#listeners.delete(listener); } - getEditableAnnotation(id) { - return this.#editableAnnotations.get(id); + terminate() { + this.#listeners.clear(); } } -exports.AnnotationLayer = AnnotationLayer; +class PDFWorker { + static #fakeWorkerId = 0; + static #isWorkerDisabled = false; + static #workerPorts; + static { + if (isNodeJS) { + this.#isWorkerDisabled = true; + GlobalWorkerOptions.workerSrc ||= "./pdf.worker.mjs"; + } + this._isSameOrigin = (baseUrl, otherUrl) => { + let base; + try { + base = new URL(baseUrl); + if (!base.origin || base.origin === "null") { + return false; + } + } catch { + return false; + } + const other = new URL(otherUrl, base); + return base.origin === other.origin; + }; + this._createCDNWrapper = url => { + const wrapper = `await import("${url}");`; + return URL.createObjectURL(new Blob([wrapper], { + type: "text/javascript" + })); + }; + } + constructor({ + name = null, + port = null, + verbosity = getVerbosityLevel() + } = {}) { + this.name = name; + this.destroyed = false; + this.verbosity = verbosity; + this._readyCapability = Promise.withResolvers(); + this._port = null; + this._webWorker = null; + this._messageHandler = null; + if (port) { + if (PDFWorker.#workerPorts?.has(port)) { + throw new Error("Cannot use more than one PDFWorker per port."); + } + (PDFWorker.#workerPorts ||= new WeakMap()).set(port, this); + this._initializeFromPort(port); + return; + } + this._initialize(); + } + get promise() { + if (isNodeJS) { + return Promise.all([NodePackages.promise, this._readyCapability.promise]); + } + return this._readyCapability.promise; + } + #resolve() { + this._readyCapability.resolve(); + this._messageHandler.send("configure", { + verbosity: this.verbosity + }); + } + get port() { + return this._port; + } + get messageHandler() { + return this._messageHandler; + } + _initializeFromPort(port) { + this._port = port; + this._messageHandler = new MessageHandler("main", "worker", port); + this._messageHandler.on("ready", function () {}); + this.#resolve(); + } + _initialize() { + if (PDFWorker.#isWorkerDisabled || PDFWorker.#mainThreadWorkerMessageHandler) { + this._setupFakeWorker(); + return; + } + let { + workerSrc + } = PDFWorker; + try { + if (!PDFWorker._isSameOrigin(window.location.href, workerSrc)) { + workerSrc = PDFWorker._createCDNWrapper(new URL(workerSrc, window.location).href); + } + const worker = new Worker(workerSrc, { + type: "module" + }); + const messageHandler = new MessageHandler("main", "worker", worker); + const terminateEarly = () => { + ac.abort(); + messageHandler.destroy(); + worker.terminate(); + if (this.destroyed) { + this._readyCapability.reject(new Error("Worker was destroyed")); + } else { + this._setupFakeWorker(); + } + }; + const ac = new AbortController(); + worker.addEventListener("error", () => { + if (!this._webWorker) { + terminateEarly(); + } + }, { + signal: ac.signal + }); + messageHandler.on("test", data => { + ac.abort(); + if (this.destroyed || !data) { + terminateEarly(); + return; + } + this._messageHandler = messageHandler; + this._port = worker; + this._webWorker = worker; + this.#resolve(); + }); + messageHandler.on("ready", data => { + ac.abort(); + if (this.destroyed) { + terminateEarly(); + return; + } + try { + sendTest(); + } catch { + this._setupFakeWorker(); + } + }); + const sendTest = () => { + const testObj = new Uint8Array(); + messageHandler.send("test", testObj, [testObj.buffer]); + }; + sendTest(); + return; + } catch { + info("The worker has been disabled."); + } + this._setupFakeWorker(); + } + _setupFakeWorker() { + if (!PDFWorker.#isWorkerDisabled) { + warn("Setting up fake worker."); + PDFWorker.#isWorkerDisabled = true; + } + PDFWorker._setupFakeWorkerGlobal.then(WorkerMessageHandler => { + if (this.destroyed) { + this._readyCapability.reject(new Error("Worker was destroyed")); + return; + } + const port = new LoopbackPort(); + this._port = port; + const id = `fake${PDFWorker.#fakeWorkerId++}`; + const workerHandler = new MessageHandler(id + "_worker", id, port); + WorkerMessageHandler.setup(workerHandler, port); + this._messageHandler = new MessageHandler(id, id + "_worker", port); + this.#resolve(); + }).catch(reason => { + this._readyCapability.reject(new Error(`Setting up fake worker failed: "${reason.message}".`)); + }); + } + destroy() { + this.destroyed = true; + if (this._webWorker) { + this._webWorker.terminate(); + this._webWorker = null; + } + PDFWorker.#workerPorts?.delete(this._port); + this._port = null; + if (this._messageHandler) { + this._messageHandler.destroy(); + this._messageHandler = null; + } + } + static fromPort(params) { + if (!params?.port) { + throw new Error("PDFWorker.fromPort - invalid method signature."); + } + const cachedPort = this.#workerPorts?.get(params.port); + if (cachedPort) { + if (cachedPort._pendingDestroy) { + throw new Error("PDFWorker.fromPort - the worker is being destroyed.\n" + "Please remember to await `PDFDocumentLoadingTask.destroy()`-calls."); + } + return cachedPort; + } + return new PDFWorker(params); + } + static get workerSrc() { + if (GlobalWorkerOptions.workerSrc) { + return GlobalWorkerOptions.workerSrc; + } + throw new Error('No "GlobalWorkerOptions.workerSrc" specified.'); + } + static get #mainThreadWorkerMessageHandler() { + try { + return globalThis.pdfjsWorker?.WorkerMessageHandler || null; + } catch { + return null; + } + } + static get _setupFakeWorkerGlobal() { + const loader = async () => { + if (this.#mainThreadWorkerMessageHandler) { + return this.#mainThreadWorkerMessageHandler; + } + const worker = await import( /*webpackIgnore: true*/this.workerSrc); + return worker.WorkerMessageHandler; + }; + return shadow(this, "_setupFakeWorkerGlobal", loader()); + } +} +class WorkerTransport { + #methodPromises = new Map(); + #pageCache = new Map(); + #pagePromises = new Map(); + #pageRefCache = new Map(); + #passwordCapability = null; + constructor(messageHandler, loadingTask, networkStream, params, factory) { + this.messageHandler = messageHandler; + this.loadingTask = loadingTask; + this.commonObjs = new PDFObjects(); + this.fontLoader = new FontLoader({ + ownerDocument: params.ownerDocument, + styleElement: params.styleElement + }); + this.loadingParams = params.loadingParams; + this._params = params; + this.canvasFactory = factory.canvasFactory; + this.filterFactory = factory.filterFactory; + this.cMapReaderFactory = factory.cMapReaderFactory; + this.standardFontDataFactory = factory.standardFontDataFactory; + this.destroyed = false; + this.destroyCapability = null; + this._networkStream = networkStream; + this._fullReader = null; + this._lastProgress = null; + this.downloadInfoCapability = Promise.withResolvers(); + this.setupMessageHandler(); + } + #cacheSimpleMethod(name, data = null) { + const cachedPromise = this.#methodPromises.get(name); + if (cachedPromise) { + return cachedPromise; + } + const promise = this.messageHandler.sendWithPromise(name, data); + this.#methodPromises.set(name, promise); + return promise; + } + get annotationStorage() { + return shadow(this, "annotationStorage", new AnnotationStorage()); + } + getRenderingIntent(intent, annotationMode = AnnotationMode.ENABLE, printAnnotationStorage = null, isEditing = false, isOpList = false) { + let renderingIntent = RenderingIntentFlag.DISPLAY; + let annotationStorageSerializable = SerializableEmpty; + switch (intent) { + case "any": + renderingIntent = RenderingIntentFlag.ANY; + break; + case "display": + break; + case "print": + renderingIntent = RenderingIntentFlag.PRINT; + break; + default: + warn(`getRenderingIntent - invalid intent: ${intent}`); + } + const annotationStorage = renderingIntent & RenderingIntentFlag.PRINT && printAnnotationStorage instanceof PrintAnnotationStorage ? printAnnotationStorage : this.annotationStorage; + switch (annotationMode) { + case AnnotationMode.DISABLE: + renderingIntent += RenderingIntentFlag.ANNOTATIONS_DISABLE; + break; + case AnnotationMode.ENABLE: + break; + case AnnotationMode.ENABLE_FORMS: + renderingIntent += RenderingIntentFlag.ANNOTATIONS_FORMS; + break; + case AnnotationMode.ENABLE_STORAGE: + renderingIntent += RenderingIntentFlag.ANNOTATIONS_STORAGE; + annotationStorageSerializable = annotationStorage.serializable; + break; + default: + warn(`getRenderingIntent - invalid annotationMode: ${annotationMode}`); + } + if (isEditing) { + renderingIntent += RenderingIntentFlag.IS_EDITING; + } + if (isOpList) { + renderingIntent += RenderingIntentFlag.OPLIST; + } + const { + ids: modifiedIds, + hash: modifiedIdsHash + } = annotationStorage.modifiedIds; + const cacheKeyBuf = [renderingIntent, annotationStorageSerializable.hash, modifiedIdsHash]; + return { + renderingIntent, + cacheKey: cacheKeyBuf.join("_"), + annotationStorageSerializable, + modifiedIds + }; + } + destroy() { + if (this.destroyCapability) { + return this.destroyCapability.promise; + } + this.destroyed = true; + this.destroyCapability = Promise.withResolvers(); + this.#passwordCapability?.reject(new Error("Worker was destroyed during onPassword callback")); + const waitOn = []; + for (const page of this.#pageCache.values()) { + waitOn.push(page._destroy()); + } + this.#pageCache.clear(); + this.#pagePromises.clear(); + this.#pageRefCache.clear(); + if (this.hasOwnProperty("annotationStorage")) { + this.annotationStorage.resetModified(); + } + const terminated = this.messageHandler.sendWithPromise("Terminate", null); + waitOn.push(terminated); + Promise.all(waitOn).then(() => { + this.commonObjs.clear(); + this.fontLoader.clear(); + this.#methodPromises.clear(); + this.filterFactory.destroy(); + TextLayer.cleanup(); + this._networkStream?.cancelAllRequests(new AbortException("Worker was terminated.")); + if (this.messageHandler) { + this.messageHandler.destroy(); + this.messageHandler = null; + } + this.destroyCapability.resolve(); + }, this.destroyCapability.reject); + return this.destroyCapability.promise; + } + setupMessageHandler() { + const { + messageHandler, + loadingTask + } = this; + messageHandler.on("GetReader", (data, sink) => { + assert(this._networkStream, "GetReader - no `IPDFStream` instance available."); + this._fullReader = this._networkStream.getFullReader(); + this._fullReader.onProgress = evt => { + this._lastProgress = { + loaded: evt.loaded, + total: evt.total + }; + }; + sink.onPull = () => { + this._fullReader.read().then(function ({ + value, + done + }) { + if (done) { + sink.close(); + return; + } + assert(value instanceof ArrayBuffer, "GetReader - expected an ArrayBuffer."); + sink.enqueue(new Uint8Array(value), 1, [value]); + }).catch(reason => { + sink.error(reason); + }); + }; + sink.onCancel = reason => { + this._fullReader.cancel(reason); + sink.ready.catch(readyReason => { + if (this.destroyed) { + return; + } + throw readyReason; + }); + }; + }); + messageHandler.on("ReaderHeadersReady", data => { + const headersCapability = Promise.withResolvers(); + const fullReader = this._fullReader; + fullReader.headersReady.then(() => { + if (!fullReader.isStreamingSupported || !fullReader.isRangeSupported) { + if (this._lastProgress) { + loadingTask.onProgress?.(this._lastProgress); + } + fullReader.onProgress = evt => { + loadingTask.onProgress?.({ + loaded: evt.loaded, + total: evt.total + }); + }; + } + headersCapability.resolve({ + isStreamingSupported: fullReader.isStreamingSupported, + isRangeSupported: fullReader.isRangeSupported, + contentLength: fullReader.contentLength + }); + }, headersCapability.reject); + return headersCapability.promise; + }); + messageHandler.on("GetRangeReader", (data, sink) => { + assert(this._networkStream, "GetRangeReader - no `IPDFStream` instance available."); + const rangeReader = this._networkStream.getRangeReader(data.begin, data.end); + if (!rangeReader) { + sink.close(); + return; + } + sink.onPull = () => { + rangeReader.read().then(function ({ + value, + done + }) { + if (done) { + sink.close(); + return; + } + assert(value instanceof ArrayBuffer, "GetRangeReader - expected an ArrayBuffer."); + sink.enqueue(new Uint8Array(value), 1, [value]); + }).catch(reason => { + sink.error(reason); + }); + }; + sink.onCancel = reason => { + rangeReader.cancel(reason); + sink.ready.catch(readyReason => { + if (this.destroyed) { + return; + } + throw readyReason; + }); + }; + }); + messageHandler.on("GetDoc", ({ + pdfInfo + }) => { + this._numPages = pdfInfo.numPages; + this._htmlForXfa = pdfInfo.htmlForXfa; + delete pdfInfo.htmlForXfa; + loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this)); + }); + messageHandler.on("DocException", function (ex) { + let reason; + switch (ex.name) { + case "PasswordException": + reason = new PasswordException(ex.message, ex.code); + break; + case "InvalidPDFException": + reason = new InvalidPDFException(ex.message); + break; + case "MissingPDFException": + reason = new MissingPDFException(ex.message); + break; + case "UnexpectedResponseException": + reason = new UnexpectedResponseException(ex.message, ex.status); + break; + case "UnknownErrorException": + reason = new UnknownErrorException(ex.message, ex.details); + break; + default: + unreachable("DocException - expected a valid Error."); + } + loadingTask._capability.reject(reason); + }); + messageHandler.on("PasswordRequest", exception => { + this.#passwordCapability = Promise.withResolvers(); + if (loadingTask.onPassword) { + const updatePassword = password => { + if (password instanceof Error) { + this.#passwordCapability.reject(password); + } else { + this.#passwordCapability.resolve({ + password + }); + } + }; + try { + loadingTask.onPassword(updatePassword, exception.code); + } catch (ex) { + this.#passwordCapability.reject(ex); + } + } else { + this.#passwordCapability.reject(new PasswordException(exception.message, exception.code)); + } + return this.#passwordCapability.promise; + }); + messageHandler.on("DataLoaded", data => { + loadingTask.onProgress?.({ + loaded: data.length, + total: data.length + }); + this.downloadInfoCapability.resolve(data); + }); + messageHandler.on("StartRenderPage", data => { + if (this.destroyed) { + return; + } + const page = this.#pageCache.get(data.pageIndex); + page._startRenderPage(data.transparency, data.cacheKey); + }); + messageHandler.on("commonobj", ([id, type, exportedData]) => { + if (this.destroyed) { + return null; + } + if (this.commonObjs.has(id)) { + return null; + } + switch (type) { + case "Font": + const { + disableFontFace, + fontExtraProperties, + pdfBug + } = this._params; + if ("error" in exportedData) { + const exportedError = exportedData.error; + warn(`Error during font loading: ${exportedError}`); + this.commonObjs.resolve(id, exportedError); + break; + } + const inspectFont = pdfBug && globalThis.FontInspector?.enabled ? (font, url) => globalThis.FontInspector.fontAdded(font, url) : null; + const font = new FontFaceObject(exportedData, { + disableFontFace, + inspectFont + }); + this.fontLoader.bind(font).catch(() => messageHandler.sendWithPromise("FontFallback", { + id + })).finally(() => { + if (!fontExtraProperties && font.data) { + font.data = null; + } + this.commonObjs.resolve(id, font); + }); + break; + case "CopyLocalImage": + const { + imageRef + } = exportedData; + assert(imageRef, "The imageRef must be defined."); + for (const pageProxy of this.#pageCache.values()) { + for (const [, data] of pageProxy.objs) { + if (data?.ref !== imageRef) { + continue; + } + if (!data.dataLen) { + return null; + } + this.commonObjs.resolve(id, structuredClone(data)); + return data.dataLen; + } + } + break; + case "FontPath": + case "Image": + case "Pattern": + this.commonObjs.resolve(id, exportedData); + break; + default: + throw new Error(`Got unknown common object type ${type}`); + } + return null; + }); + messageHandler.on("obj", ([id, pageIndex, type, imageData]) => { + if (this.destroyed) { + return; + } + const pageProxy = this.#pageCache.get(pageIndex); + if (pageProxy.objs.has(id)) { + return; + } + if (pageProxy._intentStates.size === 0) { + imageData?.bitmap?.close(); + return; + } + switch (type) { + case "Image": + pageProxy.objs.resolve(id, imageData); + if (imageData?.dataLen > MAX_IMAGE_SIZE_TO_CACHE) { + pageProxy._maybeCleanupAfterRender = true; + } + break; + case "Pattern": + pageProxy.objs.resolve(id, imageData); + break; + default: + throw new Error(`Got unknown object type ${type}`); + } + }); + messageHandler.on("DocProgress", data => { + if (this.destroyed) { + return; + } + loadingTask.onProgress?.({ + loaded: data.loaded, + total: data.total + }); + }); + messageHandler.on("FetchBuiltInCMap", data => { + if (this.destroyed) { + return Promise.reject(new Error("Worker was destroyed.")); + } + if (!this.cMapReaderFactory) { + return Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.")); + } + return this.cMapReaderFactory.fetch(data); + }); + messageHandler.on("FetchStandardFontData", data => { + if (this.destroyed) { + return Promise.reject(new Error("Worker was destroyed.")); + } + if (!this.standardFontDataFactory) { + return Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.")); + } + return this.standardFontDataFactory.fetch(data); + }); + } + getData() { + return this.messageHandler.sendWithPromise("GetData", null); + } + saveDocument() { + if (this.annotationStorage.size <= 0) { + warn("saveDocument called while `annotationStorage` is empty, " + "please use the getData-method instead."); + } + const { + map, + transfer + } = this.annotationStorage.serializable; + return this.messageHandler.sendWithPromise("SaveDocument", { + isPureXfa: !!this._htmlForXfa, + numPages: this._numPages, + annotationStorage: map, + filename: this._fullReader?.filename ?? null + }, transfer).finally(() => { + this.annotationStorage.resetModified(); + }); + } + getPage(pageNumber) { + if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this._numPages) { + return Promise.reject(new Error("Invalid page request.")); + } + const pageIndex = pageNumber - 1, + cachedPromise = this.#pagePromises.get(pageIndex); + if (cachedPromise) { + return cachedPromise; + } + const promise = this.messageHandler.sendWithPromise("GetPage", { + pageIndex + }).then(pageInfo => { + if (this.destroyed) { + throw new Error("Transport destroyed"); + } + if (pageInfo.refStr) { + this.#pageRefCache.set(pageInfo.refStr, pageNumber); + } + const page = new PDFPageProxy(pageIndex, pageInfo, this, this._params.pdfBug); + this.#pageCache.set(pageIndex, page); + return page; + }); + this.#pagePromises.set(pageIndex, promise); + return promise; + } + getPageIndex(ref) { + if (!isRefProxy(ref)) { + return Promise.reject(new Error("Invalid pageIndex request.")); + } + return this.messageHandler.sendWithPromise("GetPageIndex", { + num: ref.num, + gen: ref.gen + }); + } + getAnnotations(pageIndex, intent) { + return this.messageHandler.sendWithPromise("GetAnnotations", { + pageIndex, + intent + }); + } + getFieldObjects() { + return this.#cacheSimpleMethod("GetFieldObjects"); + } + hasJSActions() { + return this.#cacheSimpleMethod("HasJSActions"); + } + getCalculationOrderIds() { + return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null); + } + getDestinations() { + return this.messageHandler.sendWithPromise("GetDestinations", null); + } + getDestination(id) { + if (typeof id !== "string") { + return Promise.reject(new Error("Invalid destination request.")); + } + return this.messageHandler.sendWithPromise("GetDestination", { + id + }); + } + getPageLabels() { + return this.messageHandler.sendWithPromise("GetPageLabels", null); + } + getPageLayout() { + return this.messageHandler.sendWithPromise("GetPageLayout", null); + } + getPageMode() { + return this.messageHandler.sendWithPromise("GetPageMode", null); + } + getViewerPreferences() { + return this.messageHandler.sendWithPromise("GetViewerPreferences", null); + } + getOpenAction() { + return this.messageHandler.sendWithPromise("GetOpenAction", null); + } + getAttachments() { + return this.messageHandler.sendWithPromise("GetAttachments", null); + } + getDocJSActions() { + return this.#cacheSimpleMethod("GetDocJSActions"); + } + getPageJSActions(pageIndex) { + return this.messageHandler.sendWithPromise("GetPageJSActions", { + pageIndex + }); + } + getStructTree(pageIndex) { + return this.messageHandler.sendWithPromise("GetStructTree", { + pageIndex + }); + } + getOutline() { + return this.messageHandler.sendWithPromise("GetOutline", null); + } + getOptionalContentConfig(renderingIntent) { + return this.#cacheSimpleMethod("GetOptionalContentConfig").then(data => new OptionalContentConfig(data, renderingIntent)); + } + getPermissions() { + return this.messageHandler.sendWithPromise("GetPermissions", null); + } + getMetadata() { + const name = "GetMetadata", + cachedPromise = this.#methodPromises.get(name); + if (cachedPromise) { + return cachedPromise; + } + const promise = this.messageHandler.sendWithPromise(name, null).then(results => ({ + info: results[0], + metadata: results[1] ? new Metadata(results[1]) : null, + contentDispositionFilename: this._fullReader?.filename ?? null, + contentLength: this._fullReader?.contentLength ?? null + })); + this.#methodPromises.set(name, promise); + return promise; + } + getMarkInfo() { + return this.messageHandler.sendWithPromise("GetMarkInfo", null); + } + async startCleanup(keepLoadedFonts = false) { + if (this.destroyed) { + return; + } + await this.messageHandler.sendWithPromise("Cleanup", null); + for (const page of this.#pageCache.values()) { + const cleanupSuccessful = page.cleanup(); + if (!cleanupSuccessful) { + throw new Error(`startCleanup: Page ${page.pageNumber} is currently rendering.`); + } + } + this.commonObjs.clear(); + if (!keepLoadedFonts) { + this.fontLoader.clear(); + } + this.#methodPromises.clear(); + this.filterFactory.destroy(true); + TextLayer.cleanup(); + } + cachedPageNumber(ref) { + if (!isRefProxy(ref)) { + return null; + } + const refStr = ref.gen === 0 ? `${ref.num}R` : `${ref.num}R${ref.gen}`; + return this.#pageRefCache.get(refStr) ?? null; + } +} +const INITIAL_DATA = Symbol("INITIAL_DATA"); +class PDFObjects { + #objs = Object.create(null); + #ensureObj(objId) { + return this.#objs[objId] ||= { + ...Promise.withResolvers(), + data: INITIAL_DATA + }; + } + get(objId, callback = null) { + if (callback) { + const obj = this.#ensureObj(objId); + obj.promise.then(() => callback(obj.data)); + return null; + } + const obj = this.#objs[objId]; + if (!obj || obj.data === INITIAL_DATA) { + throw new Error(`Requesting object that isn't resolved yet ${objId}.`); + } + return obj.data; + } + has(objId) { + const obj = this.#objs[objId]; + return !!obj && obj.data !== INITIAL_DATA; + } + resolve(objId, data = null) { + const obj = this.#ensureObj(objId); + obj.data = data; + obj.resolve(); + } + clear() { + for (const objId in this.#objs) { + const { + data + } = this.#objs[objId]; + data?.bitmap?.close(); + } + this.#objs = Object.create(null); + } + *[Symbol.iterator]() { + for (const objId in this.#objs) { + const { + data + } = this.#objs[objId]; + if (data === INITIAL_DATA) { + continue; + } + yield [objId, data]; + } + } +} +class RenderTask { + #internalRenderTask = null; + constructor(internalRenderTask) { + this.#internalRenderTask = internalRenderTask; + this.onContinue = null; + } + get promise() { + return this.#internalRenderTask.capability.promise; + } + cancel(extraDelay = 0) { + this.#internalRenderTask.cancel(null, extraDelay); + } + get separateAnnots() { + const { + separateAnnots + } = this.#internalRenderTask.operatorList; + if (!separateAnnots) { + return false; + } + const { + annotationCanvasMap + } = this.#internalRenderTask; + return separateAnnots.form || separateAnnots.canvas && annotationCanvasMap?.size > 0; + } +} +class InternalRenderTask { + #rAF = null; + static #canvasInUse = new WeakSet(); + constructor({ + callback, + params, + objs, + commonObjs, + annotationCanvasMap, + operatorList, + pageIndex, + canvasFactory, + filterFactory, + useRequestAnimationFrame = false, + pdfBug = false, + pageColors = null + }) { + this.callback = callback; + this.params = params; + this.objs = objs; + this.commonObjs = commonObjs; + this.annotationCanvasMap = annotationCanvasMap; + this.operatorListIdx = null; + this.operatorList = operatorList; + this._pageIndex = pageIndex; + this.canvasFactory = canvasFactory; + this.filterFactory = filterFactory; + this._pdfBug = pdfBug; + this.pageColors = pageColors; + this.running = false; + this.graphicsReadyCallback = null; + this.graphicsReady = false; + this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== "undefined"; + this.cancelled = false; + this.capability = Promise.withResolvers(); + this.task = new RenderTask(this); + this._cancelBound = this.cancel.bind(this); + this._continueBound = this._continue.bind(this); + this._scheduleNextBound = this._scheduleNext.bind(this); + this._nextBound = this._next.bind(this); + this._canvas = params.canvasContext.canvas; + } + get completed() { + return this.capability.promise.catch(function () {}); + } + initializeGraphics({ + transparency = false, + optionalContentConfig + }) { + if (this.cancelled) { + return; + } + if (this._canvas) { + if (InternalRenderTask.#canvasInUse.has(this._canvas)) { + throw new Error("Cannot use the same canvas during multiple render() operations. " + "Use different canvas or ensure previous operations were " + "cancelled or completed."); + } + InternalRenderTask.#canvasInUse.add(this._canvas); + } + if (this._pdfBug && globalThis.StepperManager?.enabled) { + this.stepper = globalThis.StepperManager.create(this._pageIndex); + this.stepper.init(this.operatorList); + this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint(); + } + const { + canvasContext, + viewport, + transform, + background + } = this.params; + this.gfx = new CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, { + optionalContentConfig + }, this.annotationCanvasMap, this.pageColors); + this.gfx.beginDrawing({ + transform, + viewport, + transparency, + background + }); + this.operatorListIdx = 0; + this.graphicsReady = true; + this.graphicsReadyCallback?.(); + } + cancel(error = null, extraDelay = 0) { + this.running = false; + this.cancelled = true; + this.gfx?.endDrawing(); + if (this.#rAF) { + window.cancelAnimationFrame(this.#rAF); + this.#rAF = null; + } + InternalRenderTask.#canvasInUse.delete(this._canvas); + this.callback(error || new RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, extraDelay)); + } + operatorListChanged() { + if (!this.graphicsReady) { + this.graphicsReadyCallback ||= this._continueBound; + return; + } + this.stepper?.updateOperatorList(this.operatorList); + if (this.running) { + return; + } + this._continue(); + } + _continue() { + this.running = true; + if (this.cancelled) { + return; + } + if (this.task.onContinue) { + this.task.onContinue(this._scheduleNextBound); + } else { + this._scheduleNext(); + } + } + _scheduleNext() { + if (this._useRequestAnimationFrame) { + this.#rAF = window.requestAnimationFrame(() => { + this.#rAF = null; + this._nextBound().catch(this._cancelBound); + }); + } else { + Promise.resolve().then(this._nextBound).catch(this._cancelBound); + } + } + async _next() { + if (this.cancelled) { + return; + } + this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper); + if (this.operatorListIdx === this.operatorList.argsArray.length) { + this.running = false; + if (this.operatorList.lastChunk) { + this.gfx.endDrawing(); + InternalRenderTask.#canvasInUse.delete(this._canvas); + this.callback(); + } + } + } +} +const version = "4.6.82"; +const build = "9b541910f"; -/***/ }), -/* 30 */ -/***/ ((__unused_webpack_module, exports) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.ColorConverters = void 0; +;// CONCATENATED MODULE: ./src/shared/scripting_utils.js function makeColorComp(n) { return Math.floor(Math.max(0, Math.min(1, n)) * 255).toString(16).padStart(2, "0"); } @@ -16337,117 +12893,9 @@ class ColorConverters { return ["CMYK", c, m, y, k]; } } -exports.ColorConverters = ColorConverters; -/***/ }), -/* 31 */ -/***/ ((__unused_webpack_module, exports) => { +;// CONCATENATED MODULE: ./src/display/xfa_layer.js - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.NullL10n = void 0; -exports.getL10nFallback = getL10nFallback; -const DEFAULT_L10N_STRINGS = { - of_pages: "of {{pagesCount}}", - page_of_pages: "({{pageNumber}} of {{pagesCount}})", - document_properties_kb: "{{size_kb}} KB ({{size_b}} bytes)", - document_properties_mb: "{{size_mb}} MB ({{size_b}} bytes)", - document_properties_date_string: "{{date}}, {{time}}", - document_properties_page_size_unit_inches: "in", - document_properties_page_size_unit_millimeters: "mm", - document_properties_page_size_orientation_portrait: "portrait", - document_properties_page_size_orientation_landscape: "landscape", - document_properties_page_size_name_a3: "A3", - document_properties_page_size_name_a4: "A4", - document_properties_page_size_name_letter: "Letter", - document_properties_page_size_name_legal: "Legal", - document_properties_page_size_dimension_string: "{{width}} × {{height}} {{unit}} ({{orientation}})", - document_properties_page_size_dimension_name_string: "{{width}} × {{height}} {{unit}} ({{name}}, {{orientation}})", - document_properties_linearized_yes: "Yes", - document_properties_linearized_no: "No", - additional_layers: "Additional Layers", - page_landmark: "Page {{page}}", - thumb_page_title: "Page {{page}}", - thumb_page_canvas: "Thumbnail of Page {{page}}", - find_reached_top: "Reached top of document, continued from bottom", - find_reached_bottom: "Reached end of document, continued from top", - "find_match_count[one]": "{{current}} of {{total}} match", - "find_match_count[other]": "{{current}} of {{total}} matches", - "find_match_count_limit[one]": "More than {{limit}} match", - "find_match_count_limit[other]": "More than {{limit}} matches", - find_not_found: "Phrase not found", - page_scale_width: "Page Width", - page_scale_fit: "Page Fit", - page_scale_auto: "Automatic Zoom", - page_scale_actual: "Actual Size", - page_scale_percent: "{{scale}}%", - loading_error: "An error occurred while loading the PDF.", - invalid_file_error: "Invalid or corrupted PDF file.", - missing_file_error: "Missing PDF file.", - unexpected_response_error: "Unexpected server response.", - rendering_error: "An error occurred while rendering the page.", - annotation_date_string: "{{date}}, {{time}}", - printing_not_supported: "Warning: Printing is not fully supported by this browser.", - printing_not_ready: "Warning: The PDF is not fully loaded for printing.", - web_fonts_disabled: "Web fonts are disabled: unable to use embedded PDF fonts.", - free_text2_default_content: "Start typing…", - editor_free_text2_aria_label: "Text Editor", - editor_ink2_aria_label: "Draw Editor", - editor_ink_canvas_aria_label: "User-created image", - editor_alt_text_button_label: "Alt text", - editor_alt_text_edit_button_label: "Edit alt text", - editor_alt_text_decorative_tooltip: "Marked as decorative" -}; -{ - DEFAULT_L10N_STRINGS.print_progress_percent = "{{progress}}%"; -} -function getL10nFallback(key, args) { - switch (key) { - case "find_match_count": - key = `find_match_count[${args.total === 1 ? "one" : "other"}]`; - break; - case "find_match_count_limit": - key = `find_match_count_limit[${args.limit === 1 ? "one" : "other"}]`; - break; - } - return DEFAULT_L10N_STRINGS[key] || ""; -} -function formatL10nValue(text, args) { - if (!args) { - return text; - } - return text.replaceAll(/\{\{\s*(\w+)\s*\}\}/g, (all, name) => { - return name in args ? args[name] : "{{" + name + "}}"; - }); -} -const NullL10n = { - async getLanguage() { - return "en-us"; - }, - async getDirection() { - return "ltr"; - }, - async get(key, args = null, fallback = getL10nFallback(key, args)) { - return formatL10nValue(fallback, args); - }, - async translate(element) {} -}; -exports.NullL10n = NullL10n; - -/***/ }), -/* 32 */ -/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.XfaLayer = void 0; -var _xfa_text = __w_pdfjs_require__(25); class XfaLayer { static setupStorage(html, id, element, storage, intent) { const storedData = storage.getValue(id, { @@ -16579,17 +13027,30 @@ class XfaLayer { linkService }); } - const stack = [[root, -1, rootHtml]]; + const isNotForRichText = intent !== "richText"; const rootDiv = parameters.div; rootDiv.append(rootHtml); if (parameters.viewport) { const transform = `matrix(${parameters.viewport.transform.join(",")})`; rootDiv.style.transform = transform; } - if (intent !== "richText") { + if (isNotForRichText) { rootDiv.setAttribute("class", "xfaLayer xfaFont"); } const textDivs = []; + if (root.children.length === 0) { + if (root.value) { + const node = document.createTextNode(root.value); + rootHtml.append(node); + if (isNotForRichText && XfaText.shouldBuildText(root.name)) { + textDivs.push(node); + } + } + return { + textDivs + }; + } + const stack = [[root, -1, rootHtml]]; while (stack.length > 0) { const [parent, i, html] = stack.at(-1); if (i + 1 === parent.children.length) { @@ -16620,11 +13081,11 @@ class XfaLayer { linkService }); } - if (child.children && child.children.length > 0) { + if (child.children?.length > 0) { stack.push([child, -1, childHtml]); } else if (child.value) { const node = document.createTextNode(child.value); - if (_xfa_text.XfaText.shouldBuildText(name)) { + if (isNotForRichText && XfaText.shouldBuildText(name)) { textDivs.push(node); } childHtml.append(node); @@ -16643,35 +13104,4650 @@ class XfaLayer { parameters.div.hidden = false; } } -exports.XfaLayer = XfaLayer; -/***/ }), -/* 33 */ -/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { +;// CONCATENATED MODULE: ./src/display/annotation_layer.js -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.InkEditor = void 0; -var _util = __w_pdfjs_require__(1); -var _editor = __w_pdfjs_require__(4); -var _annotation_layer = __w_pdfjs_require__(29); -var _display_utils = __w_pdfjs_require__(6); -var _tools = __w_pdfjs_require__(5); -class InkEditor extends _editor.AnnotationEditor { + + +const DEFAULT_TAB_INDEX = 1000; +const annotation_layer_DEFAULT_FONT_SIZE = 9; +const GetElementsByNameSet = new WeakSet(); +function getRectDims(rect) { + return { + width: rect[2] - rect[0], + height: rect[3] - rect[1] + }; +} +class AnnotationElementFactory { + static create(parameters) { + const subtype = parameters.data.annotationType; + switch (subtype) { + case AnnotationType.LINK: + return new LinkAnnotationElement(parameters); + case AnnotationType.TEXT: + return new TextAnnotationElement(parameters); + case AnnotationType.WIDGET: + const fieldType = parameters.data.fieldType; + switch (fieldType) { + case "Tx": + return new TextWidgetAnnotationElement(parameters); + case "Btn": + if (parameters.data.radioButton) { + return new RadioButtonWidgetAnnotationElement(parameters); + } else if (parameters.data.checkBox) { + return new CheckboxWidgetAnnotationElement(parameters); + } + return new PushButtonWidgetAnnotationElement(parameters); + case "Ch": + return new ChoiceWidgetAnnotationElement(parameters); + case "Sig": + return new SignatureWidgetAnnotationElement(parameters); + } + return new WidgetAnnotationElement(parameters); + case AnnotationType.POPUP: + return new PopupAnnotationElement(parameters); + case AnnotationType.FREETEXT: + return new FreeTextAnnotationElement(parameters); + case AnnotationType.LINE: + return new LineAnnotationElement(parameters); + case AnnotationType.SQUARE: + return new SquareAnnotationElement(parameters); + case AnnotationType.CIRCLE: + return new CircleAnnotationElement(parameters); + case AnnotationType.POLYLINE: + return new PolylineAnnotationElement(parameters); + case AnnotationType.CARET: + return new CaretAnnotationElement(parameters); + case AnnotationType.INK: + return new InkAnnotationElement(parameters); + case AnnotationType.POLYGON: + return new PolygonAnnotationElement(parameters); + case AnnotationType.HIGHLIGHT: + return new HighlightAnnotationElement(parameters); + case AnnotationType.UNDERLINE: + return new UnderlineAnnotationElement(parameters); + case AnnotationType.SQUIGGLY: + return new SquigglyAnnotationElement(parameters); + case AnnotationType.STRIKEOUT: + return new StrikeOutAnnotationElement(parameters); + case AnnotationType.STAMP: + return new StampAnnotationElement(parameters); + case AnnotationType.FILEATTACHMENT: + return new FileAttachmentAnnotationElement(parameters); + default: + return new AnnotationElement(parameters); + } + } +} +class AnnotationElement { + #updates = null; + #hasBorder = false; + #popupElement = null; + constructor(parameters, { + isRenderable = false, + ignoreBorder = false, + createQuadrilaterals = false + } = {}) { + this.isRenderable = isRenderable; + this.data = parameters.data; + this.layer = parameters.layer; + this.linkService = parameters.linkService; + this.downloadManager = parameters.downloadManager; + this.imageResourcesPath = parameters.imageResourcesPath; + this.renderForms = parameters.renderForms; + this.svgFactory = parameters.svgFactory; + this.annotationStorage = parameters.annotationStorage; + this.enableScripting = parameters.enableScripting; + this.hasJSActions = parameters.hasJSActions; + this._fieldObjects = parameters.fieldObjects; + this.parent = parameters.parent; + if (isRenderable) { + this.container = this._createContainer(ignoreBorder); + } + if (createQuadrilaterals) { + this._createQuadrilaterals(); + } + } + static _hasPopupData({ + titleObj, + contentsObj, + richText + }) { + return !!(titleObj?.str || contentsObj?.str || richText?.str); + } + get _isEditable() { + return this.data.isEditable; + } + get hasPopupData() { + return AnnotationElement._hasPopupData(this.data); + } + updateEdited(params) { + if (!this.container) { + return; + } + this.#updates ||= { + rect: this.data.rect.slice(0) + }; + const { + rect + } = params; + if (rect) { + this.#setRectEdited(rect); + } + this.#popupElement?.popup.updateEdited(params); + } + resetEdited() { + if (!this.#updates) { + return; + } + this.#setRectEdited(this.#updates.rect); + this.#popupElement?.popup.resetEdited(); + this.#updates = null; + } + #setRectEdited(rect) { + const { + container: { + style + }, + data: { + rect: currentRect, + rotation + }, + parent: { + viewport: { + rawDims: { + pageWidth, + pageHeight, + pageX, + pageY + } + } + } + } = this; + currentRect?.splice(0, 4, ...rect); + const { + width, + height + } = getRectDims(rect); + style.left = `${100 * (rect[0] - pageX) / pageWidth}%`; + style.top = `${100 * (pageHeight - rect[3] + pageY) / pageHeight}%`; + if (rotation === 0) { + style.width = `${100 * width / pageWidth}%`; + style.height = `${100 * height / pageHeight}%`; + } else { + this.setRotation(rotation); + } + } + _createContainer(ignoreBorder) { + const { + data, + parent: { + page, + viewport + } + } = this; + const container = document.createElement("section"); + container.setAttribute("data-annotation-id", data.id); + if (!(this instanceof WidgetAnnotationElement)) { + container.tabIndex = DEFAULT_TAB_INDEX; + } + const { + style + } = container; + style.zIndex = this.parent.zIndex++; + if (data.popupRef) { + container.setAttribute("aria-haspopup", "dialog"); + } + if (data.alternativeText) { + container.title = data.alternativeText; + } + if (data.noRotate) { + container.classList.add("norotate"); + } + if (!data.rect || this instanceof PopupAnnotationElement) { + const { + rotation + } = data; + if (!data.hasOwnCanvas && rotation !== 0) { + this.setRotation(rotation, container); + } + return container; + } + const { + width, + height + } = getRectDims(data.rect); + if (!ignoreBorder && data.borderStyle.width > 0) { + style.borderWidth = `${data.borderStyle.width}px`; + const horizontalRadius = data.borderStyle.horizontalCornerRadius; + const verticalRadius = data.borderStyle.verticalCornerRadius; + if (horizontalRadius > 0 || verticalRadius > 0) { + const radius = `calc(${horizontalRadius}px * var(--scale-factor)) / calc(${verticalRadius}px * var(--scale-factor))`; + style.borderRadius = radius; + } else if (this instanceof RadioButtonWidgetAnnotationElement) { + const radius = `calc(${width}px * var(--scale-factor)) / calc(${height}px * var(--scale-factor))`; + style.borderRadius = radius; + } + switch (data.borderStyle.style) { + case AnnotationBorderStyleType.SOLID: + style.borderStyle = "solid"; + break; + case AnnotationBorderStyleType.DASHED: + style.borderStyle = "dashed"; + break; + case AnnotationBorderStyleType.BEVELED: + warn("Unimplemented border style: beveled"); + break; + case AnnotationBorderStyleType.INSET: + warn("Unimplemented border style: inset"); + break; + case AnnotationBorderStyleType.UNDERLINE: + style.borderBottomStyle = "solid"; + break; + default: + break; + } + const borderColor = data.borderColor || null; + if (borderColor) { + this.#hasBorder = true; + style.borderColor = Util.makeHexColor(borderColor[0] | 0, borderColor[1] | 0, borderColor[2] | 0); + } else { + style.borderWidth = 0; + } + } + 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]]); + const { + pageWidth, + pageHeight, + pageX, + pageY + } = viewport.rawDims; + style.left = `${100 * (rect[0] - pageX) / pageWidth}%`; + style.top = `${100 * (rect[1] - pageY) / pageHeight}%`; + const { + rotation + } = data; + if (data.hasOwnCanvas || rotation === 0) { + style.width = `${100 * width / pageWidth}%`; + style.height = `${100 * height / pageHeight}%`; + } else { + this.setRotation(rotation, container); + } + return container; + } + setRotation(angle, container = this.container) { + if (!this.data.rect) { + return; + } + const { + pageWidth, + pageHeight + } = this.parent.viewport.rawDims; + const { + width, + height + } = getRectDims(this.data.rect); + let elementWidth, elementHeight; + if (angle % 180 === 0) { + elementWidth = 100 * width / pageWidth; + elementHeight = 100 * height / pageHeight; + } else { + elementWidth = 100 * height / pageWidth; + elementHeight = 100 * width / pageHeight; + } + container.style.width = `${elementWidth}%`; + container.style.height = `${elementHeight}%`; + container.setAttribute("data-main-rotation", (360 - angle) % 360); + } + get _commonActions() { + const setColor = (jsName, styleName, event) => { + const color = event.detail[jsName]; + const colorType = color[0]; + const colorArray = color.slice(1); + event.target.style[styleName] = ColorConverters[`${colorType}_HTML`](colorArray); + this.annotationStorage.setValue(this.data.id, { + [styleName]: ColorConverters[`${colorType}_rgb`](colorArray) + }); + }; + return shadow(this, "_commonActions", { + display: event => { + const { + display + } = event.detail; + const hidden = display % 2 === 1; + this.container.style.visibility = hidden ? "hidden" : "visible"; + this.annotationStorage.setValue(this.data.id, { + noView: hidden, + noPrint: display === 1 || display === 2 + }); + }, + print: event => { + this.annotationStorage.setValue(this.data.id, { + noPrint: !event.detail.print + }); + }, + hidden: event => { + const { + hidden + } = event.detail; + this.container.style.visibility = hidden ? "hidden" : "visible"; + this.annotationStorage.setValue(this.data.id, { + noPrint: hidden, + noView: hidden + }); + }, + focus: event => { + setTimeout(() => event.target.focus({ + preventScroll: false + }), 0); + }, + userName: event => { + event.target.title = event.detail.userName; + }, + readonly: event => { + event.target.disabled = event.detail.readonly; + }, + required: event => { + this._setRequired(event.target, event.detail.required); + }, + bgColor: event => { + setColor("bgColor", "backgroundColor", event); + }, + fillColor: event => { + setColor("fillColor", "backgroundColor", event); + }, + fgColor: event => { + setColor("fgColor", "color", event); + }, + textColor: event => { + setColor("textColor", "color", event); + }, + borderColor: event => { + setColor("borderColor", "borderColor", event); + }, + strokeColor: event => { + setColor("strokeColor", "borderColor", event); + }, + rotation: event => { + const angle = event.detail.rotation; + this.setRotation(angle); + this.annotationStorage.setValue(this.data.id, { + rotation: angle + }); + } + }); + } + _dispatchEventFromSandbox(actions, jsEvent) { + const commonActions = this._commonActions; + for (const name of Object.keys(jsEvent.detail)) { + const action = actions[name] || commonActions[name]; + action?.(jsEvent); + } + } + _setDefaultPropertiesFromJS(element) { + if (!this.enableScripting) { + return; + } + const storedData = this.annotationStorage.getRawValue(this.data.id); + if (!storedData) { + return; + } + const commonActions = this._commonActions; + for (const [actionName, detail] of Object.entries(storedData)) { + const action = commonActions[actionName]; + if (action) { + const eventProxy = { + detail: { + [actionName]: detail + }, + target: element + }; + action(eventProxy); + delete storedData[actionName]; + } + } + } + _createQuadrilaterals() { + if (!this.container) { + return; + } + const { + quadPoints + } = this.data; + if (!quadPoints) { + return; + } + const [rectBlX, rectBlY, rectTrX, rectTrY] = this.data.rect.map(x => Math.fround(x)); + if (quadPoints.length === 8) { + const [trX, trY, blX, blY] = quadPoints.subarray(2, 6); + if (rectTrX === trX && rectTrY === trY && rectBlX === blX && rectBlY === blY) { + return; + } + } + const { + style + } = this.container; + let svgBuffer; + if (this.#hasBorder) { + const { + borderColor, + borderWidth + } = style; + style.borderWidth = 0; + svgBuffer = ["url('data:image/svg+xml;utf8,", ``, ``]; + this.container.classList.add("hasBorder"); + } + const width = rectTrX - rectBlX; + const height = rectTrY - rectBlY; + const { + svgFactory + } = this; + const svg = svgFactory.createElement("svg"); + svg.classList.add("quadrilateralsContainer"); + svg.setAttribute("width", 0); + svg.setAttribute("height", 0); + const defs = svgFactory.createElement("defs"); + svg.append(defs); + const clipPath = svgFactory.createElement("clipPath"); + const id = `clippath_${this.data.id}`; + clipPath.setAttribute("id", id); + clipPath.setAttribute("clipPathUnits", "objectBoundingBox"); + defs.append(clipPath); + for (let i = 2, ii = quadPoints.length; i < ii; i += 8) { + const trX = quadPoints[i]; + const trY = quadPoints[i + 1]; + const blX = quadPoints[i + 2]; + const blY = quadPoints[i + 3]; + const rect = svgFactory.createElement("rect"); + const x = (blX - rectBlX) / width; + const y = (rectTrY - trY) / height; + const rectWidth = (trX - blX) / width; + const rectHeight = (trY - blY) / height; + rect.setAttribute("x", x); + rect.setAttribute("y", y); + rect.setAttribute("width", rectWidth); + rect.setAttribute("height", rectHeight); + clipPath.append(rect); + svgBuffer?.push(``); + } + if (this.#hasBorder) { + svgBuffer.push(`')`); + style.backgroundImage = svgBuffer.join(""); + } + this.container.append(svg); + this.container.style.clipPath = `url(#${id})`; + } + _createPopup() { + const { + container, + data + } = this; + container.setAttribute("aria-haspopup", "dialog"); + const popup = this.#popupElement = new PopupAnnotationElement({ + data: { + color: data.color, + titleObj: data.titleObj, + modificationDate: data.modificationDate, + contentsObj: data.contentsObj, + richText: data.richText, + parentRect: data.rect, + borderStyle: 0, + id: `popup_${data.id}`, + rotation: data.rotation + }, + parent: this.parent, + elements: [this] + }); + this.parent.div.append(popup.render()); + } + render() { + unreachable("Abstract method `AnnotationElement.render` called"); + } + _getElementsByName(name, skipId = null) { + const fields = []; + if (this._fieldObjects) { + const fieldObj = this._fieldObjects[name]; + if (fieldObj) { + for (const { + page, + id, + exportValues + } of fieldObj) { + if (page === -1) { + continue; + } + if (id === skipId) { + continue; + } + const exportValue = typeof exportValues === "string" ? exportValues : null; + const domElement = document.querySelector(`[data-element-id="${id}"]`); + if (domElement && !GetElementsByNameSet.has(domElement)) { + warn(`_getElementsByName - element not allowed: ${id}`); + continue; + } + fields.push({ + id, + exportValue, + domElement + }); + } + } + return fields; + } + for (const domElement of document.getElementsByName(name)) { + const { + exportValue + } = domElement; + const id = domElement.getAttribute("data-element-id"); + if (id === skipId) { + continue; + } + if (!GetElementsByNameSet.has(domElement)) { + continue; + } + fields.push({ + id, + exportValue, + domElement + }); + } + return fields; + } + show() { + if (this.container) { + this.container.hidden = false; + } + this.popup?.maybeShow(); + } + hide() { + if (this.container) { + this.container.hidden = true; + } + this.popup?.forceHide(); + } + getElementsToTriggerPopup() { + return this.container; + } + addHighlightArea() { + const triggers = this.getElementsToTriggerPopup(); + if (Array.isArray(triggers)) { + for (const element of triggers) { + element.classList.add("highlightArea"); + } + } else { + triggers.classList.add("highlightArea"); + } + } + _editOnDoubleClick() { + if (!this._isEditable) { + return; + } + const { + annotationEditorType: mode, + data: { + id: editId + } + } = this; + this.container.addEventListener("dblclick", () => { + this.linkService.eventBus?.dispatch("switchannotationeditormode", { + source: this, + mode, + editId + }); + }); + } +} +class LinkAnnotationElement extends AnnotationElement { + constructor(parameters, options = null) { + super(parameters, { + isRenderable: true, + ignoreBorder: !!options?.ignoreBorder, + createQuadrilaterals: true + }); + this.isTooltipOnly = parameters.data.isTooltipOnly; + } + render() { + const { + data, + linkService + } = this; + const link = document.createElement("a"); + link.setAttribute("data-element-id", data.id); + let isBound = false; + if (data.url) { + linkService.addLinkAttributes(link, data.url, data.newWindow); + isBound = true; + } else if (data.action) { + this._bindNamedAction(link, data.action); + isBound = true; + } else if (data.attachment) { + this.#bindAttachment(link, data.attachment, data.attachmentDest); + isBound = true; + } else if (data.setOCGState) { + this.#bindSetOCGState(link, data.setOCGState); + isBound = true; + } else if (data.dest) { + this._bindLink(link, data.dest); + isBound = true; + } else { + if (data.actions && (data.actions.Action || data.actions["Mouse Up"] || data.actions["Mouse Down"]) && this.enableScripting && this.hasJSActions) { + this._bindJSAction(link, data); + isBound = true; + } + if (data.resetForm) { + this._bindResetFormAction(link, data.resetForm); + isBound = true; + } else if (this.isTooltipOnly && !isBound) { + this._bindLink(link, ""); + isBound = true; + } + } + this.container.classList.add("linkAnnotation"); + if (isBound) { + this.container.append(link); + } + return this.container; + } + #setInternalLink() { + this.container.setAttribute("data-internal-link", ""); + } + _bindLink(link, destination) { + link.href = this.linkService.getDestinationHash(destination); + link.onclick = () => { + if (destination) { + this.linkService.goToDestination(destination); + } + return false; + }; + if (destination || destination === "") { + this.#setInternalLink(); + } + } + _bindNamedAction(link, action) { + link.href = this.linkService.getAnchorUrl(""); + link.onclick = () => { + this.linkService.executeNamedAction(action); + return false; + }; + this.#setInternalLink(); + } + #bindAttachment(link, attachment, dest = null) { + link.href = this.linkService.getAnchorUrl(""); + if (attachment.description) { + link.title = attachment.description; + } + link.onclick = () => { + this.downloadManager?.openOrDownloadData(attachment.content, attachment.filename, dest); + return false; + }; + this.#setInternalLink(); + } + #bindSetOCGState(link, action) { + link.href = this.linkService.getAnchorUrl(""); + link.onclick = () => { + this.linkService.executeSetOCGState(action); + return false; + }; + this.#setInternalLink(); + } + _bindJSAction(link, data) { + link.href = this.linkService.getAnchorUrl(""); + const map = new Map([["Action", "onclick"], ["Mouse Up", "onmouseup"], ["Mouse Down", "onmousedown"]]); + for (const name of Object.keys(data.actions)) { + const jsName = map.get(name); + if (!jsName) { + continue; + } + link[jsName] = () => { + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id: data.id, + name + } + }); + return false; + }; + } + if (!link.onclick) { + link.onclick = () => false; + } + this.#setInternalLink(); + } + _bindResetFormAction(link, resetForm) { + const otherClickAction = link.onclick; + if (!otherClickAction) { + link.href = this.linkService.getAnchorUrl(""); + } + this.#setInternalLink(); + if (!this._fieldObjects) { + warn(`_bindResetFormAction - "resetForm" action not supported, ` + "ensure that the `fieldObjects` parameter is provided."); + if (!otherClickAction) { + link.onclick = () => false; + } + return; + } + link.onclick = () => { + otherClickAction?.(); + const { + fields: resetFormFields, + refs: resetFormRefs, + include + } = resetForm; + const allFields = []; + if (resetFormFields.length !== 0 || resetFormRefs.length !== 0) { + const fieldIds = new Set(resetFormRefs); + for (const fieldName of resetFormFields) { + const fields = this._fieldObjects[fieldName] || []; + for (const { + id + } of fields) { + fieldIds.add(id); + } + } + for (const fields of Object.values(this._fieldObjects)) { + for (const field of fields) { + if (fieldIds.has(field.id) === include) { + allFields.push(field); + } + } + } + } else { + for (const fields of Object.values(this._fieldObjects)) { + allFields.push(...fields); + } + } + const storage = this.annotationStorage; + const allIds = []; + for (const field of allFields) { + const { + id + } = field; + allIds.push(id); + switch (field.type) { + case "text": + { + const value = field.defaultValue || ""; + storage.setValue(id, { + value + }); + break; + } + case "checkbox": + case "radiobutton": + { + const value = field.defaultValue === field.exportValues; + storage.setValue(id, { + value + }); + break; + } + case "combobox": + case "listbox": + { + const value = field.defaultValue || ""; + storage.setValue(id, { + value + }); + break; + } + default: + continue; + } + const domElement = document.querySelector(`[data-element-id="${id}"]`); + if (!domElement) { + continue; + } else if (!GetElementsByNameSet.has(domElement)) { + warn(`_bindResetFormAction - element not allowed: ${id}`); + continue; + } + domElement.dispatchEvent(new Event("resetform")); + } + if (this.enableScripting) { + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id: "app", + ids: allIds, + name: "ResetForm" + } + }); + } + return false; + }; + } +} +class TextAnnotationElement extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true + }); + } + render() { + this.container.classList.add("textAnnotation"); + const image = document.createElement("img"); + image.src = this.imageResourcesPath + "annotation-" + this.data.name.toLowerCase() + ".svg"; + image.setAttribute("data-l10n-id", "pdfjs-text-annotation-type"); + image.setAttribute("data-l10n-args", JSON.stringify({ + type: this.data.name + })); + if (!this.data.popupRef && this.hasPopupData) { + this._createPopup(); + } + this.container.append(image); + return this.container; + } +} +class WidgetAnnotationElement extends AnnotationElement { + render() { + return this.container; + } + showElementAndHideCanvas(element) { + if (this.data.hasOwnCanvas) { + if (element.previousSibling?.nodeName === "CANVAS") { + element.previousSibling.hidden = true; + } + element.hidden = false; + } + } + _getKeyModifier(event) { + return util_FeatureTest.platform.isMac ? event.metaKey : event.ctrlKey; + } + _setEventListener(element, elementData, baseName, eventName, valueGetter) { + if (baseName.includes("mouse")) { + element.addEventListener(baseName, event => { + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id: this.data.id, + name: eventName, + value: valueGetter(event), + shift: event.shiftKey, + modifier: this._getKeyModifier(event) + } + }); + }); + } else { + element.addEventListener(baseName, event => { + if (baseName === "blur") { + if (!elementData.focused || !event.relatedTarget) { + return; + } + elementData.focused = false; + } else if (baseName === "focus") { + if (elementData.focused) { + return; + } + elementData.focused = true; + } + if (!valueGetter) { + return; + } + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id: this.data.id, + name: eventName, + value: valueGetter(event) + } + }); + }); + } + } + _setEventListeners(element, elementData, names, getter) { + for (const [baseName, eventName] of names) { + if (eventName === "Action" || this.data.actions?.[eventName]) { + if (eventName === "Focus" || eventName === "Blur") { + elementData ||= { + focused: false + }; + } + this._setEventListener(element, elementData, baseName, eventName, getter); + if (eventName === "Focus" && !this.data.actions?.Blur) { + this._setEventListener(element, elementData, "blur", "Blur", null); + } else if (eventName === "Blur" && !this.data.actions?.Focus) { + this._setEventListener(element, elementData, "focus", "Focus", null); + } + } + } + } + _setBackgroundColor(element) { + const color = this.data.backgroundColor || null; + element.style.backgroundColor = color === null ? "transparent" : Util.makeHexColor(color[0], color[1], color[2]); + } + _setTextStyle(element) { + const TEXT_ALIGNMENT = ["left", "center", "right"]; + const { + fontColor + } = this.data.defaultAppearanceData; + const fontSize = this.data.defaultAppearanceData.fontSize || annotation_layer_DEFAULT_FONT_SIZE; + const style = element.style; + let computedFontSize; + const BORDER_SIZE = 2; + const roundToOneDecimal = x => Math.round(10 * x) / 10; + if (this.data.multiLine) { + const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE); + const numberOfLines = Math.round(height / (LINE_FACTOR * fontSize)) || 1; + const lineHeight = height / numberOfLines; + computedFontSize = Math.min(fontSize, roundToOneDecimal(lineHeight / LINE_FACTOR)); + } else { + const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE); + computedFontSize = Math.min(fontSize, roundToOneDecimal(height / LINE_FACTOR)); + } + style.fontSize = `calc(${computedFontSize}px * var(--scale-factor))`; + style.color = Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]); + if (this.data.textAlignment !== null) { + style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment]; + } + } + _setRequired(element, isRequired) { + if (isRequired) { + element.setAttribute("required", true); + } else { + element.removeAttribute("required"); + } + element.setAttribute("aria-required", isRequired); + } +} +class TextWidgetAnnotationElement extends WidgetAnnotationElement { + constructor(parameters) { + const isRenderable = parameters.renderForms || parameters.data.hasOwnCanvas || !parameters.data.hasAppearance && !!parameters.data.fieldValue; + super(parameters, { + isRenderable + }); + } + setPropertyOnSiblings(base, key, value, keyInStorage) { + const storage = this.annotationStorage; + for (const element of this._getElementsByName(base.name, base.id)) { + if (element.domElement) { + element.domElement[key] = value; + } + storage.setValue(element.id, { + [keyInStorage]: value + }); + } + } + render() { + const storage = this.annotationStorage; + const id = this.data.id; + this.container.classList.add("textWidgetAnnotation"); + let element = null; + if (this.renderForms) { + const storedData = storage.getValue(id, { + value: this.data.fieldValue + }); + let textContent = storedData.value || ""; + const maxLen = storage.getValue(id, { + charLimit: this.data.maxLen + }).charLimit; + if (maxLen && textContent.length > maxLen) { + textContent = textContent.slice(0, maxLen); + } + let fieldFormattedValues = storedData.formattedValue || this.data.textContent?.join("\n") || null; + if (fieldFormattedValues && this.data.comb) { + fieldFormattedValues = fieldFormattedValues.replaceAll(/\s+/g, ""); + } + const elementData = { + userValue: textContent, + formattedValue: fieldFormattedValues, + lastCommittedValue: null, + commitKey: 1, + focused: false + }; + if (this.data.multiLine) { + element = document.createElement("textarea"); + element.textContent = fieldFormattedValues ?? textContent; + if (this.data.doNotScroll) { + element.style.overflowY = "hidden"; + } + } else { + element = document.createElement("input"); + element.type = "text"; + element.setAttribute("value", fieldFormattedValues ?? textContent); + if (this.data.doNotScroll) { + element.style.overflowX = "hidden"; + } + } + if (this.data.hasOwnCanvas) { + element.hidden = true; + } + GetElementsByNameSet.add(element); + element.setAttribute("data-element-id", id); + element.disabled = this.data.readOnly; + element.name = this.data.fieldName; + element.tabIndex = DEFAULT_TAB_INDEX; + this._setRequired(element, this.data.required); + if (maxLen) { + element.maxLength = maxLen; + } + element.addEventListener("input", event => { + storage.setValue(id, { + value: event.target.value + }); + this.setPropertyOnSiblings(element, "value", event.target.value, "value"); + elementData.formattedValue = null; + }); + element.addEventListener("resetform", event => { + const defaultValue = this.data.defaultFieldValue ?? ""; + element.value = elementData.userValue = defaultValue; + elementData.formattedValue = null; + }); + let blurListener = event => { + const { + formattedValue + } = elementData; + if (formattedValue !== null && formattedValue !== undefined) { + event.target.value = formattedValue; + } + event.target.scrollLeft = 0; + }; + if (this.enableScripting && this.hasJSActions) { + element.addEventListener("focus", event => { + if (elementData.focused) { + return; + } + const { + target + } = event; + if (elementData.userValue) { + target.value = elementData.userValue; + } + elementData.lastCommittedValue = target.value; + elementData.commitKey = 1; + if (!this.data.actions?.Focus) { + elementData.focused = true; + } + }); + element.addEventListener("updatefromsandbox", jsEvent => { + this.showElementAndHideCanvas(jsEvent.target); + const actions = { + value(event) { + elementData.userValue = event.detail.value ?? ""; + storage.setValue(id, { + value: elementData.userValue.toString() + }); + event.target.value = elementData.userValue; + }, + formattedValue(event) { + const { + formattedValue + } = event.detail; + elementData.formattedValue = formattedValue; + if (formattedValue !== null && formattedValue !== undefined && event.target !== document.activeElement) { + event.target.value = formattedValue; + } + storage.setValue(id, { + formattedValue + }); + }, + selRange(event) { + event.target.setSelectionRange(...event.detail.selRange); + }, + charLimit: event => { + const { + charLimit + } = event.detail; + const { + target + } = event; + if (charLimit === 0) { + target.removeAttribute("maxLength"); + return; + } + target.setAttribute("maxLength", charLimit); + let value = elementData.userValue; + if (!value || value.length <= charLimit) { + return; + } + value = value.slice(0, charLimit); + target.value = elementData.userValue = value; + storage.setValue(id, { + value + }); + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id, + name: "Keystroke", + value, + willCommit: true, + commitKey: 1, + selStart: target.selectionStart, + selEnd: target.selectionEnd + } + }); + } + }; + this._dispatchEventFromSandbox(actions, jsEvent); + }); + element.addEventListener("keydown", event => { + elementData.commitKey = 1; + let commitKey = -1; + if (event.key === "Escape") { + commitKey = 0; + } else if (event.key === "Enter" && !this.data.multiLine) { + commitKey = 2; + } else if (event.key === "Tab") { + elementData.commitKey = 3; + } + if (commitKey === -1) { + return; + } + const { + value + } = event.target; + if (elementData.lastCommittedValue === value) { + return; + } + elementData.lastCommittedValue = value; + elementData.userValue = value; + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id, + name: "Keystroke", + value, + willCommit: true, + commitKey, + selStart: event.target.selectionStart, + selEnd: event.target.selectionEnd + } + }); + }); + const _blurListener = blurListener; + blurListener = null; + element.addEventListener("blur", event => { + if (!elementData.focused || !event.relatedTarget) { + return; + } + if (!this.data.actions?.Blur) { + elementData.focused = false; + } + const { + value + } = event.target; + elementData.userValue = value; + if (elementData.lastCommittedValue !== value) { + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id, + name: "Keystroke", + value, + willCommit: true, + commitKey: elementData.commitKey, + selStart: event.target.selectionStart, + selEnd: event.target.selectionEnd + } + }); + } + _blurListener(event); + }); + if (this.data.actions?.Keystroke) { + element.addEventListener("beforeinput", event => { + elementData.lastCommittedValue = null; + const { + data, + target + } = event; + const { + value, + selectionStart, + selectionEnd + } = target; + let selStart = selectionStart, + selEnd = selectionEnd; + switch (event.inputType) { + case "deleteWordBackward": + { + const match = value.substring(0, selectionStart).match(/\w*[^\w]*$/); + if (match) { + selStart -= match[0].length; + } + break; + } + case "deleteWordForward": + { + const match = value.substring(selectionStart).match(/^[^\w]*\w*/); + if (match) { + selEnd += match[0].length; + } + break; + } + case "deleteContentBackward": + if (selectionStart === selectionEnd) { + selStart -= 1; + } + break; + case "deleteContentForward": + if (selectionStart === selectionEnd) { + selEnd += 1; + } + break; + } + event.preventDefault(); + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id, + name: "Keystroke", + value, + change: data || "", + willCommit: false, + selStart, + selEnd + } + }); + }); + } + this._setEventListeners(element, elementData, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.value); + } + if (blurListener) { + element.addEventListener("blur", blurListener); + } + if (this.data.comb) { + const fieldWidth = this.data.rect[2] - this.data.rect[0]; + const combWidth = fieldWidth / maxLen; + element.classList.add("comb"); + element.style.letterSpacing = `calc(${combWidth}px * var(--scale-factor) - 1ch)`; + } + } else { + element = document.createElement("div"); + element.textContent = this.data.fieldValue; + element.style.verticalAlign = "middle"; + element.style.display = "table-cell"; + if (this.data.hasOwnCanvas) { + element.hidden = true; + } + } + this._setTextStyle(element); + this._setBackgroundColor(element); + this._setDefaultPropertiesFromJS(element); + this.container.append(element); + return this.container; + } +} +class SignatureWidgetAnnotationElement extends WidgetAnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: !!parameters.data.hasOwnCanvas + }); + } +} +class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: parameters.renderForms + }); + } + render() { + const storage = this.annotationStorage; + const data = this.data; + const id = data.id; + let value = storage.getValue(id, { + value: data.exportValue === data.fieldValue + }).value; + if (typeof value === "string") { + value = value !== "Off"; + storage.setValue(id, { + value + }); + } + this.container.classList.add("buttonWidgetAnnotation", "checkBox"); + const element = document.createElement("input"); + GetElementsByNameSet.add(element); + element.setAttribute("data-element-id", id); + element.disabled = data.readOnly; + this._setRequired(element, this.data.required); + element.type = "checkbox"; + element.name = data.fieldName; + if (value) { + element.setAttribute("checked", true); + } + element.setAttribute("exportValue", data.exportValue); + element.tabIndex = DEFAULT_TAB_INDEX; + element.addEventListener("change", event => { + const { + name, + checked + } = event.target; + for (const checkbox of this._getElementsByName(name, id)) { + const curChecked = checked && checkbox.exportValue === data.exportValue; + if (checkbox.domElement) { + checkbox.domElement.checked = curChecked; + } + storage.setValue(checkbox.id, { + value: curChecked + }); + } + storage.setValue(id, { + value: checked + }); + }); + element.addEventListener("resetform", event => { + const defaultValue = data.defaultFieldValue || "Off"; + event.target.checked = defaultValue === data.exportValue; + }); + if (this.enableScripting && this.hasJSActions) { + element.addEventListener("updatefromsandbox", jsEvent => { + const actions = { + value(event) { + event.target.checked = event.detail.value !== "Off"; + storage.setValue(id, { + value: event.target.checked + }); + } + }; + this._dispatchEventFromSandbox(actions, jsEvent); + }); + 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); + } + this._setBackgroundColor(element); + this._setDefaultPropertiesFromJS(element); + this.container.append(element); + return this.container; + } +} +class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: parameters.renderForms + }); + } + render() { + this.container.classList.add("buttonWidgetAnnotation", "radioButton"); + const storage = this.annotationStorage; + const data = this.data; + const id = data.id; + let value = storage.getValue(id, { + value: data.fieldValue === data.buttonValue + }).value; + if (typeof value === "string") { + value = value !== data.buttonValue; + storage.setValue(id, { + value + }); + } + if (value) { + for (const radio of this._getElementsByName(data.fieldName, id)) { + storage.setValue(radio.id, { + value: false + }); + } + } + const element = document.createElement("input"); + GetElementsByNameSet.add(element); + element.setAttribute("data-element-id", id); + element.disabled = data.readOnly; + this._setRequired(element, this.data.required); + element.type = "radio"; + element.name = data.fieldName; + if (value) { + element.setAttribute("checked", true); + } + element.tabIndex = DEFAULT_TAB_INDEX; + element.addEventListener("change", event => { + const { + name, + checked + } = event.target; + for (const radio of this._getElementsByName(name, id)) { + storage.setValue(radio.id, { + value: false + }); + } + storage.setValue(id, { + value: checked + }); + }); + element.addEventListener("resetform", event => { + const defaultValue = data.defaultFieldValue; + event.target.checked = defaultValue !== null && defaultValue !== undefined && defaultValue === data.buttonValue; + }); + if (this.enableScripting && this.hasJSActions) { + const pdfButtonValue = data.buttonValue; + element.addEventListener("updatefromsandbox", jsEvent => { + const actions = { + value: event => { + const checked = pdfButtonValue === event.detail.value; + for (const radio of this._getElementsByName(event.target.name)) { + const curChecked = checked && radio.id === id; + if (radio.domElement) { + radio.domElement.checked = curChecked; + } + storage.setValue(radio.id, { + value: curChecked + }); + } + } + }; + this._dispatchEventFromSandbox(actions, jsEvent); + }); + 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); + } + this._setBackgroundColor(element); + this._setDefaultPropertiesFromJS(element); + this.container.append(element); + return this.container; + } +} +class PushButtonWidgetAnnotationElement extends LinkAnnotationElement { + constructor(parameters) { + super(parameters, { + ignoreBorder: parameters.data.hasAppearance + }); + } + render() { + const container = super.render(); + container.classList.add("buttonWidgetAnnotation", "pushButton"); + const linkElement = container.lastChild; + if (this.enableScripting && this.hasJSActions && linkElement) { + this._setDefaultPropertiesFromJS(linkElement); + linkElement.addEventListener("updatefromsandbox", jsEvent => { + this._dispatchEventFromSandbox({}, jsEvent); + }); + } + return container; + } +} +class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: parameters.renderForms + }); + } + render() { + this.container.classList.add("choiceWidgetAnnotation"); + const storage = this.annotationStorage; + const id = this.data.id; + const storedData = storage.getValue(id, { + value: this.data.fieldValue + }); + const selectElement = document.createElement("select"); + GetElementsByNameSet.add(selectElement); + selectElement.setAttribute("data-element-id", id); + selectElement.disabled = this.data.readOnly; + this._setRequired(selectElement, this.data.required); + selectElement.name = this.data.fieldName; + selectElement.tabIndex = DEFAULT_TAB_INDEX; + let addAnEmptyEntry = this.data.combo && this.data.options.length > 0; + if (!this.data.combo) { + selectElement.size = this.data.options.length; + if (this.data.multiSelect) { + selectElement.multiple = true; + } + } + selectElement.addEventListener("resetform", event => { + const defaultValue = this.data.defaultFieldValue; + for (const option of selectElement.options) { + option.selected = option.value === defaultValue; + } + }); + for (const option of this.data.options) { + const optionElement = document.createElement("option"); + optionElement.textContent = option.displayValue; + optionElement.value = option.exportValue; + if (storedData.value.includes(option.exportValue)) { + optionElement.setAttribute("selected", true); + addAnEmptyEntry = false; + } + selectElement.append(optionElement); + } + let removeEmptyEntry = null; + if (addAnEmptyEntry) { + const noneOptionElement = document.createElement("option"); + noneOptionElement.value = " "; + noneOptionElement.setAttribute("hidden", true); + noneOptionElement.setAttribute("selected", true); + selectElement.prepend(noneOptionElement); + removeEmptyEntry = () => { + noneOptionElement.remove(); + selectElement.removeEventListener("input", removeEmptyEntry); + removeEmptyEntry = null; + }; + selectElement.addEventListener("input", removeEmptyEntry); + } + const getValue = isExport => { + const name = isExport ? "value" : "textContent"; + const { + options, + multiple + } = selectElement; + if (!multiple) { + return options.selectedIndex === -1 ? null : options[options.selectedIndex][name]; + } + return Array.prototype.filter.call(options, option => option.selected).map(option => option[name]); + }; + let selectedValues = getValue(false); + const getItems = event => { + const options = event.target.options; + return Array.prototype.map.call(options, option => ({ + displayValue: option.textContent, + exportValue: option.value + })); + }; + if (this.enableScripting && this.hasJSActions) { + selectElement.addEventListener("updatefromsandbox", jsEvent => { + const actions = { + value(event) { + removeEmptyEntry?.(); + const value = event.detail.value; + const values = new Set(Array.isArray(value) ? value : [value]); + for (const option of selectElement.options) { + option.selected = values.has(option.value); + } + storage.setValue(id, { + value: getValue(true) + }); + selectedValues = getValue(false); + }, + multipleSelection(event) { + selectElement.multiple = true; + }, + remove(event) { + const options = selectElement.options; + const index = event.detail.remove; + options[index].selected = false; + selectElement.remove(index); + if (options.length > 0) { + const i = Array.prototype.findIndex.call(options, option => option.selected); + if (i === -1) { + options[0].selected = true; + } + } + storage.setValue(id, { + value: getValue(true), + items: getItems(event) + }); + selectedValues = getValue(false); + }, + clear(event) { + while (selectElement.length !== 0) { + selectElement.remove(0); + } + storage.setValue(id, { + value: null, + items: [] + }); + selectedValues = getValue(false); + }, + insert(event) { + const { + index, + displayValue, + exportValue + } = event.detail.insert; + const selectChild = selectElement.children[index]; + const optionElement = document.createElement("option"); + optionElement.textContent = displayValue; + optionElement.value = exportValue; + if (selectChild) { + selectChild.before(optionElement); + } else { + selectElement.append(optionElement); + } + storage.setValue(id, { + value: getValue(true), + items: getItems(event) + }); + selectedValues = getValue(false); + }, + items(event) { + const { + items + } = event.detail; + while (selectElement.length !== 0) { + selectElement.remove(0); + } + for (const item of items) { + const { + displayValue, + exportValue + } = item; + const optionElement = document.createElement("option"); + optionElement.textContent = displayValue; + optionElement.value = exportValue; + selectElement.append(optionElement); + } + if (selectElement.options.length > 0) { + selectElement.options[0].selected = true; + } + storage.setValue(id, { + value: getValue(true), + items: getItems(event) + }); + selectedValues = getValue(false); + }, + indices(event) { + const indices = new Set(event.detail.indices); + for (const option of event.target.options) { + option.selected = indices.has(option.index); + } + storage.setValue(id, { + value: getValue(true) + }); + selectedValues = getValue(false); + }, + editable(event) { + event.target.disabled = !event.detail.editable; + } + }; + this._dispatchEventFromSandbox(actions, jsEvent); + }); + selectElement.addEventListener("input", event => { + const exportValue = getValue(true); + const change = getValue(false); + storage.setValue(id, { + value: exportValue + }); + event.preventDefault(); + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id, + name: "Keystroke", + value: selectedValues, + change, + changeEx: exportValue, + willCommit: false, + commitKey: 1, + keyDown: false + } + }); + }); + 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); + } else { + selectElement.addEventListener("input", function (event) { + storage.setValue(id, { + value: getValue(true) + }); + }); + } + if (this.data.combo) { + this._setTextStyle(selectElement); + } else {} + this._setBackgroundColor(selectElement); + this._setDefaultPropertiesFromJS(selectElement); + this.container.append(selectElement); + return this.container; + } +} +class PopupAnnotationElement extends AnnotationElement { + constructor(parameters) { + const { + data, + elements + } = parameters; + super(parameters, { + isRenderable: AnnotationElement._hasPopupData(data) + }); + this.elements = elements; + this.popup = null; + } + render() { + this.container.classList.add("popupAnnotation"); + const popup = this.popup = new PopupElement({ + container: this.container, + color: this.data.color, + titleObj: this.data.titleObj, + modificationDate: this.data.modificationDate, + contentsObj: this.data.contentsObj, + richText: this.data.richText, + rect: this.data.rect, + parentRect: this.data.parentRect || null, + parent: this.parent, + elements: this.elements, + open: this.data.open + }); + const elementIds = []; + for (const element of this.elements) { + element.popup = popup; + elementIds.push(element.data.id); + element.addHighlightArea(); + } + this.container.setAttribute("aria-controls", elementIds.map(id => `${AnnotationPrefix}${id}`).join(",")); + return this.container; + } +} +class PopupElement { + #boundKeyDown = this.#keyDown.bind(this); + #boundHide = this.#hide.bind(this); + #boundShow = this.#show.bind(this); + #boundToggle = this.#toggle.bind(this); + #color = null; + #container = null; + #contentsObj = null; + #dateObj = null; + #elements = null; + #parent = null; + #parentRect = null; + #pinned = false; + #popup = null; + #position = null; + #rect = null; + #richText = null; + #titleObj = null; + #updates = null; + #wasVisible = false; + constructor({ + container, + color, + elements, + titleObj, + modificationDate, + contentsObj, + richText, + parent, + rect, + parentRect, + open + }) { + this.#container = container; + this.#titleObj = titleObj; + this.#contentsObj = contentsObj; + this.#richText = richText; + this.#parent = parent; + this.#color = color; + this.#rect = rect; + this.#parentRect = parentRect; + this.#elements = elements; + this.#dateObj = PDFDateString.toDateObject(modificationDate); + this.trigger = elements.flatMap(e => e.getElementsToTriggerPopup()); + for (const element of this.trigger) { + element.addEventListener("click", this.#boundToggle); + element.addEventListener("mouseenter", this.#boundShow); + element.addEventListener("mouseleave", this.#boundHide); + element.classList.add("popupTriggerArea"); + } + for (const element of elements) { + element.container?.addEventListener("keydown", this.#boundKeyDown); + } + this.#container.hidden = true; + if (open) { + this.#toggle(); + } + } + render() { + if (this.#popup) { + return; + } + const popup = this.#popup = document.createElement("div"); + popup.className = "popup"; + if (this.#color) { + const baseColor = popup.style.outlineColor = Util.makeHexColor(...this.#color); + if (CSS.supports("background-color", "color-mix(in srgb, red 30%, white)")) { + popup.style.backgroundColor = `color-mix(in srgb, ${baseColor} 30%, white)`; + } else { + const BACKGROUND_ENLIGHT = 0.7; + popup.style.backgroundColor = Util.makeHexColor(...this.#color.map(c => Math.floor(BACKGROUND_ENLIGHT * (255 - c) + c))); + } + } + const header = document.createElement("span"); + header.className = "header"; + const title = document.createElement("h1"); + header.append(title); + ({ + dir: title.dir, + str: title.textContent + } = this.#titleObj); + popup.append(header); + if (this.#dateObj) { + const modificationDate = document.createElement("span"); + modificationDate.classList.add("popupDate"); + modificationDate.setAttribute("data-l10n-id", "pdfjs-annotation-date-time-string"); + modificationDate.setAttribute("data-l10n-args", JSON.stringify({ + dateObj: this.#dateObj.valueOf() + })); + header.append(modificationDate); + } + const html = this.#html; + if (html) { + XfaLayer.render({ + xfaHtml: html, + intent: "richText", + div: popup + }); + popup.lastChild.classList.add("richText", "popupContent"); + } else { + const contents = this._formatContents(this.#contentsObj); + popup.append(contents); + } + this.#container.append(popup); + } + get #html() { + const richText = this.#richText; + const contentsObj = this.#contentsObj; + if (richText?.str && (!contentsObj?.str || contentsObj.str === richText.str)) { + return this.#richText.html || null; + } + return null; + } + get #fontSize() { + return this.#html?.attributes?.style?.fontSize || 0; + } + get #fontColor() { + return this.#html?.attributes?.style?.color || null; + } + #makePopupContent(text) { + const popupLines = []; + const popupContent = { + str: text, + html: { + name: "div", + attributes: { + dir: "auto" + }, + children: [{ + name: "p", + children: popupLines + }] + } + }; + const lineAttributes = { + style: { + color: this.#fontColor, + fontSize: this.#fontSize ? `calc(${this.#fontSize}px * var(--scale-factor))` : "" + } + }; + for (const line of text.split("\n")) { + popupLines.push({ + name: "span", + value: line, + attributes: lineAttributes + }); + } + return popupContent; + } + _formatContents({ + str, + dir + }) { + const p = document.createElement("p"); + p.classList.add("popupContent"); + p.dir = dir; + const lines = str.split(/(?:\r\n?|\n)/); + for (let i = 0, ii = lines.length; i < ii; ++i) { + const line = lines[i]; + p.append(document.createTextNode(line)); + if (i < ii - 1) { + p.append(document.createElement("br")); + } + } + return p; + } + #keyDown(event) { + if (event.altKey || event.shiftKey || event.ctrlKey || event.metaKey) { + return; + } + if (event.key === "Enter" || event.key === "Escape" && this.#pinned) { + this.#toggle(); + } + } + updateEdited({ + rect, + popupContent + }) { + this.#updates ||= { + contentsObj: this.#contentsObj, + richText: this.#richText + }; + if (rect) { + this.#position = null; + } + if (popupContent) { + this.#richText = this.#makePopupContent(popupContent); + this.#contentsObj = null; + } + this.#popup?.remove(); + this.#popup = null; + } + resetEdited() { + if (!this.#updates) { + return; + } + ({ + contentsObj: this.#contentsObj, + richText: this.#richText + } = this.#updates); + this.#updates = null; + this.#popup?.remove(); + this.#popup = null; + this.#position = null; + } + #setPosition() { + if (this.#position !== null) { + return; + } + const { + page: { + view + }, + viewport: { + rawDims: { + pageWidth, + pageHeight, + pageX, + pageY + } + } + } = this.#parent; + let useParentRect = !!this.#parentRect; + let rect = useParentRect ? this.#parentRect : this.#rect; + for (const element of this.#elements) { + if (!rect || Util.intersect(element.data.rect, rect) !== null) { + rect = element.data.rect; + useParentRect = true; + break; + } + } + const normalizedRect = Util.normalizeRect([rect[0], view[3] - rect[1] + view[1], rect[2], view[3] - rect[3] + view[1]]); + const HORIZONTAL_SPACE_AFTER_ANNOTATION = 5; + const parentWidth = useParentRect ? rect[2] - rect[0] + HORIZONTAL_SPACE_AFTER_ANNOTATION : 0; + const popupLeft = normalizedRect[0] + parentWidth; + const popupTop = normalizedRect[1]; + this.#position = [100 * (popupLeft - pageX) / pageWidth, 100 * (popupTop - pageY) / pageHeight]; + const { + style + } = this.#container; + style.left = `${this.#position[0]}%`; + style.top = `${this.#position[1]}%`; + } + #toggle() { + this.#pinned = !this.#pinned; + if (this.#pinned) { + this.#show(); + this.#container.addEventListener("click", this.#boundToggle); + this.#container.addEventListener("keydown", this.#boundKeyDown); + } else { + this.#hide(); + this.#container.removeEventListener("click", this.#boundToggle); + this.#container.removeEventListener("keydown", this.#boundKeyDown); + } + } + #show() { + if (!this.#popup) { + this.render(); + } + if (!this.isVisible) { + this.#setPosition(); + this.#container.hidden = false; + this.#container.style.zIndex = parseInt(this.#container.style.zIndex) + 1000; + } else if (this.#pinned) { + this.#container.classList.add("focused"); + } + } + #hide() { + this.#container.classList.remove("focused"); + if (this.#pinned || !this.isVisible) { + return; + } + this.#container.hidden = true; + this.#container.style.zIndex = parseInt(this.#container.style.zIndex) - 1000; + } + forceHide() { + this.#wasVisible = this.isVisible; + if (!this.#wasVisible) { + return; + } + this.#container.hidden = true; + } + maybeShow() { + if (!this.#wasVisible) { + return; + } + if (!this.#popup) { + this.#show(); + } + this.#wasVisible = false; + this.#container.hidden = false; + } + get isVisible() { + return this.#container.hidden === false; + } +} +class FreeTextAnnotationElement extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + this.textContent = parameters.data.textContent; + this.textPosition = parameters.data.textPosition; + this.annotationEditorType = AnnotationEditorType.FREETEXT; + } + render() { + this.container.classList.add("freeTextAnnotation"); + if (this.textContent) { + const content = document.createElement("div"); + content.classList.add("annotationTextContent"); + content.setAttribute("role", "comment"); + for (const line of this.textContent) { + const lineSpan = document.createElement("span"); + lineSpan.textContent = line; + content.append(lineSpan); + } + this.container.append(content); + } + if (!this.data.popupRef && this.hasPopupData) { + this._createPopup(); + } + this._editOnDoubleClick(); + return this.container; + } +} +class LineAnnotationElement extends AnnotationElement { + #line = null; + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + } + render() { + this.container.classList.add("lineAnnotation"); + const data = this.data; + const { + width, + height + } = getRectDims(data.rect); + const svg = this.svgFactory.create(width, height, true); + const line = this.#line = this.svgFactory.createElement("svg:line"); + line.setAttribute("x1", data.rect[2] - data.lineCoordinates[0]); + line.setAttribute("y1", data.rect[3] - data.lineCoordinates[1]); + line.setAttribute("x2", data.rect[2] - data.lineCoordinates[2]); + line.setAttribute("y2", data.rect[3] - data.lineCoordinates[3]); + line.setAttribute("stroke-width", data.borderStyle.width || 1); + line.setAttribute("stroke", "transparent"); + line.setAttribute("fill", "transparent"); + svg.append(line); + this.container.append(svg); + if (!data.popupRef && this.hasPopupData) { + this._createPopup(); + } + return this.container; + } + getElementsToTriggerPopup() { + return this.#line; + } + addHighlightArea() { + this.container.classList.add("highlightArea"); + } +} +class SquareAnnotationElement extends AnnotationElement { + #square = null; + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + } + render() { + this.container.classList.add("squareAnnotation"); + const data = this.data; + const { + width, + height + } = getRectDims(data.rect); + const svg = this.svgFactory.create(width, height, true); + const borderWidth = data.borderStyle.width; + const square = this.#square = this.svgFactory.createElement("svg:rect"); + square.setAttribute("x", borderWidth / 2); + square.setAttribute("y", borderWidth / 2); + square.setAttribute("width", width - borderWidth); + square.setAttribute("height", height - borderWidth); + square.setAttribute("stroke-width", borderWidth || 1); + square.setAttribute("stroke", "transparent"); + square.setAttribute("fill", "transparent"); + svg.append(square); + this.container.append(svg); + if (!data.popupRef && this.hasPopupData) { + this._createPopup(); + } + return this.container; + } + getElementsToTriggerPopup() { + return this.#square; + } + addHighlightArea() { + this.container.classList.add("highlightArea"); + } +} +class CircleAnnotationElement extends AnnotationElement { + #circle = null; + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + } + render() { + this.container.classList.add("circleAnnotation"); + const data = this.data; + const { + width, + height + } = getRectDims(data.rect); + const svg = this.svgFactory.create(width, height, true); + const borderWidth = data.borderStyle.width; + const circle = this.#circle = this.svgFactory.createElement("svg:ellipse"); + circle.setAttribute("cx", width / 2); + circle.setAttribute("cy", height / 2); + circle.setAttribute("rx", width / 2 - borderWidth / 2); + circle.setAttribute("ry", height / 2 - borderWidth / 2); + circle.setAttribute("stroke-width", borderWidth || 1); + circle.setAttribute("stroke", "transparent"); + circle.setAttribute("fill", "transparent"); + svg.append(circle); + this.container.append(svg); + if (!data.popupRef && this.hasPopupData) { + this._createPopup(); + } + return this.container; + } + getElementsToTriggerPopup() { + return this.#circle; + } + addHighlightArea() { + this.container.classList.add("highlightArea"); + } +} +class PolylineAnnotationElement extends AnnotationElement { + #polyline = null; + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + this.containerClassName = "polylineAnnotation"; + this.svgElementName = "svg:polyline"; + } + render() { + this.container.classList.add(this.containerClassName); + const { + data: { + rect, + vertices, + borderStyle, + popupRef + } + } = this; + if (!vertices) { + return this.container; + } + const { + width, + height + } = getRectDims(rect); + const svg = this.svgFactory.create(width, height, true); + let points = []; + for (let i = 0, ii = vertices.length; i < ii; i += 2) { + const x = vertices[i] - rect[0]; + const y = rect[3] - vertices[i + 1]; + points.push(`${x},${y}`); + } + points = points.join(" "); + const polyline = this.#polyline = this.svgFactory.createElement(this.svgElementName); + polyline.setAttribute("points", points); + polyline.setAttribute("stroke-width", borderStyle.width || 1); + polyline.setAttribute("stroke", "transparent"); + polyline.setAttribute("fill", "transparent"); + svg.append(polyline); + this.container.append(svg); + if (!popupRef && this.hasPopupData) { + this._createPopup(); + } + return this.container; + } + getElementsToTriggerPopup() { + return this.#polyline; + } + addHighlightArea() { + this.container.classList.add("highlightArea"); + } +} +class PolygonAnnotationElement extends PolylineAnnotationElement { + constructor(parameters) { + super(parameters); + this.containerClassName = "polygonAnnotation"; + this.svgElementName = "svg:polygon"; + } +} +class CaretAnnotationElement extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + } + render() { + this.container.classList.add("caretAnnotation"); + if (!this.data.popupRef && this.hasPopupData) { + this._createPopup(); + } + return this.container; + } +} +class InkAnnotationElement extends AnnotationElement { + #polylines = []; + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + this.containerClassName = "inkAnnotation"; + this.svgElementName = "svg:polyline"; + this.annotationEditorType = AnnotationEditorType.INK; + } + render() { + this.container.classList.add(this.containerClassName); + const { + data: { + rect, + inkLists, + borderStyle, + popupRef + } + } = this; + const { + width, + height + } = getRectDims(rect); + const svg = this.svgFactory.create(width, height, true); + for (const inkList of inkLists) { + let points = []; + for (let i = 0, ii = inkList.length; i < ii; i += 2) { + const x = inkList[i] - rect[0]; + const y = rect[3] - inkList[i + 1]; + points.push(`${x},${y}`); + } + points = points.join(" "); + const polyline = this.svgFactory.createElement(this.svgElementName); + this.#polylines.push(polyline); + polyline.setAttribute("points", points); + polyline.setAttribute("stroke-width", borderStyle.width || 1); + polyline.setAttribute("stroke", "transparent"); + polyline.setAttribute("fill", "transparent"); + if (!popupRef && this.hasPopupData) { + this._createPopup(); + } + svg.append(polyline); + } + this.container.append(svg); + return this.container; + } + getElementsToTriggerPopup() { + return this.#polylines; + } + addHighlightArea() { + this.container.classList.add("highlightArea"); + } +} +class HighlightAnnotationElement extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true, + createQuadrilaterals: true + }); + } + render() { + if (!this.data.popupRef && this.hasPopupData) { + this._createPopup(); + } + this.container.classList.add("highlightAnnotation"); + return this.container; + } +} +class UnderlineAnnotationElement extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true, + createQuadrilaterals: true + }); + } + render() { + if (!this.data.popupRef && this.hasPopupData) { + this._createPopup(); + } + this.container.classList.add("underlineAnnotation"); + return this.container; + } +} +class SquigglyAnnotationElement extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true, + createQuadrilaterals: true + }); + } + render() { + if (!this.data.popupRef && this.hasPopupData) { + this._createPopup(); + } + this.container.classList.add("squigglyAnnotation"); + return this.container; + } +} +class StrikeOutAnnotationElement extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true, + createQuadrilaterals: true + }); + } + render() { + if (!this.data.popupRef && this.hasPopupData) { + this._createPopup(); + } + this.container.classList.add("strikeoutAnnotation"); + return this.container; + } +} +class StampAnnotationElement extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + } + render() { + this.container.classList.add("stampAnnotation"); + if (!this.data.popupRef && this.hasPopupData) { + this._createPopup(); + } + return this.container; + } +} +class FileAttachmentAnnotationElement extends AnnotationElement { + #trigger = null; + constructor(parameters) { + super(parameters, { + isRenderable: true + }); + const { + file + } = this.data; + this.filename = file.filename; + this.content = file.content; + this.linkService.eventBus?.dispatch("fileattachmentannotation", { + source: this, + ...file + }); + } + render() { + this.container.classList.add("fileAttachmentAnnotation"); + const { + container, + data + } = this; + let trigger; + if (data.hasAppearance || data.fillAlpha === 0) { + trigger = document.createElement("div"); + } else { + trigger = document.createElement("img"); + trigger.src = `${this.imageResourcesPath}annotation-${/paperclip/i.test(data.name) ? "paperclip" : "pushpin"}.svg`; + if (data.fillAlpha && data.fillAlpha < 1) { + trigger.style = `filter: opacity(${Math.round(data.fillAlpha * 100)}%);`; + } + } + trigger.addEventListener("dblclick", this.#download.bind(this)); + this.#trigger = trigger; + const { + isMac + } = util_FeatureTest.platform; + container.addEventListener("keydown", evt => { + if (evt.key === "Enter" && (isMac ? evt.metaKey : evt.ctrlKey)) { + this.#download(); + } + }); + if (!data.popupRef && this.hasPopupData) { + this._createPopup(); + } else { + trigger.classList.add("popupTriggerArea"); + } + container.append(trigger); + return container; + } + getElementsToTriggerPopup() { + return this.#trigger; + } + addHighlightArea() { + this.container.classList.add("highlightArea"); + } + #download() { + this.downloadManager?.openOrDownloadData(this.content, this.filename); + } +} +class AnnotationLayer { + #accessibilityManager = null; + #annotationCanvasMap = null; + #editableAnnotations = new Map(); + constructor({ + div, + accessibilityManager, + annotationCanvasMap, + annotationEditorUIManager, + page, + viewport + }) { + this.div = div; + this.#accessibilityManager = accessibilityManager; + this.#annotationCanvasMap = annotationCanvasMap; + this.page = page; + this.viewport = viewport; + this.zIndex = 0; + this._annotationEditorUIManager = annotationEditorUIManager; + } + hasEditableAnnotations() { + return this.#editableAnnotations.size > 0; + } + #appendElement(element, id) { + const contentElement = element.firstChild || element; + contentElement.id = `${AnnotationPrefix}${id}`; + this.div.append(element); + this.#accessibilityManager?.moveElementInDOM(this.div, element, contentElement, false); + } + async render(params) { + const { + annotations + } = params; + const layer = this.div; + setLayerDimensions(layer, this.viewport); + const popupToElements = new Map(); + const elementParams = { + data: null, + layer, + linkService: params.linkService, + downloadManager: params.downloadManager, + imageResourcesPath: params.imageResourcesPath || "", + renderForms: params.renderForms !== false, + svgFactory: new DOMSVGFactory(), + annotationStorage: params.annotationStorage || new AnnotationStorage(), + enableScripting: params.enableScripting === true, + hasJSActions: params.hasJSActions, + fieldObjects: params.fieldObjects, + parent: this, + elements: null + }; + for (const data of annotations) { + if (data.noHTML) { + continue; + } + const isPopupAnnotation = data.annotationType === AnnotationType.POPUP; + if (!isPopupAnnotation) { + const { + width, + height + } = getRectDims(data.rect); + if (width <= 0 || height <= 0) { + continue; + } + } else { + const elements = popupToElements.get(data.id); + if (!elements) { + continue; + } + elementParams.elements = elements; + } + elementParams.data = data; + const element = AnnotationElementFactory.create(elementParams); + if (!element.isRenderable) { + continue; + } + if (!isPopupAnnotation && data.popupRef) { + const elements = popupToElements.get(data.popupRef); + if (!elements) { + popupToElements.set(data.popupRef, [element]); + } else { + elements.push(element); + } + } + const rendered = element.render(); + if (data.hidden) { + rendered.style.visibility = "hidden"; + } + this.#appendElement(rendered, data.id); + if (element._isEditable) { + this.#editableAnnotations.set(element.data.id, element); + this._annotationEditorUIManager?.renderAnnotationElement(element); + } + } + this.#setAnnotationCanvasMap(); + } + update({ + viewport + }) { + const layer = this.div; + this.viewport = viewport; + setLayerDimensions(layer, { + rotation: viewport.rotation + }); + this.#setAnnotationCanvasMap(); + layer.hidden = false; + } + #setAnnotationCanvasMap() { + if (!this.#annotationCanvasMap) { + return; + } + const layer = this.div; + for (const [id, canvas] of this.#annotationCanvasMap) { + const element = layer.querySelector(`[data-annotation-id="${id}"]`); + if (!element) { + continue; + } + canvas.className = "annotationContent"; + const { + firstChild + } = element; + if (!firstChild) { + element.append(canvas); + } else if (firstChild.nodeName === "CANVAS") { + firstChild.replaceWith(canvas); + } else if (!firstChild.classList.contains("annotationContent")) { + firstChild.before(canvas); + } else { + firstChild.after(canvas); + } + } + this.#annotationCanvasMap.clear(); + } + getEditableAnnotations() { + return Array.from(this.#editableAnnotations.values()); + } + getEditableAnnotation(id) { + return this.#editableAnnotations.get(id); + } +} + +;// CONCATENATED MODULE: ./src/display/editor/freetext.js + + + + +const EOL_PATTERN = /\r\n?|\n/g; +class FreeTextEditor extends AnnotationEditor { + #color; + #content = ""; + #editorDivId = `${this.id}-editor`; + #editModeAC = null; + #fontSize; + #initialData = null; + static _freeTextDefaultContent = ""; + static _internalPadding = 0; + static _defaultColor = null; + static _defaultFontSize = 10; + static get _keyboardManager() { + const proto = FreeTextEditor.prototype; + const arrowChecker = self => self.isEmpty(); + const small = AnnotationEditorUIManager.TRANSLATE_SMALL; + const big = AnnotationEditorUIManager.TRANSLATE_BIG; + return shadow(this, "_keyboardManager", new KeyboardManager([[["ctrl+s", "mac+meta+s", "ctrl+p", "mac+meta+p"], proto.commitOrRemove, { + bubbles: true + }], [["ctrl+Enter", "mac+meta+Enter", "Escape", "mac+Escape"], proto.commitOrRemove], [["ArrowLeft", "mac+ArrowLeft"], proto._translateEmpty, { + args: [-small, 0], + checker: arrowChecker + }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], proto._translateEmpty, { + args: [-big, 0], + checker: arrowChecker + }], [["ArrowRight", "mac+ArrowRight"], proto._translateEmpty, { + args: [small, 0], + checker: arrowChecker + }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], proto._translateEmpty, { + args: [big, 0], + checker: arrowChecker + }], [["ArrowUp", "mac+ArrowUp"], proto._translateEmpty, { + args: [0, -small], + checker: arrowChecker + }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], proto._translateEmpty, { + args: [0, -big], + checker: arrowChecker + }], [["ArrowDown", "mac+ArrowDown"], proto._translateEmpty, { + args: [0, small], + checker: arrowChecker + }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], proto._translateEmpty, { + args: [0, big], + checker: arrowChecker + }]])); + } + static _type = "freetext"; + static _editorType = AnnotationEditorType.FREETEXT; + constructor(params) { + super({ + ...params, + name: "freeTextEditor" + }); + this.#color = params.color || FreeTextEditor._defaultColor || AnnotationEditor._defaultLineColor; + this.#fontSize = params.fontSize || FreeTextEditor._defaultFontSize; + } + static initialize(l10n, uiManager) { + AnnotationEditor.initialize(l10n, uiManager, { + strings: ["pdfjs-free-text-default-content"] + }); + const style = getComputedStyle(document.documentElement); + this._internalPadding = parseFloat(style.getPropertyValue("--freetext-padding")); + } + static updateDefaultParams(type, value) { + switch (type) { + case AnnotationEditorParamsType.FREETEXT_SIZE: + FreeTextEditor._defaultFontSize = value; + break; + case AnnotationEditorParamsType.FREETEXT_COLOR: + FreeTextEditor._defaultColor = value; + break; + } + } + updateParams(type, value) { + switch (type) { + case AnnotationEditorParamsType.FREETEXT_SIZE: + this.#updateFontSize(value); + break; + case AnnotationEditorParamsType.FREETEXT_COLOR: + this.#updateColor(value); + break; + } + } + static get defaultPropertiesToUpdate() { + return [[AnnotationEditorParamsType.FREETEXT_SIZE, FreeTextEditor._defaultFontSize], [AnnotationEditorParamsType.FREETEXT_COLOR, FreeTextEditor._defaultColor || AnnotationEditor._defaultLineColor]]; + } + get propertiesToUpdate() { + return [[AnnotationEditorParamsType.FREETEXT_SIZE, this.#fontSize], [AnnotationEditorParamsType.FREETEXT_COLOR, this.#color]]; + } + #updateFontSize(fontSize) { + const setFontsize = size => { + this.editorDiv.style.fontSize = `calc(${size}px * var(--scale-factor))`; + this.translate(0, -(size - this.#fontSize) * this.parentScale); + this.#fontSize = size; + this.#setEditorDimensions(); + }; + const savedFontsize = this.#fontSize; + this.addCommands({ + cmd: setFontsize.bind(this, fontSize), + undo: setFontsize.bind(this, savedFontsize), + post: this._uiManager.updateUI.bind(this._uiManager, this), + mustExec: true, + type: AnnotationEditorParamsType.FREETEXT_SIZE, + overwriteIfSameType: true, + keepUndo: true + }); + } + #updateColor(color) { + const setColor = col => { + this.#color = this.editorDiv.style.color = col; + }; + const savedColor = this.#color; + this.addCommands({ + cmd: setColor.bind(this, color), + undo: setColor.bind(this, savedColor), + post: this._uiManager.updateUI.bind(this._uiManager, this), + mustExec: true, + type: AnnotationEditorParamsType.FREETEXT_COLOR, + overwriteIfSameType: true, + keepUndo: true + }); + } + _translateEmpty(x, y) { + this._uiManager.translateSelectedEditors(x, y, true); + } + getInitialTranslation() { + const scale = this.parentScale; + return [-FreeTextEditor._internalPadding * scale, -(FreeTextEditor._internalPadding + this.#fontSize) * scale]; + } + rebuild() { + if (!this.parent) { + return; + } + super.rebuild(); + if (this.div === null) { + return; + } + if (!this.isAttachedToDOM) { + this.parent.add(this); + } + } + enableEditMode() { + if (this.isInEditMode()) { + return; + } + this.parent.setEditingState(false); + this.parent.updateToolbar(AnnotationEditorType.FREETEXT); + super.enableEditMode(); + this.overlayDiv.classList.remove("enabled"); + this.editorDiv.contentEditable = true; + this._isDraggable = false; + this.div.removeAttribute("aria-activedescendant"); + this.#editModeAC = new AbortController(); + const signal = this._uiManager.combinedSignal(this.#editModeAC); + this.editorDiv.addEventListener("keydown", this.editorDivKeydown.bind(this), { + signal + }); + this.editorDiv.addEventListener("focus", this.editorDivFocus.bind(this), { + signal + }); + this.editorDiv.addEventListener("blur", this.editorDivBlur.bind(this), { + signal + }); + this.editorDiv.addEventListener("input", this.editorDivInput.bind(this), { + signal + }); + this.editorDiv.addEventListener("paste", this.editorDivPaste.bind(this), { + signal + }); + } + disableEditMode() { + if (!this.isInEditMode()) { + return; + } + this.parent.setEditingState(true); + super.disableEditMode(); + this.overlayDiv.classList.add("enabled"); + this.editorDiv.contentEditable = false; + this.div.setAttribute("aria-activedescendant", this.#editorDivId); + this._isDraggable = true; + this.#editModeAC?.abort(); + this.#editModeAC = null; + this.div.focus({ + preventScroll: true + }); + this.isEditing = false; + this.parent.div.classList.add("freetextEditing"); + } + focusin(event) { + if (!this._focusEventsAllowed) { + return; + } + super.focusin(event); + if (event.target !== this.editorDiv) { + this.editorDiv.focus(); + } + } + onceAdded() { + if (this.width) { + return; + } + this.enableEditMode(); + this.editorDiv.focus(); + if (this._initialOptions?.isCentered) { + this.center(); + } + this._initialOptions = null; + } + isEmpty() { + return !this.editorDiv || this.editorDiv.innerText.trim() === ""; + } + remove() { + this.isEditing = false; + if (this.parent) { + this.parent.setEditingState(true); + this.parent.div.classList.add("freetextEditing"); + } + super.remove(); + } + #extractText() { + const buffer = []; + this.editorDiv.normalize(); + for (const child of this.editorDiv.childNodes) { + buffer.push(FreeTextEditor.#getNodeContent(child)); + } + return buffer.join("\n"); + } + #setEditorDimensions() { + const [parentWidth, parentHeight] = this.parentDimensions; + let rect; + if (this.isAttachedToDOM) { + rect = this.div.getBoundingClientRect(); + } else { + const { + currentLayer, + div + } = this; + const savedDisplay = div.style.display; + const savedVisibility = div.classList.contains("hidden"); + div.classList.remove("hidden"); + div.style.display = "hidden"; + currentLayer.div.append(this.div); + rect = div.getBoundingClientRect(); + div.remove(); + div.style.display = savedDisplay; + div.classList.toggle("hidden", savedVisibility); + } + if (this.rotation % 180 === this.parentRotation % 180) { + this.width = rect.width / parentWidth; + this.height = rect.height / parentHeight; + } else { + this.width = rect.height / parentWidth; + this.height = rect.width / parentHeight; + } + this.fixAndSetPosition(); + } + commit() { + if (!this.isInEditMode()) { + return; + } + super.commit(); + this.disableEditMode(); + const savedText = this.#content; + const newText = this.#content = this.#extractText().trimEnd(); + if (savedText === newText) { + return; + } + const setText = text => { + this.#content = text; + if (!text) { + this.remove(); + return; + } + this.#setContent(); + this._uiManager.rebuild(this); + this.#setEditorDimensions(); + }; + this.addCommands({ + cmd: () => { + setText(newText); + }, + undo: () => { + setText(savedText); + }, + mustExec: false + }); + this.#setEditorDimensions(); + } + shouldGetKeyboardEvents() { + return this.isInEditMode(); + } + enterInEditMode() { + this.enableEditMode(); + this.editorDiv.focus(); + } + dblclick(event) { + this.enterInEditMode(); + } + keydown(event) { + if (event.target === this.div && event.key === "Enter") { + this.enterInEditMode(); + event.preventDefault(); + } + } + editorDivKeydown(event) { + FreeTextEditor._keyboardManager.exec(this, event); + } + editorDivFocus(event) { + this.isEditing = true; + } + editorDivBlur(event) { + this.isEditing = false; + } + editorDivInput(event) { + this.parent.div.classList.toggle("freetextEditing", this.isEmpty()); + } + disableEditing() { + this.editorDiv.setAttribute("role", "comment"); + this.editorDiv.removeAttribute("aria-multiline"); + } + enableEditing() { + this.editorDiv.setAttribute("role", "textbox"); + this.editorDiv.setAttribute("aria-multiline", true); + } + render() { + if (this.div) { + return this.div; + } + let baseX, baseY; + if (this.width) { + baseX = this.x; + baseY = this.y; + } + super.render(); + this.editorDiv = document.createElement("div"); + this.editorDiv.className = "internal"; + this.editorDiv.setAttribute("id", this.#editorDivId); + this.editorDiv.setAttribute("data-l10n-id", "pdfjs-free-text"); + this.enableEditing(); + AnnotationEditor._l10nPromise.get("pdfjs-free-text-default-content").then(msg => this.editorDiv?.setAttribute("default-content", msg)); + this.editorDiv.contentEditable = true; + const { + style + } = this.editorDiv; + style.fontSize = `calc(${this.#fontSize}px * var(--scale-factor))`; + style.color = this.#color; + this.div.append(this.editorDiv); + this.overlayDiv = document.createElement("div"); + this.overlayDiv.classList.add("overlay", "enabled"); + this.div.append(this.overlayDiv); + bindEvents(this, this.div, ["dblclick", "keydown"]); + if (this.width) { + const [parentWidth, parentHeight] = this.parentDimensions; + if (this.annotationElementId) { + const { + position + } = this.#initialData; + let [tx, ty] = this.getInitialTranslation(); + [tx, ty] = this.pageTranslationToScreen(tx, ty); + const [pageWidth, pageHeight] = this.pageDimensions; + const [pageX, pageY] = this.pageTranslation; + let posX, posY; + switch (this.rotation) { + case 0: + posX = baseX + (position[0] - pageX) / pageWidth; + posY = baseY + this.height - (position[1] - pageY) / pageHeight; + break; + case 90: + posX = baseX + (position[0] - pageX) / pageWidth; + posY = baseY - (position[1] - pageY) / pageHeight; + [tx, ty] = [ty, -tx]; + break; + case 180: + posX = baseX - this.width + (position[0] - pageX) / pageWidth; + posY = baseY - (position[1] - pageY) / pageHeight; + [tx, ty] = [-tx, -ty]; + break; + case 270: + posX = baseX + (position[0] - pageX - this.height * pageHeight) / pageWidth; + posY = baseY + (position[1] - pageY - this.width * pageWidth) / pageHeight; + [tx, ty] = [-ty, tx]; + break; + } + this.setAt(posX * parentWidth, posY * parentHeight, tx, ty); + } else { + this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight); + } + this.#setContent(); + this._isDraggable = true; + this.editorDiv.contentEditable = false; + } else { + this._isDraggable = false; + this.editorDiv.contentEditable = true; + } + return this.div; + } + static #getNodeContent(node) { + return (node.nodeType === Node.TEXT_NODE ? node.nodeValue : node.innerText).replaceAll(EOL_PATTERN, ""); + } + editorDivPaste(event) { + const clipboardData = event.clipboardData || window.clipboardData; + const { + types + } = clipboardData; + if (types.length === 1 && types[0] === "text/plain") { + return; + } + event.preventDefault(); + const paste = FreeTextEditor.#deserializeContent(clipboardData.getData("text") || "").replaceAll(EOL_PATTERN, "\n"); + if (!paste) { + return; + } + const selection = window.getSelection(); + if (!selection.rangeCount) { + return; + } + this.editorDiv.normalize(); + selection.deleteFromDocument(); + const range = selection.getRangeAt(0); + if (!paste.includes("\n")) { + range.insertNode(document.createTextNode(paste)); + this.editorDiv.normalize(); + selection.collapseToStart(); + return; + } + const { + startContainer, + startOffset + } = range; + const bufferBefore = []; + const bufferAfter = []; + if (startContainer.nodeType === Node.TEXT_NODE) { + const parent = startContainer.parentElement; + bufferAfter.push(startContainer.nodeValue.slice(startOffset).replaceAll(EOL_PATTERN, "")); + if (parent !== this.editorDiv) { + let buffer = bufferBefore; + for (const child of this.editorDiv.childNodes) { + if (child === parent) { + buffer = bufferAfter; + continue; + } + buffer.push(FreeTextEditor.#getNodeContent(child)); + } + } + bufferBefore.push(startContainer.nodeValue.slice(0, startOffset).replaceAll(EOL_PATTERN, "")); + } else if (startContainer === this.editorDiv) { + let buffer = bufferBefore; + let i = 0; + for (const child of this.editorDiv.childNodes) { + if (i++ === startOffset) { + buffer = bufferAfter; + } + buffer.push(FreeTextEditor.#getNodeContent(child)); + } + } + this.#content = `${bufferBefore.join("\n")}${paste}${bufferAfter.join("\n")}`; + this.#setContent(); + const newRange = new Range(); + let beforeLength = bufferBefore.reduce((acc, line) => acc + line.length, 0); + for (const { + firstChild + } of this.editorDiv.childNodes) { + if (firstChild.nodeType === Node.TEXT_NODE) { + const length = firstChild.nodeValue.length; + if (beforeLength <= length) { + newRange.setStart(firstChild, beforeLength); + newRange.setEnd(firstChild, beforeLength); + break; + } + beforeLength -= length; + } + } + selection.removeAllRanges(); + selection.addRange(newRange); + } + #setContent() { + this.editorDiv.replaceChildren(); + if (!this.#content) { + return; + } + for (const line of this.#content.split("\n")) { + const div = document.createElement("div"); + div.append(line ? document.createTextNode(line) : document.createElement("br")); + this.editorDiv.append(div); + } + } + #serializeContent() { + return this.#content.replaceAll("\xa0", " "); + } + static #deserializeContent(content) { + return content.replaceAll(" ", "\xa0"); + } + get contentDiv() { + return this.editorDiv; + } + static deserialize(data, parent, uiManager) { + let initialData = null; + if (data instanceof FreeTextAnnotationElement) { + const { + data: { + defaultAppearanceData: { + fontSize, + fontColor + }, + rect, + rotation, + id + }, + textContent, + textPosition, + parent: { + page: { + pageNumber + } + } + } = data; + if (!textContent || textContent.length === 0) { + return null; + } + initialData = data = { + annotationType: AnnotationEditorType.FREETEXT, + color: Array.from(fontColor), + fontSize, + value: textContent.join("\n"), + position: textPosition, + pageIndex: pageNumber - 1, + rect: rect.slice(0), + rotation, + id, + deleted: false + }; + } + const editor = super.deserialize(data, parent, uiManager); + editor.#fontSize = data.fontSize; + editor.#color = Util.makeHexColor(...data.color); + editor.#content = FreeTextEditor.#deserializeContent(data.value); + editor.annotationElementId = data.id || null; + editor.#initialData = initialData; + return editor; + } + serialize(isForCopying = false) { + if (this.isEmpty()) { + return null; + } + if (this.deleted) { + return { + pageIndex: this.pageIndex, + id: this.annotationElementId, + deleted: true + }; + } + const padding = FreeTextEditor._internalPadding * this.parentScale; + const rect = this.getRect(padding, padding); + const color = AnnotationEditor._colorManager.convert(this.isAttachedToDOM ? getComputedStyle(this.editorDiv).color : this.#color); + const serialized = { + annotationType: AnnotationEditorType.FREETEXT, + color, + fontSize: this.#fontSize, + value: this.#serializeContent(), + pageIndex: this.pageIndex, + rect, + rotation: this.rotation, + structTreeParentId: this._structTreeParentId + }; + if (isForCopying) { + return serialized; + } + if (this.annotationElementId && !this.#hasElementChanged(serialized)) { + return null; + } + serialized.id = this.annotationElementId; + return serialized; + } + #hasElementChanged(serialized) { + const { + value, + fontSize, + color, + pageIndex + } = this.#initialData; + return this._hasBeenMoved || serialized.value !== value || serialized.fontSize !== fontSize || serialized.color.some((c, i) => c !== color[i]) || serialized.pageIndex !== pageIndex; + } + renderAnnotationElement(annotation) { + const content = super.renderAnnotationElement(annotation); + if (this.deleted) { + return content; + } + const { + style + } = content; + style.fontSize = `calc(${this.#fontSize}px * var(--scale-factor))`; + style.color = this.#color; + content.replaceChildren(); + for (const line of this.#content.split("\n")) { + const div = document.createElement("div"); + div.append(line ? document.createTextNode(line) : document.createElement("br")); + content.append(div); + } + const padding = FreeTextEditor._internalPadding * this.parentScale; + annotation.updateEdited({ + rect: this.getRect(padding, padding), + popupContent: this.#content + }); + return content; + } + resetAnnotationElement(annotation) { + super.resetAnnotationElement(annotation); + annotation.resetEdited(); + } +} + +;// CONCATENATED MODULE: ./src/display/editor/outliner.js + +class Outliner { + #box; + #verticalEdges = []; + #intervals = []; + constructor(boxes, borderWidth = 0, innerMargin = 0, isLTR = true) { + let minX = Infinity; + let maxX = -Infinity; + let minY = Infinity; + let maxY = -Infinity; + const NUMBER_OF_DIGITS = 4; + const EPSILON = 10 ** -NUMBER_OF_DIGITS; + for (const { + x, + y, + width, + height + } of boxes) { + const x1 = Math.floor((x - borderWidth) / EPSILON) * EPSILON; + const x2 = Math.ceil((x + width + borderWidth) / EPSILON) * EPSILON; + const y1 = Math.floor((y - borderWidth) / EPSILON) * EPSILON; + const y2 = Math.ceil((y + height + borderWidth) / EPSILON) * EPSILON; + const left = [x1, y1, y2, true]; + const right = [x2, y1, y2, false]; + this.#verticalEdges.push(left, right); + minX = Math.min(minX, x1); + maxX = Math.max(maxX, x2); + minY = Math.min(minY, y1); + maxY = Math.max(maxY, y2); + } + const bboxWidth = maxX - minX + 2 * innerMargin; + const bboxHeight = maxY - minY + 2 * innerMargin; + const shiftedMinX = minX - innerMargin; + const shiftedMinY = minY - innerMargin; + const lastEdge = this.#verticalEdges.at(isLTR ? -1 : -2); + const lastPoint = [lastEdge[0], lastEdge[2]]; + for (const edge of this.#verticalEdges) { + const [x, y1, y2] = edge; + edge[0] = (x - shiftedMinX) / bboxWidth; + edge[1] = (y1 - shiftedMinY) / bboxHeight; + edge[2] = (y2 - shiftedMinY) / bboxHeight; + } + this.#box = { + x: shiftedMinX, + y: shiftedMinY, + width: bboxWidth, + height: bboxHeight, + lastPoint + }; + } + getOutlines() { + this.#verticalEdges.sort((a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]); + const outlineVerticalEdges = []; + for (const edge of this.#verticalEdges) { + if (edge[3]) { + outlineVerticalEdges.push(...this.#breakEdge(edge)); + this.#insert(edge); + } else { + this.#remove(edge); + outlineVerticalEdges.push(...this.#breakEdge(edge)); + } + } + return this.#getOutlines(outlineVerticalEdges); + } + #getOutlines(outlineVerticalEdges) { + const edges = []; + const allEdges = new Set(); + for (const edge of outlineVerticalEdges) { + const [x, y1, y2] = edge; + edges.push([x, y1, edge], [x, y2, edge]); + } + edges.sort((a, b) => a[1] - b[1] || a[0] - b[0]); + for (let i = 0, ii = edges.length; i < ii; i += 2) { + const edge1 = edges[i][2]; + const edge2 = edges[i + 1][2]; + edge1.push(edge2); + edge2.push(edge1); + allEdges.add(edge1); + allEdges.add(edge2); + } + const outlines = []; + let outline; + while (allEdges.size > 0) { + const edge = allEdges.values().next().value; + let [x, y1, y2, edge1, edge2] = edge; + allEdges.delete(edge); + let lastPointX = x; + let lastPointY = y1; + outline = [x, y2]; + outlines.push(outline); + while (true) { + let e; + if (allEdges.has(edge1)) { + e = edge1; + } else if (allEdges.has(edge2)) { + e = edge2; + } else { + break; + } + allEdges.delete(e); + [x, y1, y2, edge1, edge2] = e; + if (lastPointX !== x) { + outline.push(lastPointX, lastPointY, x, lastPointY === y1 ? y1 : y2); + lastPointX = x; + } + lastPointY = lastPointY === y1 ? y2 : y1; + } + outline.push(lastPointX, lastPointY); + } + return new HighlightOutline(outlines, this.#box); + } + #binarySearch(y) { + const array = this.#intervals; + let start = 0; + let end = array.length - 1; + while (start <= end) { + const middle = start + end >> 1; + const y1 = array[middle][0]; + if (y1 === y) { + return middle; + } + if (y1 < y) { + start = middle + 1; + } else { + end = middle - 1; + } + } + return end + 1; + } + #insert([, y1, y2]) { + const index = this.#binarySearch(y1); + this.#intervals.splice(index, 0, [y1, y2]); + } + #remove([, y1, y2]) { + const index = this.#binarySearch(y1); + for (let i = index; i < this.#intervals.length; i++) { + const [start, end] = this.#intervals[i]; + if (start !== y1) { + break; + } + if (start === y1 && end === y2) { + this.#intervals.splice(i, 1); + return; + } + } + for (let i = index - 1; i >= 0; i--) { + const [start, end] = this.#intervals[i]; + if (start !== y1) { + break; + } + if (start === y1 && end === y2) { + this.#intervals.splice(i, 1); + return; + } + } + } + #breakEdge(edge) { + const [x, y1, y2] = edge; + const results = [[x, y1, y2]]; + const index = this.#binarySearch(y2); + for (let i = 0; i < index; i++) { + const [start, end] = this.#intervals[i]; + for (let j = 0, jj = results.length; j < jj; j++) { + const [, y3, y4] = results[j]; + if (end <= y3 || y4 <= start) { + continue; + } + if (y3 >= start) { + if (y4 > end) { + results[j][1] = end; + } else { + if (jj === 1) { + return []; + } + results.splice(j, 1); + j--; + jj--; + } + continue; + } + results[j][2] = start; + if (y4 > end) { + results.push([x, end, y4]); + } + } + } + return results; + } +} +class Outline { + toSVGPath() { + throw new Error("Abstract method `toSVGPath` must be implemented."); + } + get box() { + throw new Error("Abstract getter `box` must be implemented."); + } + serialize(_bbox, _rotation) { + throw new Error("Abstract method `serialize` must be implemented."); + } + get free() { + return this instanceof FreeHighlightOutline; + } +} +class HighlightOutline extends Outline { + #box; + #outlines; + constructor(outlines, box) { + super(); + this.#outlines = outlines; + this.#box = box; + } + toSVGPath() { + const buffer = []; + for (const polygon of this.#outlines) { + let [prevX, prevY] = polygon; + buffer.push(`M${prevX} ${prevY}`); + for (let i = 2; i < polygon.length; i += 2) { + const x = polygon[i]; + const y = polygon[i + 1]; + if (x === prevX) { + buffer.push(`V${y}`); + prevY = y; + } else if (y === prevY) { + buffer.push(`H${x}`); + prevX = x; + } + } + buffer.push("Z"); + } + return buffer.join(" "); + } + serialize([blX, blY, trX, trY], _rotation) { + const outlines = []; + const width = trX - blX; + const height = trY - blY; + for (const outline of this.#outlines) { + const points = new Array(outline.length); + for (let i = 0; i < outline.length; i += 2) { + points[i] = blX + outline[i] * width; + points[i + 1] = trY - outline[i + 1] * height; + } + outlines.push(points); + } + return outlines; + } + get box() { + return this.#box; + } +} +class FreeOutliner { + #box; + #bottom = []; + #innerMargin; + #isLTR; + #top = []; + #last = new Float64Array(18); + #lastX; + #lastY; + #min; + #min_dist; + #scaleFactor; + #thickness; + #points = []; + static #MIN_DIST = 8; + static #MIN_DIFF = 2; + static #MIN = FreeOutliner.#MIN_DIST + FreeOutliner.#MIN_DIFF; + constructor({ + x, + y + }, box, scaleFactor, thickness, isLTR, innerMargin = 0) { + this.#box = box; + this.#thickness = thickness * scaleFactor; + this.#isLTR = isLTR; + this.#last.set([NaN, NaN, NaN, NaN, x, y], 6); + this.#innerMargin = innerMargin; + this.#min_dist = FreeOutliner.#MIN_DIST * scaleFactor; + this.#min = FreeOutliner.#MIN * scaleFactor; + this.#scaleFactor = scaleFactor; + this.#points.push(x, y); + } + get free() { + return true; + } + isEmpty() { + return isNaN(this.#last[8]); + } + #getLastCoords() { + const lastTop = this.#last.subarray(4, 6); + const lastBottom = this.#last.subarray(16, 18); + const [x, y, width, height] = this.#box; + 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]; + } + add({ + x, + y + }) { + this.#lastX = x; + this.#lastY = y; + const [layerX, layerY, layerWidth, layerHeight] = this.#box; + let [x1, y1, x2, y2] = this.#last.subarray(8, 12); + const diffX = x - x2; + const diffY = y - y2; + const d = Math.hypot(diffX, diffY); + if (d < this.#min) { + return false; + } + const diffD = d - this.#min_dist; + const K = diffD / d; + const shiftX = K * diffX; + const shiftY = K * diffY; + let x0 = x1; + let y0 = y1; + x1 = x2; + y1 = y2; + x2 += shiftX; + y2 += shiftY; + this.#points?.push(x, y); + const nX = -shiftY / diffD; + const nY = shiftX / diffD; + const thX = nX * this.#thickness; + const thY = nY * this.#thickness; + this.#last.set(this.#last.subarray(2, 8), 0); + this.#last.set([x2 + thX, y2 + thY], 4); + this.#last.set(this.#last.subarray(14, 18), 12); + this.#last.set([x2 - thX, y2 - thY], 16); + if (isNaN(this.#last[6])) { + if (this.#top.length === 0) { + this.#last.set([x1 + thX, y1 + thY], 2); + this.#top.push(NaN, NaN, NaN, NaN, (x1 + thX - layerX) / layerWidth, (y1 + thY - layerY) / layerHeight); + this.#last.set([x1 - thX, y1 - thY], 14); + this.#bottom.push(NaN, NaN, NaN, NaN, (x1 - thX - layerX) / layerWidth, (y1 - thY - layerY) / layerHeight); + } + this.#last.set([x0, y0, x1, y1, x2, y2], 6); + return !this.isEmpty(); + } + this.#last.set([x0, y0, x1, y1, x2, y2], 6); + const angle = Math.abs(Math.atan2(y0 - y1, x0 - x1) - Math.atan2(shiftY, shiftX)); + if (angle < Math.PI / 2) { + [x1, y1, x2, y2] = this.#last.subarray(2, 6); + this.#top.push(NaN, NaN, NaN, NaN, ((x1 + x2) / 2 - layerX) / layerWidth, ((y1 + y2) / 2 - layerY) / layerHeight); + [x1, y1, x0, y0] = this.#last.subarray(14, 18); + this.#bottom.push(NaN, NaN, NaN, NaN, ((x0 + x1) / 2 - layerX) / layerWidth, ((y0 + y1) / 2 - layerY) / layerHeight); + return true; + } + [x0, y0, x1, y1, x2, y2] = this.#last.subarray(0, 6); + 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); + [x2, y2, x1, y1, x0, y0] = this.#last.subarray(12, 18); + 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); + return true; + } + toSVGPath() { + if (this.isEmpty()) { + return ""; + } + const top = this.#top; + const bottom = this.#bottom; + const lastTop = this.#last.subarray(4, 6); + const lastBottom = this.#last.subarray(16, 18); + const [x, y, width, height] = this.#box; + const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords(); + if (isNaN(this.#last[6]) && !this.isEmpty()) { + 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`; + } + const buffer = []; + buffer.push(`M${top[4]} ${top[5]}`); + for (let i = 6; i < top.length; i += 6) { + if (isNaN(top[i])) { + buffer.push(`L${top[i + 4]} ${top[i + 5]}`); + } else { + buffer.push(`C${top[i]} ${top[i + 1]} ${top[i + 2]} ${top[i + 3]} ${top[i + 4]} ${top[i + 5]}`); + } + } + 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}`); + for (let i = bottom.length - 6; i >= 6; i -= 6) { + if (isNaN(bottom[i])) { + buffer.push(`L${bottom[i + 4]} ${bottom[i + 5]}`); + } else { + buffer.push(`C${bottom[i]} ${bottom[i + 1]} ${bottom[i + 2]} ${bottom[i + 3]} ${bottom[i + 4]} ${bottom[i + 5]}`); + } + } + buffer.push(`L${bottom[4]} ${bottom[5]} Z`); + return buffer.join(" "); + } + getOutlines() { + const top = this.#top; + const bottom = this.#bottom; + const last = this.#last; + const lastTop = last.subarray(4, 6); + const lastBottom = last.subarray(16, 18); + const [layerX, layerY, layerWidth, layerHeight] = this.#box; + const points = new Float64Array((this.#points?.length ?? 0) + 2); + for (let i = 0, ii = points.length - 2; i < ii; i += 2) { + points[i] = (this.#points[i] - layerX) / layerWidth; + points[i + 1] = (this.#points[i + 1] - layerY) / layerHeight; + } + points[points.length - 2] = (this.#lastX - layerX) / layerWidth; + points[points.length - 1] = (this.#lastY - layerY) / layerHeight; + const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords(); + if (isNaN(last[6]) && !this.isEmpty()) { + const outline = new Float64Array(36); + 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); + return new FreeHighlightOutline(outline, points, this.#box, this.#scaleFactor, this.#innerMargin, this.#isLTR); + } + const outline = new Float64Array(this.#top.length + 24 + this.#bottom.length); + let N = top.length; + for (let i = 0; i < N; i += 2) { + if (isNaN(top[i])) { + outline[i] = outline[i + 1] = NaN; + continue; + } + outline[i] = top[i]; + outline[i + 1] = top[i + 1]; + } + 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); + N += 24; + for (let i = bottom.length - 6; i >= 6; i -= 6) { + for (let j = 0; j < 6; j += 2) { + if (isNaN(bottom[i + j])) { + outline[N] = outline[N + 1] = NaN; + N += 2; + continue; + } + outline[N] = bottom[i + j]; + outline[N + 1] = bottom[i + j + 1]; + N += 2; + } + } + outline.set([NaN, NaN, NaN, NaN, bottom[4], bottom[5]], N); + return new FreeHighlightOutline(outline, points, this.#box, this.#scaleFactor, this.#innerMargin, this.#isLTR); + } +} +class FreeHighlightOutline extends Outline { + #box; + #bbox = null; + #innerMargin; + #isLTR; + #points; + #scaleFactor; + #outline; + constructor(outline, points, box, scaleFactor, innerMargin, isLTR) { + super(); + this.#outline = outline; + this.#points = points; + this.#box = box; + this.#scaleFactor = scaleFactor; + this.#innerMargin = innerMargin; + this.#isLTR = isLTR; + this.#computeMinMax(isLTR); + const { + x, + y, + width, + height + } = this.#bbox; + for (let i = 0, ii = outline.length; i < ii; i += 2) { + outline[i] = (outline[i] - x) / width; + outline[i + 1] = (outline[i + 1] - y) / height; + } + for (let i = 0, ii = points.length; i < ii; i += 2) { + points[i] = (points[i] - x) / width; + points[i + 1] = (points[i + 1] - y) / height; + } + } + toSVGPath() { + const buffer = [`M${this.#outline[4]} ${this.#outline[5]}`]; + for (let i = 6, ii = this.#outline.length; i < ii; i += 6) { + if (isNaN(this.#outline[i])) { + buffer.push(`L${this.#outline[i + 4]} ${this.#outline[i + 5]}`); + continue; + } + 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]}`); + } + buffer.push("Z"); + return buffer.join(" "); + } + serialize([blX, blY, trX, trY], rotation) { + const width = trX - blX; + const height = trY - blY; + let outline; + let points; + switch (rotation) { + case 0: + outline = this.#rescale(this.#outline, blX, trY, width, -height); + points = this.#rescale(this.#points, blX, trY, width, -height); + break; + case 90: + outline = this.#rescaleAndSwap(this.#outline, blX, blY, width, height); + points = this.#rescaleAndSwap(this.#points, blX, blY, width, height); + break; + case 180: + outline = this.#rescale(this.#outline, trX, blY, -width, height); + points = this.#rescale(this.#points, trX, blY, -width, height); + break; + case 270: + outline = this.#rescaleAndSwap(this.#outline, trX, trY, -width, -height); + points = this.#rescaleAndSwap(this.#points, trX, trY, -width, -height); + break; + } + return { + outline: Array.from(outline), + points: [Array.from(points)] + }; + } + #rescale(src, tx, ty, sx, sy) { + const dest = new Float64Array(src.length); + for (let i = 0, ii = src.length; i < ii; i += 2) { + dest[i] = tx + src[i] * sx; + dest[i + 1] = ty + src[i + 1] * sy; + } + return dest; + } + #rescaleAndSwap(src, tx, ty, sx, sy) { + const dest = new Float64Array(src.length); + for (let i = 0, ii = src.length; i < ii; i += 2) { + dest[i] = tx + src[i + 1] * sx; + dest[i + 1] = ty + src[i] * sy; + } + return dest; + } + #computeMinMax(isLTR) { + const outline = this.#outline; + let lastX = outline[4]; + let lastY = outline[5]; + let minX = lastX; + let minY = lastY; + let maxX = lastX; + let maxY = lastY; + let lastPointX = lastX; + let lastPointY = lastY; + const ltrCallback = isLTR ? Math.max : Math.min; + for (let i = 6, ii = outline.length; i < ii; i += 6) { + if (isNaN(outline[i])) { + minX = Math.min(minX, outline[i + 4]); + minY = Math.min(minY, outline[i + 5]); + maxX = Math.max(maxX, outline[i + 4]); + maxY = Math.max(maxY, outline[i + 5]); + if (lastPointY < outline[i + 5]) { + lastPointX = outline[i + 4]; + lastPointY = outline[i + 5]; + } else if (lastPointY === outline[i + 5]) { + lastPointX = ltrCallback(lastPointX, outline[i + 4]); + } + } else { + const bbox = Util.bezierBoundingBox(lastX, lastY, ...outline.slice(i, i + 6)); + minX = Math.min(minX, bbox[0]); + minY = Math.min(minY, bbox[1]); + maxX = Math.max(maxX, bbox[2]); + maxY = Math.max(maxY, bbox[3]); + if (lastPointY < bbox[3]) { + lastPointX = bbox[2]; + lastPointY = bbox[3]; + } else if (lastPointY === bbox[3]) { + lastPointX = ltrCallback(lastPointX, bbox[2]); + } + } + lastX = outline[i + 4]; + lastY = outline[i + 5]; + } + const x = minX - this.#innerMargin, + y = minY - this.#innerMargin, + width = maxX - minX + 2 * this.#innerMargin, + height = maxY - minY + 2 * this.#innerMargin; + this.#bbox = { + x, + y, + width, + height, + lastPoint: [lastPointX, lastPointY] + }; + } + get box() { + return this.#bbox; + } + getNewOutline(thickness, innerMargin) { + const { + x, + y, + width, + height + } = this.#bbox; + const [layerX, layerY, layerWidth, layerHeight] = this.#box; + const sx = width * layerWidth; + const sy = height * layerHeight; + const tx = x * layerWidth + layerX; + const ty = y * layerHeight + layerY; + const outliner = new FreeOutliner({ + x: this.#points[0] * sx + tx, + y: this.#points[1] * sy + ty + }, this.#box, this.#scaleFactor, thickness, this.#isLTR, innerMargin ?? this.#innerMargin); + for (let i = 2; i < this.#points.length; i += 2) { + outliner.add({ + x: this.#points[i] * sx + tx, + y: this.#points[i + 1] * sy + ty + }); + } + return outliner.getOutlines(); + } +} + +;// CONCATENATED MODULE: ./src/display/editor/color_picker.js + + + +class ColorPicker { + #boundKeyDown = this.#keyDown.bind(this); + #boundPointerDown = this.#pointerDown.bind(this); + #button = null; + #buttonSwatch = null; + #defaultColor; + #dropdown = null; + #dropdownWasFromKeyboard = false; + #isMainColorPicker = false; + #editor = null; + #eventBus; + #uiManager = null; + #type; + static get _keyboardManager() { + 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]])); + } + constructor({ + editor = null, + uiManager = null + }) { + if (editor) { + this.#isMainColorPicker = false; + this.#type = AnnotationEditorParamsType.HIGHLIGHT_COLOR; + this.#editor = editor; + } else { + this.#isMainColorPicker = true; + this.#type = AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR; + } + this.#uiManager = editor?._uiManager || uiManager; + this.#eventBus = this.#uiManager._eventBus; + this.#defaultColor = editor?.color || this.#uiManager?.highlightColors.values().next().value || "#FFFF98"; + } + renderButton() { + const button = this.#button = document.createElement("button"); + button.className = "colorPicker"; + button.tabIndex = "0"; + button.setAttribute("data-l10n-id", "pdfjs-editor-colorpicker-button"); + button.setAttribute("aria-haspopup", true); + const signal = this.#uiManager._signal; + button.addEventListener("click", this.#openDropdown.bind(this), { + signal + }); + button.addEventListener("keydown", this.#boundKeyDown, { + signal + }); + const swatch = this.#buttonSwatch = document.createElement("span"); + swatch.className = "swatch"; + swatch.setAttribute("aria-hidden", true); + swatch.style.backgroundColor = this.#defaultColor; + button.append(swatch); + return button; + } + renderMainDropdown() { + const dropdown = this.#dropdown = this.#getDropdownRoot(); + dropdown.setAttribute("aria-orientation", "horizontal"); + dropdown.setAttribute("aria-labelledby", "highlightColorPickerLabel"); + return dropdown; + } + #getDropdownRoot() { + const div = document.createElement("div"); + const signal = this.#uiManager._signal; + div.addEventListener("contextmenu", noContextMenu, { + signal + }); + div.className = "dropdown"; + div.role = "listbox"; + div.setAttribute("aria-multiselectable", false); + div.setAttribute("aria-orientation", "vertical"); + div.setAttribute("data-l10n-id", "pdfjs-editor-colorpicker-dropdown"); + for (const [name, color] of this.#uiManager.highlightColors) { + const button = document.createElement("button"); + button.tabIndex = "0"; + button.role = "option"; + button.setAttribute("data-color", color); + button.title = name; + button.setAttribute("data-l10n-id", `pdfjs-editor-colorpicker-${name}`); + const swatch = document.createElement("span"); + button.append(swatch); + swatch.className = "swatch"; + swatch.style.backgroundColor = color; + button.setAttribute("aria-selected", color === this.#defaultColor); + button.addEventListener("click", this.#colorSelect.bind(this, color), { + signal + }); + div.append(button); + } + div.addEventListener("keydown", this.#boundKeyDown, { + signal + }); + return div; + } + #colorSelect(color, event) { + event.stopPropagation(); + this.#eventBus.dispatch("switchannotationeditorparams", { + source: this, + type: this.#type, + value: color + }); + } + _colorSelectFromKeyboard(event) { + if (event.target === this.#button) { + this.#openDropdown(event); + return; + } + const color = event.target.getAttribute("data-color"); + if (!color) { + return; + } + this.#colorSelect(color, event); + } + _moveToNext(event) { + if (!this.#isDropdownVisible) { + this.#openDropdown(event); + return; + } + if (event.target === this.#button) { + this.#dropdown.firstChild?.focus(); + return; + } + event.target.nextSibling?.focus(); + } + _moveToPrevious(event) { + if (event.target === this.#dropdown?.firstChild || event.target === this.#button) { + if (this.#isDropdownVisible) { + this._hideDropdownFromKeyboard(); + } + return; + } + if (!this.#isDropdownVisible) { + this.#openDropdown(event); + } + event.target.previousSibling?.focus(); + } + _moveToBeginning(event) { + if (!this.#isDropdownVisible) { + this.#openDropdown(event); + return; + } + this.#dropdown.firstChild?.focus(); + } + _moveToEnd(event) { + if (!this.#isDropdownVisible) { + this.#openDropdown(event); + return; + } + this.#dropdown.lastChild?.focus(); + } + #keyDown(event) { + ColorPicker._keyboardManager.exec(this, event); + } + #openDropdown(event) { + if (this.#isDropdownVisible) { + this.hideDropdown(); + return; + } + this.#dropdownWasFromKeyboard = event.detail === 0; + window.addEventListener("pointerdown", this.#boundPointerDown, { + signal: this.#uiManager._signal + }); + if (this.#dropdown) { + this.#dropdown.classList.remove("hidden"); + return; + } + const root = this.#dropdown = this.#getDropdownRoot(); + this.#button.append(root); + } + #pointerDown(event) { + if (this.#dropdown?.contains(event.target)) { + return; + } + this.hideDropdown(); + } + hideDropdown() { + this.#dropdown?.classList.add("hidden"); + window.removeEventListener("pointerdown", this.#boundPointerDown); + } + get #isDropdownVisible() { + return this.#dropdown && !this.#dropdown.classList.contains("hidden"); + } + _hideDropdownFromKeyboard() { + if (this.#isMainColorPicker) { + return; + } + if (!this.#isDropdownVisible) { + this.#editor?.unselect(); + return; + } + this.hideDropdown(); + this.#button.focus({ + preventScroll: true, + focusVisible: this.#dropdownWasFromKeyboard + }); + } + updateColor(color) { + if (this.#buttonSwatch) { + this.#buttonSwatch.style.backgroundColor = color; + } + if (!this.#dropdown) { + return; + } + const i = this.#uiManager.highlightColors.values(); + for (const child of this.#dropdown.children) { + child.setAttribute("aria-selected", i.next().value === color); + } + } + destroy() { + this.#button?.remove(); + this.#button = null; + this.#buttonSwatch = null; + this.#dropdown?.remove(); + this.#dropdown = null; + } +} + +;// CONCATENATED MODULE: ./src/display/editor/highlight.js + + + + + + +class HighlightEditor extends AnnotationEditor { + #anchorNode = null; + #anchorOffset = 0; + #boxes; + #clipPathId = null; + #colorPicker = null; + #focusOutlines = null; + #focusNode = null; + #focusOffset = 0; + #highlightDiv = null; + #highlightOutlines = null; + #id = null; + #isFreeHighlight = false; + #lastPoint = null; + #opacity; + #outlineId = null; + #text = ""; + #thickness; + #methodOfCreation = ""; + static _defaultColor = null; + static _defaultOpacity = 1; + static _defaultThickness = 12; + static _l10nPromise; + static _type = "highlight"; + static _editorType = AnnotationEditorType.HIGHLIGHT; + static _freeHighlightId = -1; + static _freeHighlight = null; + static _freeHighlightClipId = ""; + static get _keyboardManager() { + const proto = HighlightEditor.prototype; + return shadow(this, "_keyboardManager", new KeyboardManager([[["ArrowLeft", "mac+ArrowLeft"], proto._moveCaret, { + args: [0] + }], [["ArrowRight", "mac+ArrowRight"], proto._moveCaret, { + args: [1] + }], [["ArrowUp", "mac+ArrowUp"], proto._moveCaret, { + args: [2] + }], [["ArrowDown", "mac+ArrowDown"], proto._moveCaret, { + args: [3] + }]])); + } + constructor(params) { + super({ + ...params, + name: "highlightEditor" + }); + this.color = params.color || HighlightEditor._defaultColor; + this.#thickness = params.thickness || HighlightEditor._defaultThickness; + this.#opacity = params.opacity || HighlightEditor._defaultOpacity; + this.#boxes = params.boxes || null; + this.#methodOfCreation = params.methodOfCreation || ""; + this.#text = params.text || ""; + this._isDraggable = false; + if (params.highlightId > -1) { + this.#isFreeHighlight = true; + this.#createFreeOutlines(params); + this.#addToDrawLayer(); + } else { + this.#anchorNode = params.anchorNode; + this.#anchorOffset = params.anchorOffset; + this.#focusNode = params.focusNode; + this.#focusOffset = params.focusOffset; + this.#createOutlines(); + this.#addToDrawLayer(); + this.rotate(this.rotation); + } + } + get telemetryInitialData() { + return { + action: "added", + type: this.#isFreeHighlight ? "free_highlight" : "highlight", + color: this._uiManager.highlightColorNames.get(this.color), + thickness: this.#thickness, + methodOfCreation: this.#methodOfCreation + }; + } + get telemetryFinalData() { + return { + type: "highlight", + color: this._uiManager.highlightColorNames.get(this.color) + }; + } + static computeTelemetryFinalData(data) { + return { + numberOfColors: data.get("color").size + }; + } + #createOutlines() { + const outliner = new Outliner(this.#boxes, 0.001); + this.#highlightOutlines = outliner.getOutlines(); + ({ + x: this.x, + y: this.y, + width: this.width, + height: this.height + } = this.#highlightOutlines.box); + const outlinerForOutline = new Outliner(this.#boxes, 0.0025, 0.001, this._uiManager.direction === "ltr"); + this.#focusOutlines = outlinerForOutline.getOutlines(); + const { + lastPoint + } = this.#focusOutlines.box; + this.#lastPoint = [(lastPoint[0] - this.x) / this.width, (lastPoint[1] - this.y) / this.height]; + } + #createFreeOutlines({ + highlightOutlines, + highlightId, + clipPathId + }) { + this.#highlightOutlines = highlightOutlines; + const extraThickness = 1.5; + this.#focusOutlines = highlightOutlines.getNewOutline(this.#thickness / 2 + extraThickness, 0.0025); + if (highlightId >= 0) { + this.#id = highlightId; + this.#clipPathId = clipPathId; + this.parent.drawLayer.finalizeLine(highlightId, highlightOutlines); + this.#outlineId = this.parent.drawLayer.highlightOutline(this.#focusOutlines); + } else if (this.parent) { + const angle = this.parent.viewport.rotation; + this.parent.drawLayer.updateLine(this.#id, highlightOutlines); + this.parent.drawLayer.updateBox(this.#id, HighlightEditor.#rotateBbox(this.#highlightOutlines.box, (angle - this.rotation + 360) % 360)); + this.parent.drawLayer.updateLine(this.#outlineId, this.#focusOutlines); + this.parent.drawLayer.updateBox(this.#outlineId, HighlightEditor.#rotateBbox(this.#focusOutlines.box, angle)); + } + const { + x, + y, + width, + height + } = highlightOutlines.box; + switch (this.rotation) { + case 0: + this.x = x; + this.y = y; + this.width = width; + this.height = height; + break; + case 90: + { + const [pageWidth, pageHeight] = this.parentDimensions; + this.x = y; + this.y = 1 - x; + this.width = width * pageHeight / pageWidth; + this.height = height * pageWidth / pageHeight; + break; + } + case 180: + this.x = 1 - x; + this.y = 1 - y; + this.width = width; + this.height = height; + break; + case 270: + { + const [pageWidth, pageHeight] = this.parentDimensions; + this.x = 1 - y; + this.y = x; + this.width = width * pageHeight / pageWidth; + this.height = height * pageWidth / pageHeight; + break; + } + } + const { + lastPoint + } = this.#focusOutlines.box; + this.#lastPoint = [(lastPoint[0] - x) / width, (lastPoint[1] - y) / height]; + } + static initialize(l10n, uiManager) { + AnnotationEditor.initialize(l10n, uiManager); + HighlightEditor._defaultColor ||= uiManager.highlightColors?.values().next().value || "#fff066"; + } + static updateDefaultParams(type, value) { + switch (type) { + case AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR: + HighlightEditor._defaultColor = value; + break; + case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS: + HighlightEditor._defaultThickness = value; + break; + } + } + translateInPage(x, y) {} + get toolbarPosition() { + return this.#lastPoint; + } + updateParams(type, value) { + switch (type) { + case AnnotationEditorParamsType.HIGHLIGHT_COLOR: + this.#updateColor(value); + break; + case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS: + this.#updateThickness(value); + break; + } + } + static get defaultPropertiesToUpdate() { + return [[AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR, HighlightEditor._defaultColor], [AnnotationEditorParamsType.HIGHLIGHT_THICKNESS, HighlightEditor._defaultThickness]]; + } + get propertiesToUpdate() { + return [[AnnotationEditorParamsType.HIGHLIGHT_COLOR, this.color || HighlightEditor._defaultColor], [AnnotationEditorParamsType.HIGHLIGHT_THICKNESS, this.#thickness || HighlightEditor._defaultThickness], [AnnotationEditorParamsType.HIGHLIGHT_FREE, this.#isFreeHighlight]]; + } + #updateColor(color) { + const setColor = col => { + this.color = col; + this.parent?.drawLayer.changeColor(this.#id, col); + this.#colorPicker?.updateColor(col); + }; + const savedColor = this.color; + this.addCommands({ + cmd: setColor.bind(this, color), + undo: setColor.bind(this, savedColor), + post: this._uiManager.updateUI.bind(this._uiManager, this), + mustExec: true, + type: AnnotationEditorParamsType.HIGHLIGHT_COLOR, + overwriteIfSameType: true, + keepUndo: true + }); + this._reportTelemetry({ + action: "color_changed", + color: this._uiManager.highlightColorNames.get(color) + }, true); + } + #updateThickness(thickness) { + const savedThickness = this.#thickness; + const setThickness = th => { + this.#thickness = th; + this.#changeThickness(th); + }; + this.addCommands({ + cmd: setThickness.bind(this, thickness), + undo: setThickness.bind(this, savedThickness), + post: this._uiManager.updateUI.bind(this._uiManager, this), + mustExec: true, + type: AnnotationEditorParamsType.INK_THICKNESS, + overwriteIfSameType: true, + keepUndo: true + }); + this._reportTelemetry({ + action: "thickness_changed", + thickness + }, true); + } + async addEditToolbar() { + const toolbar = await super.addEditToolbar(); + if (!toolbar) { + return null; + } + if (this._uiManager.highlightColors) { + this.#colorPicker = new ColorPicker({ + editor: this + }); + toolbar.addColorPicker(this.#colorPicker); + } + return toolbar; + } + disableEditing() { + super.disableEditing(); + this.div.classList.toggle("disabled", true); + } + enableEditing() { + super.enableEditing(); + this.div.classList.toggle("disabled", false); + } + fixAndSetPosition() { + return super.fixAndSetPosition(this.#getRotation()); + } + getBaseTranslation() { + return [0, 0]; + } + getRect(tx, ty) { + return super.getRect(tx, ty, this.#getRotation()); + } + onceAdded() { + this.parent.addUndoableEditor(this); + this.div.focus(); + } + remove() { + this.#cleanDrawLayer(); + this._reportTelemetry({ + action: "deleted" + }); + super.remove(); + } + rebuild() { + if (!this.parent) { + return; + } + super.rebuild(); + if (this.div === null) { + return; + } + this.#addToDrawLayer(); + if (!this.isAttachedToDOM) { + this.parent.add(this); + } + } + setParent(parent) { + let mustBeSelected = false; + if (this.parent && !parent) { + this.#cleanDrawLayer(); + } else if (parent) { + this.#addToDrawLayer(parent); + mustBeSelected = !this.parent && this.div?.classList.contains("selectedEditor"); + } + super.setParent(parent); + this.show(this._isVisible); + if (mustBeSelected) { + this.select(); + } + } + #changeThickness(thickness) { + if (!this.#isFreeHighlight) { + return; + } + this.#createFreeOutlines({ + highlightOutlines: this.#highlightOutlines.getNewOutline(thickness / 2) + }); + this.fixAndSetPosition(); + const [parentWidth, parentHeight] = this.parentDimensions; + this.setDims(this.width * parentWidth, this.height * parentHeight); + } + #cleanDrawLayer() { + if (this.#id === null || !this.parent) { + return; + } + this.parent.drawLayer.remove(this.#id); + this.#id = null; + this.parent.drawLayer.remove(this.#outlineId); + this.#outlineId = null; + } + #addToDrawLayer(parent = this.parent) { + if (this.#id !== null) { + return; + } + ({ + id: this.#id, + clipPathId: this.#clipPathId + } = parent.drawLayer.highlight(this.#highlightOutlines, this.color, this.#opacity)); + this.#outlineId = parent.drawLayer.highlightOutline(this.#focusOutlines); + if (this.#highlightDiv) { + this.#highlightDiv.style.clipPath = this.#clipPathId; + } + } + static #rotateBbox({ + x, + y, + width, + height + }, angle) { + switch (angle) { + case 90: + return { + x: 1 - y - height, + y: x, + width: height, + height: width + }; + case 180: + return { + x: 1 - x - width, + y: 1 - y - height, + width, + height + }; + case 270: + return { + x: y, + y: 1 - x - width, + width: height, + height: width + }; + } + return { + x, + y, + width, + height + }; + } + rotate(angle) { + const { + drawLayer + } = this.parent; + let box; + if (this.#isFreeHighlight) { + angle = (angle - this.rotation + 360) % 360; + box = HighlightEditor.#rotateBbox(this.#highlightOutlines.box, angle); + } else { + box = HighlightEditor.#rotateBbox(this, angle); + } + drawLayer.rotate(this.#id, angle); + drawLayer.rotate(this.#outlineId, angle); + drawLayer.updateBox(this.#id, box); + drawLayer.updateBox(this.#outlineId, HighlightEditor.#rotateBbox(this.#focusOutlines.box, angle)); + } + render() { + if (this.div) { + return this.div; + } + const div = super.render(); + if (this.#text) { + div.setAttribute("aria-label", this.#text); + div.setAttribute("role", "mark"); + } + if (this.#isFreeHighlight) { + div.classList.add("free"); + } else { + this.div.addEventListener("keydown", this.#keydown.bind(this), { + signal: this._uiManager._signal + }); + } + const highlightDiv = this.#highlightDiv = document.createElement("div"); + div.append(highlightDiv); + highlightDiv.setAttribute("aria-hidden", "true"); + highlightDiv.className = "internal"; + highlightDiv.style.clipPath = this.#clipPathId; + const [parentWidth, parentHeight] = this.parentDimensions; + this.setDims(this.width * parentWidth, this.height * parentHeight); + bindEvents(this, this.#highlightDiv, ["pointerover", "pointerleave"]); + this.enableEditing(); + return div; + } + pointerover() { + this.parent.drawLayer.addClass(this.#outlineId, "hovered"); + } + pointerleave() { + this.parent.drawLayer.removeClass(this.#outlineId, "hovered"); + } + #keydown(event) { + HighlightEditor._keyboardManager.exec(this, event); + } + _moveCaret(direction) { + this.parent.unselect(this); + switch (direction) { + case 0: + case 2: + this.#setCaret(true); + break; + case 1: + case 3: + this.#setCaret(false); + break; + } + } + #setCaret(start) { + if (!this.#anchorNode) { + return; + } + const selection = window.getSelection(); + if (start) { + selection.setPosition(this.#anchorNode, this.#anchorOffset); + } else { + selection.setPosition(this.#focusNode, this.#focusOffset); + } + } + select() { + super.select(); + if (!this.#outlineId) { + return; + } + this.parent?.drawLayer.removeClass(this.#outlineId, "hovered"); + this.parent?.drawLayer.addClass(this.#outlineId, "selected"); + } + unselect() { + super.unselect(); + if (!this.#outlineId) { + return; + } + this.parent?.drawLayer.removeClass(this.#outlineId, "selected"); + if (!this.#isFreeHighlight) { + this.#setCaret(false); + } + } + get _mustFixPosition() { + return !this.#isFreeHighlight; + } + show(visible = this._isVisible) { + super.show(visible); + if (this.parent) { + this.parent.drawLayer.show(this.#id, visible); + this.parent.drawLayer.show(this.#outlineId, visible); + } + } + #getRotation() { + return this.#isFreeHighlight ? this.rotation : 0; + } + #serializeBoxes() { + if (this.#isFreeHighlight) { + return null; + } + const [pageWidth, pageHeight] = this.pageDimensions; + const [pageX, pageY] = this.pageTranslation; + const boxes = this.#boxes; + const quadPoints = new Float32Array(boxes.length * 8); + let i = 0; + for (const { + x, + y, + width, + height + } of boxes) { + const sx = x * pageWidth + pageX; + const sy = (1 - y - height) * pageHeight + pageY; + quadPoints[i] = quadPoints[i + 4] = sx; + quadPoints[i + 1] = quadPoints[i + 3] = sy; + quadPoints[i + 2] = quadPoints[i + 6] = sx + width * pageWidth; + quadPoints[i + 5] = quadPoints[i + 7] = sy + height * pageHeight; + i += 8; + } + return quadPoints; + } + #serializeOutlines(rect) { + return this.#highlightOutlines.serialize(rect, this.#getRotation()); + } + static startHighlighting(parent, isLTR, { + target: textLayer, + x, + y + }) { + const { + x: layerX, + y: layerY, + width: parentWidth, + height: parentHeight + } = textLayer.getBoundingClientRect(); + const ac = new AbortController(); + const signal = parent.combinedSignal(ac); + const pointerDown = e => { + e.preventDefault(); + e.stopPropagation(); + }; + const pointerUpCallback = e => { + ac.abort(); + this.#endHighlight(parent, e); + }; + window.addEventListener("blur", pointerUpCallback, { + signal + }); + window.addEventListener("pointerup", pointerUpCallback, { + signal + }); + window.addEventListener("pointerdown", pointerDown, { + capture: true, + passive: false, + signal + }); + window.addEventListener("contextmenu", noContextMenu, { + signal + }); + textLayer.addEventListener("pointermove", this.#highlightMove.bind(this, parent), { + signal + }); + this._freeHighlight = new FreeOutliner({ + x, + y + }, [layerX, layerY, parentWidth, parentHeight], parent.scale, this._defaultThickness / 2, isLTR, 0.001); + ({ + id: this._freeHighlightId, + clipPathId: this._freeHighlightClipId + } = parent.drawLayer.highlight(this._freeHighlight, this._defaultColor, this._defaultOpacity, true)); + } + static #highlightMove(parent, event) { + if (this._freeHighlight.add(event)) { + parent.drawLayer.updatePath(this._freeHighlightId, this._freeHighlight); + } + } + static #endHighlight(parent, event) { + if (!this._freeHighlight.isEmpty()) { + parent.createAndAddNewEditor(event, false, { + highlightId: this._freeHighlightId, + highlightOutlines: this._freeHighlight.getOutlines(), + clipPathId: this._freeHighlightClipId, + methodOfCreation: "main_toolbar" + }); + } else { + parent.drawLayer.removeFreeHighlight(this._freeHighlightId); + } + this._freeHighlightId = -1; + this._freeHighlight = null; + this._freeHighlightClipId = ""; + } + static deserialize(data, parent, uiManager) { + const editor = super.deserialize(data, parent, uiManager); + const { + rect: [blX, blY, trX, trY], + color, + quadPoints + } = data; + editor.color = Util.makeHexColor(...color); + editor.#opacity = data.opacity; + const [pageWidth, pageHeight] = editor.pageDimensions; + editor.width = (trX - blX) / pageWidth; + editor.height = (trY - blY) / pageHeight; + const boxes = editor.#boxes = []; + for (let i = 0; i < quadPoints.length; i += 8) { + boxes.push({ + x: (quadPoints[4] - trX) / pageWidth, + y: (trY - (1 - quadPoints[i + 5])) / pageHeight, + width: (quadPoints[i + 2] - quadPoints[i]) / pageWidth, + height: (quadPoints[i + 5] - quadPoints[i + 1]) / pageHeight + }); + } + editor.#createOutlines(); + return editor; + } + serialize(isForCopying = false) { + if (this.isEmpty() || isForCopying) { + return null; + } + const rect = this.getRect(0, 0); + const color = AnnotationEditor._colorManager.convert(this.color); + return { + annotationType: AnnotationEditorType.HIGHLIGHT, + color, + opacity: this.#opacity, + thickness: this.#thickness, + quadPoints: this.#serializeBoxes(), + outlines: this.#serializeOutlines(rect), + pageIndex: this.pageIndex, + rect, + rotation: this.#getRotation(), + structTreeParentId: this._structTreeParentId + }; + } + static canCreateNewEmptyEditor() { + return false; + } +} + +;// CONCATENATED MODULE: ./src/display/editor/ink.js + + + + + +class InkEditor extends AnnotationEditor { #baseHeight = 0; #baseWidth = 0; - #boundCanvasPointermove = this.canvasPointermove.bind(this); - #boundCanvasPointerleave = this.canvasPointerleave.bind(this); - #boundCanvasPointerup = this.canvasPointerup.bind(this); - #boundCanvasPointerdown = this.canvasPointerdown.bind(this); + #canvasContextMenuTimeoutId = null; #currentPath2D = new Path2D(); #disableEditing = false; + #drawingAC = null; #hasSomethingToDraw = false; #isCanvasInitialized = false; #observer = null; + #pointerdownAC = null; #realWidth = 0; #realHeight = 0; #requestFrameCallback = null; @@ -16679,6 +17755,7 @@ class InkEditor extends _editor.AnnotationEditor { static _defaultOpacity = 1; static _defaultThickness = 1; static _type = "ink"; + static _editorType = AnnotationEditorType.INK; constructor(params) { super({ ...params, @@ -16697,91 +17774,86 @@ class InkEditor extends _editor.AnnotationEditor { this.y = 0; this._willKeepAspectRatio = true; } - static initialize(l10n) { - _editor.AnnotationEditor.initialize(l10n, { - strings: ["editor_ink_canvas_aria_label", "editor_ink2_aria_label"] - }); + static initialize(l10n, uiManager) { + AnnotationEditor.initialize(l10n, uiManager); } static updateDefaultParams(type, value) { switch (type) { - case _util.AnnotationEditorParamsType.INK_THICKNESS: + case AnnotationEditorParamsType.INK_THICKNESS: InkEditor._defaultThickness = value; break; - case _util.AnnotationEditorParamsType.INK_COLOR: + case AnnotationEditorParamsType.INK_COLOR: InkEditor._defaultColor = value; break; - case _util.AnnotationEditorParamsType.INK_OPACITY: + case AnnotationEditorParamsType.INK_OPACITY: InkEditor._defaultOpacity = value / 100; break; } } updateParams(type, value) { switch (type) { - case _util.AnnotationEditorParamsType.INK_THICKNESS: + case AnnotationEditorParamsType.INK_THICKNESS: this.#updateThickness(value); break; - case _util.AnnotationEditorParamsType.INK_COLOR: + case AnnotationEditorParamsType.INK_COLOR: this.#updateColor(value); break; - case _util.AnnotationEditorParamsType.INK_OPACITY: + case AnnotationEditorParamsType.INK_OPACITY: this.#updateOpacity(value); break; } } static get defaultPropertiesToUpdate() { - return [[_util.AnnotationEditorParamsType.INK_THICKNESS, InkEditor._defaultThickness], [_util.AnnotationEditorParamsType.INK_COLOR, InkEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor], [_util.AnnotationEditorParamsType.INK_OPACITY, Math.round(InkEditor._defaultOpacity * 100)]]; + return [[AnnotationEditorParamsType.INK_THICKNESS, InkEditor._defaultThickness], [AnnotationEditorParamsType.INK_COLOR, InkEditor._defaultColor || AnnotationEditor._defaultLineColor], [AnnotationEditorParamsType.INK_OPACITY, Math.round(InkEditor._defaultOpacity * 100)]]; } get propertiesToUpdate() { - return [[_util.AnnotationEditorParamsType.INK_THICKNESS, this.thickness || InkEditor._defaultThickness], [_util.AnnotationEditorParamsType.INK_COLOR, this.color || InkEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor], [_util.AnnotationEditorParamsType.INK_OPACITY, Math.round(100 * (this.opacity ?? InkEditor._defaultOpacity))]]; + 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))]]; } #updateThickness(thickness) { + const setThickness = th => { + this.thickness = th; + this.#fitToContent(); + }; const savedThickness = this.thickness; this.addCommands({ - cmd: () => { - this.thickness = thickness; - this.#fitToContent(); - }, - undo: () => { - this.thickness = savedThickness; - this.#fitToContent(); - }, + cmd: setThickness.bind(this, thickness), + undo: setThickness.bind(this, savedThickness), + post: this._uiManager.updateUI.bind(this._uiManager, this), mustExec: true, - type: _util.AnnotationEditorParamsType.INK_THICKNESS, + type: AnnotationEditorParamsType.INK_THICKNESS, overwriteIfSameType: true, keepUndo: true }); } #updateColor(color) { + const setColor = col => { + this.color = col; + this.#redraw(); + }; const savedColor = this.color; this.addCommands({ - cmd: () => { - this.color = color; - this.#redraw(); - }, - undo: () => { - this.color = savedColor; - this.#redraw(); - }, + cmd: setColor.bind(this, color), + undo: setColor.bind(this, savedColor), + post: this._uiManager.updateUI.bind(this._uiManager, this), mustExec: true, - type: _util.AnnotationEditorParamsType.INK_COLOR, + type: AnnotationEditorParamsType.INK_COLOR, overwriteIfSameType: true, keepUndo: true }); } #updateOpacity(opacity) { + const setOpacity = op => { + this.opacity = op; + this.#redraw(); + }; opacity /= 100; const savedOpacity = this.opacity; this.addCommands({ - cmd: () => { - this.opacity = opacity; - this.#redraw(); - }, - undo: () => { - this.opacity = savedOpacity; - this.#redraw(); - }, + cmd: setOpacity.bind(this, opacity), + undo: setOpacity.bind(this, savedOpacity), + post: this._uiManager.updateUI.bind(this._uiManager, this), mustExec: true, - type: _util.AnnotationEditorParamsType.INK_OPACITY, + type: AnnotationEditorParamsType.INK_OPACITY, overwriteIfSameType: true, keepUndo: true }); @@ -16814,7 +17886,11 @@ class InkEditor extends _editor.AnnotationEditor { this.canvas.width = this.canvas.height = 0; this.canvas.remove(); this.canvas = null; - this.#observer.disconnect(); + if (this.#canvasContextMenuTimeoutId) { + clearTimeout(this.#canvasContextMenuTimeoutId); + this.#canvasContextMenuTimeoutId = null; + } + this.#observer?.disconnect(); this.#observer = null; super.remove(); } @@ -16838,7 +17914,7 @@ class InkEditor extends _editor.AnnotationEditor { } super.enableEditMode(); this._isDraggable = false; - this.canvas.addEventListener("pointerdown", this.#boundCanvasPointerdown); + this.#addPointerdownListener(); } disableEditMode() { if (!this.isInEditMode() || this.canvas === null) { @@ -16847,7 +17923,7 @@ class InkEditor extends _editor.AnnotationEditor { super.disableEditMode(); this._isDraggable = !this.isEmpty(); this.div.classList.remove("editing"); - this.canvas.removeEventListener("pointerdown", this.#boundCanvasPointerdown); + this.#removePointerdownListener(); } onceAdded() { this._isDraggable = !this.isEmpty(); @@ -16884,20 +17960,30 @@ class InkEditor extends _editor.AnnotationEditor { ctx.lineCap = "round"; ctx.lineJoin = "round"; ctx.miterLimit = 10; - ctx.strokeStyle = `${color}${(0, _tools.opacityToHex)(opacity)}`; + ctx.strokeStyle = `${color}${opacityToHex(opacity)}`; } #startDrawing(x, y) { - this.canvas.addEventListener("contextmenu", _display_utils.noContextMenu); - this.canvas.addEventListener("pointerleave", this.#boundCanvasPointerleave); - this.canvas.addEventListener("pointermove", this.#boundCanvasPointermove); - this.canvas.addEventListener("pointerup", this.#boundCanvasPointerup); - this.canvas.removeEventListener("pointerdown", this.#boundCanvasPointerdown); + this.canvas.addEventListener("contextmenu", noContextMenu, { + signal: this._uiManager._signal + }); + this.#removePointerdownListener(); + this.#drawingAC = new AbortController(); + const signal = this._uiManager.combinedSignal(this.#drawingAC); + this.canvas.addEventListener("pointerleave", this.canvasPointerleave.bind(this), { + signal + }); + this.canvas.addEventListener("pointermove", this.canvasPointermove.bind(this), { + signal + }); + this.canvas.addEventListener("pointerup", this.canvasPointerup.bind(this), { + signal + }); this.isEditing = true; if (!this.#isCanvasInitialized) { this.#isCanvasInitialized = true; this.#setCanvasDims(); this.thickness ||= InkEditor._defaultThickness; - this.color ||= InkEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor; + this.color ||= InkEditor._defaultColor || AnnotationEditor._defaultLineColor; this.opacity ??= InkEditor._defaultOpacity; } this.currentPath.push([x, y]); @@ -16959,7 +18045,7 @@ class InkEditor extends _editor.AnnotationEditor { this.allRawPaths.push(currentPath); this.paths.push(bezier); this.bezierPath2D.push(path2D); - this.rebuild(); + this._uiManager.rebuild(this); }; const undo = () => { this.allRawPaths.pop(); @@ -17065,7 +18151,7 @@ class InkEditor extends _editor.AnnotationEditor { this.#disableEditing = true; this.div.classList.add("disabled"); this.#fitToContent(true); - this.makeResizable(); + this.select(); this.parent.addInkEditorIfNeeded(true); this.moveInDOM(); this.div.focus({ @@ -17079,14 +18165,30 @@ class InkEditor extends _editor.AnnotationEditor { super.focusin(event); this.enableEditMode(); } + #addPointerdownListener() { + if (this.#pointerdownAC) { + return; + } + this.#pointerdownAC = new AbortController(); + const signal = this._uiManager.combinedSignal(this.#pointerdownAC); + this.canvas.addEventListener("pointerdown", this.canvasPointerdown.bind(this), { + signal + }); + } + #removePointerdownListener() { + this.pointerdownAC?.abort(); + this.pointerdownAC = null; + } canvasPointerdown(event) { if (event.button !== 0 || !this.isInEditMode() || this.#disableEditing) { return; } this.setInForeground(); event.preventDefault(); - if (event.type !== "mouse") { - this.div.focus(); + if (!this.div.contains(document.activeElement)) { + this.div.focus({ + preventScroll: true + }); } this.#startDrawing(event.offsetX, event.offsetY); } @@ -17102,12 +18204,15 @@ class InkEditor extends _editor.AnnotationEditor { this.#endDrawing(event); } #endDrawing(event) { - this.canvas.removeEventListener("pointerleave", this.#boundCanvasPointerleave); - this.canvas.removeEventListener("pointermove", this.#boundCanvasPointermove); - this.canvas.removeEventListener("pointerup", this.#boundCanvasPointerup); - this.canvas.addEventListener("pointerdown", this.#boundCanvasPointerdown); - setTimeout(() => { - this.canvas.removeEventListener("contextmenu", _display_utils.noContextMenu); + this.#drawingAC?.abort(); + this.#drawingAC = null; + this.#addPointerdownListener(); + if (this.#canvasContextMenuTimeoutId) { + clearTimeout(this.#canvasContextMenuTimeoutId); + } + this.#canvasContextMenuTimeoutId = setTimeout(() => { + this.#canvasContextMenuTimeoutId = null; + this.canvas.removeEventListener("contextmenu", noContextMenu); }, 10); this.#stopDrawing(event.offsetX, event.offsetY); this.addToAnnotationStorage(); @@ -17117,7 +18222,7 @@ class InkEditor extends _editor.AnnotationEditor { this.canvas = document.createElement("canvas"); this.canvas.width = this.canvas.height = 0; this.canvas.className = "inkEditorCanvas"; - _editor.AnnotationEditor._l10nPromise.get("editor_ink_canvas_aria_label").then(msg => this.canvas?.setAttribute("aria-label", msg)); + this.canvas.setAttribute("data-l10n-id", "pdfjs-ink-canvas"); this.div.append(this.canvas); this.ctx = this.canvas.getContext("2d"); } @@ -17129,6 +18234,12 @@ class InkEditor extends _editor.AnnotationEditor { } }); this.#observer.observe(this.div); + this._uiManager._signal.addEventListener("abort", () => { + this.#observer?.disconnect(); + this.#observer = null; + }, { + once: true + }); } get isResizable() { return !this.isEmpty() && this.#disableEditing; @@ -17143,7 +18254,7 @@ class InkEditor extends _editor.AnnotationEditor { baseY = this.y; } super.render(); - _editor.AnnotationEditor._l10nPromise.get("editor_ink2_aria_label").then(msg => this.div?.setAttribute("aria-label", msg)); + this.div.setAttribute("data-l10n-id", "pdfjs-ink"); const [x, y, w, h] = this.#getInitialBBox(); this.setAt(x, y, 0, 0); this.setDims(w, h); @@ -17293,6 +18404,13 @@ class InkEditor extends _editor.AnnotationEditor { const points = []; for (let j = 0, jj = bezier.length; j < jj; j++) { const [first, control1, control2, second] = bezier[j]; + if (first[0] === second[0] && first[1] === second[1] && jj === 1) { + const p0 = s * first[0] + shiftX; + const p1 = s * first[1] + shiftY; + buffer.push(p0, p1); + points.push(p0, p1); + break; + } const p10 = s * first[0] + shiftX; const p11 = s * first[1] + shiftY; const p20 = s * control1[0] + shiftX; @@ -17325,7 +18443,7 @@ class InkEditor extends _editor.AnnotationEditor { let yMax = -Infinity; for (const path of this.paths) { for (const [first, control1, control2, second] of path) { - const bbox = _util.Util.bezierBoundingBox(...first, ...control1, ...control2, ...second); + const bbox = Util.bezierBoundingBox(...first, ...control1, ...control2, ...second); xMin = Math.min(xMin, bbox[0]); yMin = Math.min(yMin, bbox[1]); xMax = Math.max(xMax, bbox[2]); @@ -17347,8 +18465,8 @@ class InkEditor extends _editor.AnnotationEditor { } const bbox = this.#getBbox(); const padding = this.#getPadding(); - this.#baseWidth = Math.max(_editor.AnnotationEditor.MIN_SIZE, bbox[2] - bbox[0]); - this.#baseHeight = Math.max(_editor.AnnotationEditor.MIN_SIZE, bbox[3] - bbox[1]); + this.#baseWidth = Math.max(AnnotationEditor.MIN_SIZE, bbox[2] - bbox[0]); + this.#baseHeight = Math.max(AnnotationEditor.MIN_SIZE, bbox[3] - bbox[1]); const width = Math.ceil(padding + this.#baseWidth * this.scaleFactor); const height = Math.ceil(padding + this.#baseHeight * this.scaleFactor); const [parentWidth, parentHeight] = this.parentDimensions; @@ -17368,12 +18486,12 @@ class InkEditor extends _editor.AnnotationEditor { this.translate(prevTranslationX - this.translationX - unscaledPadding, prevTranslationY - this.translationY - unscaledPadding); } static deserialize(data, parent, uiManager) { - if (data instanceof _annotation_layer.InkAnnotationElement) { + if (data instanceof InkAnnotationElement) { return null; } const editor = super.deserialize(data, parent, uiManager); editor.thickness = data.thickness; - editor.color = _util.Util.makeHexColor(...data.color); + editor.color = Util.makeHexColor(...data.color); editor.opacity = data.opacity; const [pageWidth, pageHeight] = editor.pageDimensions; const width = editor.width * pageWidth; @@ -17411,8 +18529,8 @@ class InkEditor extends _editor.AnnotationEditor { editor.bezierPath2D.push(path2D); } const bbox = editor.#getBbox(); - editor.#baseWidth = Math.max(_editor.AnnotationEditor.MIN_SIZE, bbox[2] - bbox[0]); - editor.#baseHeight = Math.max(_editor.AnnotationEditor.MIN_SIZE, bbox[3] - bbox[1]); + editor.#baseWidth = Math.max(AnnotationEditor.MIN_SIZE, bbox[2] - bbox[0]); + editor.#baseHeight = Math.max(AnnotationEditor.MIN_SIZE, bbox[3] - bbox[1]); editor.#setScaleFactor(width, height); return editor; } @@ -17421,9 +18539,9 @@ class InkEditor extends _editor.AnnotationEditor { return null; } const rect = this.getRect(0, 0); - const color = _editor.AnnotationEditor._colorManager.convert(this.ctx.strokeStyle); + const color = AnnotationEditor._colorManager.convert(this.ctx.strokeStyle); return { - annotationType: _util.AnnotationEditorType.INK, + annotationType: AnnotationEditorType.INK, color, thickness: this.thickness, opacity: this.opacity, @@ -17435,34 +18553,26 @@ class InkEditor extends _editor.AnnotationEditor { }; } } -exports.InkEditor = InkEditor; -/***/ }), -/* 34 */ -/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { +;// CONCATENATED MODULE: ./src/display/editor/stamp.js -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.StampEditor = void 0; -var _util = __w_pdfjs_require__(1); -var _editor = __w_pdfjs_require__(4); -var _display_utils = __w_pdfjs_require__(6); -var _annotation_layer = __w_pdfjs_require__(29); -class StampEditor extends _editor.AnnotationEditor { + +class StampEditor extends AnnotationEditor { #bitmap = null; #bitmapId = null; #bitmapPromise = null; #bitmapUrl = null; #bitmapFile = null; + #bitmapFileName = ""; #canvas = null; #observer = null; #resizeTimeoutId = null; #isSvg = false; #hasBeenAddedInUndoStack = false; static _type = "stamp"; + static _editorType = AnnotationEditorType.STAMP; constructor(params) { super({ ...params, @@ -17471,24 +18581,43 @@ class StampEditor extends _editor.AnnotationEditor { this.#bitmapUrl = params.bitmapUrl; this.#bitmapFile = params.bitmapFile; } - static initialize(l10n) { - _editor.AnnotationEditor.initialize(l10n); + static initialize(l10n, uiManager) { + AnnotationEditor.initialize(l10n, uiManager); } static get supportedTypes() { const types = ["apng", "avif", "bmp", "gif", "jpeg", "png", "svg+xml", "webp", "x-icon"]; - return (0, _util.shadow)(this, "supportedTypes", types.map(type => `image/${type}`)); + return shadow(this, "supportedTypes", types.map(type => `image/${type}`)); } static get supportedTypesStr() { - return (0, _util.shadow)(this, "supportedTypesStr", this.supportedTypes.join(",")); + return shadow(this, "supportedTypesStr", this.supportedTypes.join(",")); } static isHandlingMimeForPasting(mime) { return this.supportedTypes.includes(mime); } static paste(item, parent) { - parent.pasteEditor(_util.AnnotationEditorType.STAMP, { + parent.pasteEditor(AnnotationEditorType.STAMP, { bitmapFile: item.getAsFile() }); } + altTextFinish() { + if (this._uiManager.useNewAltTextFlow) { + this.div.hidden = false; + } + super.altTextFinish(); + } + get telemetryFinalData() { + return { + type: "stamp", + hasAltText: !!this.altTextData?.altText + }; + } + static computeTelemetryFinalData(data) { + const hasAltTextStats = data.get("hasAltText"); + return { + hasAltText: hasAltTextStats.get(true) ?? 0, + hasNoAltText: hasAltTextStats.get(false) ?? 0 + }; + } #getBitmapFetched(data, fromId = false) { if (!data) { this.remove(); @@ -17499,14 +18628,84 @@ class StampEditor extends _editor.AnnotationEditor { this.#bitmapId = data.id; this.#isSvg = data.isSvg; } + if (data.file) { + this.#bitmapFileName = data.file.name; + } this.#createCanvas(); } #getBitmapDone() { this.#bitmapPromise = null; this._uiManager.enableWaiting(false); - if (this.#canvas) { - this.div.focus(); + if (!this.#canvas) { + return; } + if (this._uiManager.useNewAltTextWhenAddingImage && this._uiManager.useNewAltTextFlow && this.#bitmap) { + this._editToolbar.hide(); + this._uiManager.editAltText(this, true); + return; + } + if (!this._uiManager.useNewAltTextWhenAddingImage && this._uiManager.useNewAltTextFlow && this.#bitmap) { + this._reportTelemetry({ + action: "pdfjs.image.image_added", + data: { + alt_text_modal: false, + alt_text_type: "empty" + } + }); + try { + this.mlGuessAltText(); + } catch {} + } + this.div.focus(); + } + async mlGuessAltText(imageData = null, updateAltTextData = true) { + if (this.hasAltTextData()) { + return null; + } + const { + mlManager + } = this._uiManager; + if (!mlManager) { + throw new Error("No ML."); + } + if (!(await mlManager.isEnabledFor("altText"))) { + throw new Error("ML isn't enabled for alt text."); + } + const { + data, + width, + height + } = imageData || this.copyCanvas(null, true).imageData; + const response = await mlManager.guess({ + name: "altText", + request: { + data, + width, + height, + channels: data.length / (width * height) + } + }); + if (!response) { + throw new Error("No response from the AI service."); + } + if (response.error) { + throw new Error("Error from the AI service."); + } + if (response.cancel) { + return null; + } + if (!response.output) { + throw new Error("No valid response from the AI service."); + } + const altText = response.output; + await this.setGuessedAltText(altText); + if (updateAltTextData && !this.hasAltTextData()) { + this.altTextData = { + alt: altText, + decorative: false + }; + } + return altText; } #getBitmap() { if (this.#bitmapId) { @@ -17531,6 +18730,7 @@ class StampEditor extends _editor.AnnotationEditor { const input = document.createElement("input"); input.type = "file"; input.accept = StampEditor.supportedTypesStr; + const signal = this._uiManager._signal; this.#bitmapPromise = new Promise(resolve => { input.addEventListener("change", async () => { if (!input.files || input.files.length === 0) { @@ -17538,13 +18738,23 @@ class StampEditor extends _editor.AnnotationEditor { } else { this._uiManager.enableWaiting(true); const data = await this._uiManager.imageManager.getFromFile(input.files[0]); + this._reportTelemetry({ + action: "pdfjs.image.image_selected", + data: { + alt_text_modal: this._uiManager.useNewAltTextFlow + } + }); this.#getBitmapFetched(data); } resolve(); + }, { + signal }); input.addEventListener("cancel", () => { this.remove(); resolve(); + }, { + signal }); }).finally(() => this.#getBitmapDone()); input.click(); @@ -17557,6 +18767,10 @@ class StampEditor extends _editor.AnnotationEditor { this.#canvas = null; this.#observer?.disconnect(); this.#observer = null; + if (this.#resizeTimeoutId) { + clearTimeout(this.#resizeTimeoutId); + this.#resizeTimeoutId = null; + } } super.remove(); } @@ -17571,7 +18785,7 @@ class StampEditor extends _editor.AnnotationEditor { if (this.div === null) { return; } - if (this.#bitmapId) { + if (this.#bitmapId && this.#canvas === null) { this.#getBitmap(); } if (!this.isAttachedToDOM) { @@ -17583,7 +18797,7 @@ class StampEditor extends _editor.AnnotationEditor { this.div.focus(); } isEmpty() { - return !(this.#bitmapPromise || this.#bitmap || this.#bitmapUrl || this.#bitmapFile); + return !(this.#bitmapPromise || this.#bitmap || this.#bitmapUrl || this.#bitmapFile || this.#bitmapId); } get isResizable() { return true; @@ -17599,6 +18813,7 @@ class StampEditor extends _editor.AnnotationEditor { } super.render(); this.div.hidden = true; + this.addAltTextButton(); if (this.#bitmap) { this.#createCanvas(); } else { @@ -17633,24 +18848,86 @@ class StampEditor extends _editor.AnnotationEditor { this._uiManager.enableWaiting(false); const canvas = this.#canvas = document.createElement("canvas"); div.append(canvas); - div.hidden = false; + if (!this._uiManager.useNewAltTextWhenAddingImage || !this._uiManager.useNewAltTextFlow) { + div.hidden = false; + } this.#drawBitmap(width, height); this.#createObserver(); if (!this.#hasBeenAddedInUndoStack) { this.parent.addUndoableEditor(this); this.#hasBeenAddedInUndoStack = true; } - this._uiManager._eventBus.dispatch("reporttelemetry", { - source: this, - details: { - type: "editing", - subtype: this.editorType, - data: { - action: "inserted_image" - } - } + this._reportTelemetry({ + action: "inserted_image" }); - this.addAltTextButton(); + if (this.#bitmapFileName) { + canvas.setAttribute("aria-label", this.#bitmapFileName); + } + } + copyCanvas(maxDimension, createImageData = false) { + if (!maxDimension) { + maxDimension = 224; + } + const { + width: bitmapWidth, + height: bitmapHeight + } = this.#bitmap; + const canvas = document.createElement("canvas"); + let bitmap = this.#bitmap; + let width = bitmapWidth, + height = bitmapHeight; + if (bitmapWidth > maxDimension || bitmapHeight > maxDimension) { + const ratio = Math.min(maxDimension / bitmapWidth, maxDimension / bitmapHeight); + width = Math.floor(bitmapWidth * ratio); + height = Math.floor(bitmapHeight * ratio); + if (!this.#isSvg) { + bitmap = this.#scaleBitmap(width, height); + } + } + canvas.width = width; + canvas.height = height; + const ctx = canvas.getContext("2d"); + ctx.filter = this._uiManager.hcmFilter; + let white = "white", + black = "#cfcfd8"; + if (this._uiManager.hcmFilter !== "none") { + black = "black"; + } else if (window.matchMedia?.("(prefers-color-scheme: dark)").matches) { + white = "#8f8f9d"; + black = "#42414d"; + } + const boxDim = 15; + const pattern = new OffscreenCanvas(boxDim * 2, boxDim * 2); + const patternCtx = pattern.getContext("2d"); + patternCtx.fillStyle = white; + patternCtx.fillRect(0, 0, boxDim * 2, boxDim * 2); + patternCtx.fillStyle = black; + patternCtx.fillRect(0, 0, boxDim, boxDim); + patternCtx.fillRect(boxDim, boxDim, boxDim, boxDim); + ctx.fillStyle = ctx.createPattern(pattern, "repeat"); + ctx.fillRect(0, 0, width, height); + if (createImageData) { + const offscreen = new OffscreenCanvas(width, height); + const offscreenCtx = offscreen.getContext("2d", { + willReadFrequently: true + }); + offscreenCtx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, width, height); + const data = offscreenCtx.getImageData(0, 0, width, height).data; + ctx.drawImage(offscreen, 0, 0); + return { + canvas, + imageData: { + width, + height, + data + } + }; + } + ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, width, height); + return { + canvas, + imageData: null + }; } #setDimensions(width, height) { const [parentWidth, parentHeight] = this.parentDimensions; @@ -17710,6 +18987,9 @@ class StampEditor extends _editor.AnnotationEditor { ctx.filter = this._uiManager.hcmFilter; ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, width, height); } + getImageForAltText() { + return this.#canvas; + } #serializeBitmap(toUrl) { if (toUrl) { if (this.#isSvg) { @@ -17729,8 +19009,8 @@ class StampEditor extends _editor.AnnotationEditor { } if (this.#isSvg) { const [pageWidth, pageHeight] = this.pageDimensions; - const width = Math.round(this.width * pageWidth * _display_utils.PixelsPerInch.PDF_TO_CSS_UNITS); - const height = Math.round(this.height * pageHeight * _display_utils.PixelsPerInch.PDF_TO_CSS_UNITS); + const width = Math.round(this.width * pageWidth * PixelsPerInch.PDF_TO_CSS_UNITS); + const height = Math.round(this.height * pageHeight * PixelsPerInch.PDF_TO_CSS_UNITS); const offscreen = new OffscreenCanvas(width, height); const ctx = offscreen.getContext("2d"); ctx.drawImage(this.#bitmap, 0, 0, this.#bitmap.width, this.#bitmap.height, 0, 0, width, height); @@ -17739,6 +19019,9 @@ class StampEditor extends _editor.AnnotationEditor { return structuredClone(this.#bitmap); } #createObserver() { + if (!this._uiManager._signal) { + return; + } this.#observer = new ResizeObserver(entries => { const rect = entries[0].contentRect; if (rect.width && rect.height) { @@ -17746,9 +19029,15 @@ class StampEditor extends _editor.AnnotationEditor { } }); this.#observer.observe(this.div); + this._uiManager._signal.addEventListener("abort", () => { + this.#observer?.disconnect(); + this.#observer = null; + }, { + once: true + }); } static deserialize(data, parent, uiManager) { - if (data instanceof _annotation_layer.StampAnnotationElement) { + if (data instanceof StampAnnotationElement) { return null; } const editor = super.deserialize(data, parent, uiManager); @@ -17778,7 +19067,7 @@ class StampEditor extends _editor.AnnotationEditor { return null; } const serialized = { - annotationType: _util.AnnotationEditorType.STAMP, + annotationType: AnnotationEditorType.STAMP, bitmapId: this.#bitmapId, pageIndex: this.pageIndex, rect: this.getRect(0, 0), @@ -17788,13 +19077,13 @@ class StampEditor extends _editor.AnnotationEditor { }; if (isForCopying) { serialized.bitmapUrl = this.#serializeBitmap(true); - serialized.accessibilityData = this.altTextData; + serialized.accessibilityData = this.serializeAltText(true); return serialized; } const { decorative, altText - } = this.altTextData; + } = this.serializeAltText(false); if (!decorative && altText) { serialized.accessibilityData = { type: "Figure", @@ -17823,324 +19112,872 @@ class StampEditor extends _editor.AnnotationEditor { return serialized; } } -exports.StampEditor = StampEditor; -/***/ }) -/******/ ]); -/************************************************************************/ -/******/ // The module cache -/******/ var __webpack_module_cache__ = {}; -/******/ -/******/ // The require function -/******/ function __w_pdfjs_require__(moduleId) { -/******/ // Check if module is in cache -/******/ var cachedModule = __webpack_module_cache__[moduleId]; -/******/ if (cachedModule !== undefined) { -/******/ return cachedModule.exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = __webpack_module_cache__[moduleId] = { -/******/ // no module.id needed -/******/ // no module.loaded needed -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ __webpack_modules__[moduleId](module, module.exports, __w_pdfjs_require__); -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/************************************************************************/ -var __webpack_exports__ = {}; -// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk. -(() => { -var exports = __webpack_exports__; +;// CONCATENATED MODULE: ./src/display/editor/annotation_editor_layer.js -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "AbortException", ({ - enumerable: true, - get: function () { - return _util.AbortException; - } -})); -Object.defineProperty(exports, "AnnotationEditorLayer", ({ - enumerable: true, - get: function () { - return _annotation_editor_layer.AnnotationEditorLayer; - } -})); -Object.defineProperty(exports, "AnnotationEditorParamsType", ({ - enumerable: true, - get: function () { - return _util.AnnotationEditorParamsType; - } -})); -Object.defineProperty(exports, "AnnotationEditorType", ({ - enumerable: true, - get: function () { - return _util.AnnotationEditorType; - } -})); -Object.defineProperty(exports, "AnnotationEditorUIManager", ({ - enumerable: true, - get: function () { - return _tools.AnnotationEditorUIManager; - } -})); -Object.defineProperty(exports, "AnnotationLayer", ({ - enumerable: true, - get: function () { - return _annotation_layer.AnnotationLayer; - } -})); -Object.defineProperty(exports, "AnnotationMode", ({ - enumerable: true, - get: function () { - return _util.AnnotationMode; - } -})); -Object.defineProperty(exports, "CMapCompressionType", ({ - enumerable: true, - get: function () { - return _util.CMapCompressionType; - } -})); -Object.defineProperty(exports, "DOMSVGFactory", ({ - enumerable: true, - get: function () { - return _display_utils.DOMSVGFactory; - } -})); -Object.defineProperty(exports, "FeatureTest", ({ - enumerable: true, - get: function () { - return _util.FeatureTest; - } -})); -Object.defineProperty(exports, "GlobalWorkerOptions", ({ - enumerable: true, - get: function () { - return _worker_options.GlobalWorkerOptions; - } -})); -Object.defineProperty(exports, "ImageKind", ({ - enumerable: true, - get: function () { - return _util.ImageKind; - } -})); -Object.defineProperty(exports, "InvalidPDFException", ({ - enumerable: true, - get: function () { - return _util.InvalidPDFException; - } -})); -Object.defineProperty(exports, "MissingPDFException", ({ - enumerable: true, - get: function () { - return _util.MissingPDFException; - } -})); -Object.defineProperty(exports, "OPS", ({ - enumerable: true, - get: function () { - return _util.OPS; - } -})); -Object.defineProperty(exports, "PDFDataRangeTransport", ({ - enumerable: true, - get: function () { - return _api.PDFDataRangeTransport; - } -})); -Object.defineProperty(exports, "PDFDateString", ({ - enumerable: true, - get: function () { - return _display_utils.PDFDateString; - } -})); -Object.defineProperty(exports, "PDFWorker", ({ - enumerable: true, - get: function () { - return _api.PDFWorker; - } -})); -Object.defineProperty(exports, "PasswordResponses", ({ - enumerable: true, - get: function () { - return _util.PasswordResponses; - } -})); -Object.defineProperty(exports, "PermissionFlag", ({ - enumerable: true, - get: function () { - return _util.PermissionFlag; - } -})); -Object.defineProperty(exports, "PixelsPerInch", ({ - enumerable: true, - get: function () { - return _display_utils.PixelsPerInch; - } -})); -Object.defineProperty(exports, "PromiseCapability", ({ - enumerable: true, - get: function () { - return _util.PromiseCapability; - } -})); -Object.defineProperty(exports, "RenderingCancelledException", ({ - enumerable: true, - get: function () { - return _display_utils.RenderingCancelledException; - } -})); -Object.defineProperty(exports, "SVGGraphics", ({ - enumerable: true, - get: function () { - return _api.SVGGraphics; - } -})); -Object.defineProperty(exports, "UnexpectedResponseException", ({ - enumerable: true, - get: function () { - return _util.UnexpectedResponseException; - } -})); -Object.defineProperty(exports, "Util", ({ - enumerable: true, - get: function () { - return _util.Util; - } -})); -Object.defineProperty(exports, "VerbosityLevel", ({ - enumerable: true, - get: function () { - return _util.VerbosityLevel; - } -})); -Object.defineProperty(exports, "XfaLayer", ({ - enumerable: true, - get: function () { - return _xfa_layer.XfaLayer; - } -})); -Object.defineProperty(exports, "build", ({ - enumerable: true, - get: function () { - return _api.build; - } -})); -Object.defineProperty(exports, "createValidAbsoluteUrl", ({ - enumerable: true, - get: function () { - return _util.createValidAbsoluteUrl; - } -})); -Object.defineProperty(exports, "getDocument", ({ - enumerable: true, - get: function () { - return _api.getDocument; - } -})); -Object.defineProperty(exports, "getFilenameFromUrl", ({ - enumerable: true, - get: function () { - return _display_utils.getFilenameFromUrl; - } -})); -Object.defineProperty(exports, "getPdfFilenameFromUrl", ({ - enumerable: true, - get: function () { - return _display_utils.getPdfFilenameFromUrl; - } -})); -Object.defineProperty(exports, "getXfaPageViewport", ({ - enumerable: true, - get: function () { - return _display_utils.getXfaPageViewport; - } -})); -Object.defineProperty(exports, "isDataScheme", ({ - enumerable: true, - get: function () { - return _display_utils.isDataScheme; - } -})); -Object.defineProperty(exports, "isPdfFile", ({ - enumerable: true, - get: function () { - return _display_utils.isPdfFile; - } -})); -Object.defineProperty(exports, "loadScript", ({ - enumerable: true, - get: function () { - return _display_utils.loadScript; - } -})); -Object.defineProperty(exports, "noContextMenu", ({ - enumerable: true, - get: function () { - return _display_utils.noContextMenu; - } -})); -Object.defineProperty(exports, "normalizeUnicode", ({ - enumerable: true, - get: function () { - return _util.normalizeUnicode; - } -})); -Object.defineProperty(exports, "renderTextLayer", ({ - enumerable: true, - get: function () { - return _text_layer.renderTextLayer; - } -})); -Object.defineProperty(exports, "setLayerDimensions", ({ - enumerable: true, - get: function () { - return _display_utils.setLayerDimensions; - } -})); -Object.defineProperty(exports, "shadow", ({ - enumerable: true, - get: function () { - return _util.shadow; - } -})); -Object.defineProperty(exports, "updateTextLayer", ({ - enumerable: true, - get: function () { - return _text_layer.updateTextLayer; - } -})); -Object.defineProperty(exports, "version", ({ - enumerable: true, - get: function () { - return _api.version; - } -})); -var _util = __w_pdfjs_require__(1); -var _api = __w_pdfjs_require__(2); -var _display_utils = __w_pdfjs_require__(6); -var _text_layer = __w_pdfjs_require__(26); -var _annotation_editor_layer = __w_pdfjs_require__(27); -var _tools = __w_pdfjs_require__(5); -var _annotation_layer = __w_pdfjs_require__(29); -var _worker_options = __w_pdfjs_require__(14); -var _xfa_layer = __w_pdfjs_require__(32); -const pdfjsVersion = '3.11.174'; -const pdfjsBuild = 'ce8716743'; -})(); -/******/ return __webpack_exports__; -/******/ })() -; -}); -//# sourceMappingURL=pdf.js.map \ No newline at end of file + + + + +class AnnotationEditorLayer { + #accessibilityManager; + #allowClick = false; + #annotationLayer = null; + #clickAC = null; + #editorFocusTimeoutId = null; + #editors = new Map(); + #hadPointerDown = false; + #isCleaningUp = false; + #isDisabling = false; + #textLayer = null; + #textSelectionAC = null; + #uiManager; + static _initialized = false; + static #editorTypes = new Map([FreeTextEditor, InkEditor, StampEditor, HighlightEditor].map(type => [type._editorType, type])); + constructor({ + uiManager, + pageIndex, + div, + accessibilityManager, + annotationLayer, + drawLayer, + textLayer, + viewport, + l10n + }) { + const editorTypes = [...AnnotationEditorLayer.#editorTypes.values()]; + if (!AnnotationEditorLayer._initialized) { + AnnotationEditorLayer._initialized = true; + for (const editorType of editorTypes) { + editorType.initialize(l10n, uiManager); + } + } + uiManager.registerEditorTypes(editorTypes); + this.#uiManager = uiManager; + this.pageIndex = pageIndex; + this.div = div; + this.#accessibilityManager = accessibilityManager; + this.#annotationLayer = annotationLayer; + this.viewport = viewport; + this.#textLayer = textLayer; + this.drawLayer = drawLayer; + this.#uiManager.addLayer(this); + } + get isEmpty() { + return this.#editors.size === 0; + } + get isInvisible() { + return this.isEmpty && this.#uiManager.getMode() === AnnotationEditorType.NONE; + } + updateToolbar(mode) { + this.#uiManager.updateToolbar(mode); + } + updateMode(mode = this.#uiManager.getMode()) { + this.#cleanup(); + switch (mode) { + case AnnotationEditorType.NONE: + this.disableTextSelection(); + this.togglePointerEvents(false); + this.toggleAnnotationLayerPointerEvents(true); + this.disableClick(); + return; + case AnnotationEditorType.INK: + this.addInkEditorIfNeeded(false); + this.disableTextSelection(); + this.togglePointerEvents(true); + this.disableClick(); + break; + case AnnotationEditorType.HIGHLIGHT: + this.enableTextSelection(); + this.togglePointerEvents(false); + this.disableClick(); + break; + default: + this.disableTextSelection(); + this.togglePointerEvents(true); + this.enableClick(); + } + this.toggleAnnotationLayerPointerEvents(false); + const { + classList + } = this.div; + for (const editorType of AnnotationEditorLayer.#editorTypes.values()) { + classList.toggle(`${editorType._type}Editing`, mode === editorType._editorType); + } + this.div.hidden = false; + } + hasTextLayer(textLayer) { + return textLayer === this.#textLayer?.div; + } + addInkEditorIfNeeded(isCommitting) { + if (this.#uiManager.getMode() !== AnnotationEditorType.INK) { + return; + } + if (!isCommitting) { + for (const editor of this.#editors.values()) { + if (editor.isEmpty()) { + editor.setInBackground(); + return; + } + } + } + const editor = this.createAndAddNewEditor({ + offsetX: 0, + offsetY: 0 + }, false); + editor.setInBackground(); + } + setEditingState(isEditing) { + this.#uiManager.setEditingState(isEditing); + } + addCommands(params) { + this.#uiManager.addCommands(params); + } + toggleDrawing(enabled = false) { + this.div.classList.toggle("drawing", !enabled); + } + togglePointerEvents(enabled = false) { + this.div.classList.toggle("disabled", !enabled); + } + toggleAnnotationLayerPointerEvents(enabled = false) { + this.#annotationLayer?.div.classList.toggle("disabled", !enabled); + } + enable() { + this.div.tabIndex = 0; + this.togglePointerEvents(true); + const annotationElementIds = new Set(); + for (const editor of this.#editors.values()) { + editor.enableEditing(); + editor.show(true); + if (editor.annotationElementId) { + this.#uiManager.removeChangedExistingAnnotation(editor); + annotationElementIds.add(editor.annotationElementId); + } + } + if (!this.#annotationLayer) { + return; + } + const editables = this.#annotationLayer.getEditableAnnotations(); + for (const editable of editables) { + editable.hide(); + if (this.#uiManager.isDeletedAnnotationElement(editable.data.id)) { + continue; + } + if (annotationElementIds.has(editable.data.id)) { + continue; + } + const editor = this.deserialize(editable); + if (!editor) { + continue; + } + this.addOrRebuild(editor); + editor.enableEditing(); + } + } + disable() { + this.#isDisabling = true; + this.div.tabIndex = -1; + this.togglePointerEvents(false); + const changedAnnotations = new Map(); + const resetAnnotations = new Map(); + for (const editor of this.#editors.values()) { + editor.disableEditing(); + if (!editor.annotationElementId) { + continue; + } + if (editor.serialize() !== null) { + changedAnnotations.set(editor.annotationElementId, editor); + continue; + } else { + resetAnnotations.set(editor.annotationElementId, editor); + } + this.getEditableAnnotation(editor.annotationElementId)?.show(); + editor.remove(); + } + if (this.#annotationLayer) { + const editables = this.#annotationLayer.getEditableAnnotations(); + for (const editable of editables) { + const { + id + } = editable.data; + if (this.#uiManager.isDeletedAnnotationElement(id)) { + continue; + } + let editor = resetAnnotations.get(id); + if (editor) { + editor.resetAnnotationElement(editable); + editor.show(false); + editable.show(); + continue; + } + editor = changedAnnotations.get(id); + if (editor) { + this.#uiManager.addChangedExistingAnnotation(editor); + editor.renderAnnotationElement(editable); + editor.show(false); + } + editable.show(); + } + } + this.#cleanup(); + if (this.isEmpty) { + this.div.hidden = true; + } + const { + classList + } = this.div; + for (const editorType of AnnotationEditorLayer.#editorTypes.values()) { + classList.remove(`${editorType._type}Editing`); + } + this.disableTextSelection(); + this.toggleAnnotationLayerPointerEvents(true); + this.#isDisabling = false; + } + getEditableAnnotation(id) { + return this.#annotationLayer?.getEditableAnnotation(id) || null; + } + setActiveEditor(editor) { + const currentActive = this.#uiManager.getActive(); + if (currentActive === editor) { + return; + } + this.#uiManager.setActiveEditor(editor); + } + enableTextSelection() { + this.div.tabIndex = -1; + if (this.#textLayer?.div && !this.#textSelectionAC) { + this.#textSelectionAC = new AbortController(); + const signal = this.#uiManager.combinedSignal(this.#textSelectionAC); + this.#textLayer.div.addEventListener("pointerdown", this.#textLayerPointerDown.bind(this), { + signal + }); + this.#textLayer.div.classList.add("highlighting"); + } + } + disableTextSelection() { + this.div.tabIndex = 0; + if (this.#textLayer?.div && this.#textSelectionAC) { + this.#textSelectionAC.abort(); + this.#textSelectionAC = null; + this.#textLayer.div.classList.remove("highlighting"); + } + } + #textLayerPointerDown(event) { + this.#uiManager.unselectAll(); + const { + target + } = event; + if (target === this.#textLayer.div || target.classList.contains("endOfContent") && this.#textLayer.div.contains(target)) { + const { + isMac + } = util_FeatureTest.platform; + if (event.button !== 0 || event.ctrlKey && isMac) { + return; + } + this.#uiManager.showAllEditors("highlight", true, true); + this.#textLayer.div.classList.add("free"); + this.toggleDrawing(); + HighlightEditor.startHighlighting(this, this.#uiManager.direction === "ltr", event); + this.#textLayer.div.addEventListener("pointerup", () => { + this.#textLayer.div.classList.remove("free"); + this.toggleDrawing(true); + }, { + once: true, + signal: this.#uiManager._signal + }); + event.preventDefault(); + } + } + enableClick() { + if (this.#clickAC) { + return; + } + this.#clickAC = new AbortController(); + const signal = this.#uiManager.combinedSignal(this.#clickAC); + this.div.addEventListener("pointerdown", this.pointerdown.bind(this), { + signal + }); + this.div.addEventListener("pointerup", this.pointerup.bind(this), { + signal + }); + } + disableClick() { + this.#clickAC?.abort(); + this.#clickAC = null; + } + attach(editor) { + this.#editors.set(editor.id, editor); + const { + annotationElementId + } = editor; + if (annotationElementId && this.#uiManager.isDeletedAnnotationElement(annotationElementId)) { + this.#uiManager.removeDeletedAnnotationElement(editor); + } + } + detach(editor) { + this.#editors.delete(editor.id); + this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv); + if (!this.#isDisabling && editor.annotationElementId) { + this.#uiManager.addDeletedAnnotationElement(editor); + } + } + remove(editor) { + this.detach(editor); + this.#uiManager.removeEditor(editor); + editor.div.remove(); + editor.isAttachedToDOM = false; + if (!this.#isCleaningUp) { + this.addInkEditorIfNeeded(false); + } + } + changeParent(editor) { + if (editor.parent === this) { + return; + } + if (editor.parent && editor.annotationElementId) { + this.#uiManager.addDeletedAnnotationElement(editor.annotationElementId); + AnnotationEditor.deleteAnnotationElement(editor); + editor.annotationElementId = null; + } + this.attach(editor); + editor.parent?.detach(editor); + editor.setParent(this); + if (editor.div && editor.isAttachedToDOM) { + editor.div.remove(); + this.div.append(editor.div); + } + } + add(editor) { + if (editor.parent === this && editor.isAttachedToDOM) { + return; + } + this.changeParent(editor); + this.#uiManager.addEditor(editor); + this.attach(editor); + if (!editor.isAttachedToDOM) { + const div = editor.render(); + this.div.append(div); + editor.isAttachedToDOM = true; + } + editor.fixAndSetPosition(); + editor.onceAdded(); + this.#uiManager.addToAnnotationStorage(editor); + editor._reportTelemetry(editor.telemetryInitialData); + } + moveEditorInDOM(editor) { + if (!editor.isAttachedToDOM) { + return; + } + const { + activeElement + } = document; + if (editor.div.contains(activeElement) && !this.#editorFocusTimeoutId) { + editor._focusEventsAllowed = false; + this.#editorFocusTimeoutId = setTimeout(() => { + this.#editorFocusTimeoutId = null; + if (!editor.div.contains(document.activeElement)) { + editor.div.addEventListener("focusin", () => { + editor._focusEventsAllowed = true; + }, { + once: true, + signal: this.#uiManager._signal + }); + activeElement.focus(); + } else { + editor._focusEventsAllowed = true; + } + }, 0); + } + editor._structTreeParentId = this.#accessibilityManager?.moveElementInDOM(this.div, editor.div, editor.contentDiv, true); + } + addOrRebuild(editor) { + if (editor.needsToBeRebuilt()) { + editor.parent ||= this; + editor.rebuild(); + editor.show(); + } else { + this.add(editor); + } + } + addUndoableEditor(editor) { + const cmd = () => editor._uiManager.rebuild(editor); + const undo = () => { + editor.remove(); + }; + this.addCommands({ + cmd, + undo, + mustExec: false + }); + } + getNextId() { + return this.#uiManager.getId(); + } + get #currentEditorType() { + return AnnotationEditorLayer.#editorTypes.get(this.#uiManager.getMode()); + } + combinedSignal(ac) { + return this.#uiManager.combinedSignal(ac); + } + #createNewEditor(params) { + const editorType = this.#currentEditorType; + return editorType ? new editorType.prototype.constructor(params) : null; + } + canCreateNewEmptyEditor() { + return this.#currentEditorType?.canCreateNewEmptyEditor(); + } + pasteEditor(mode, params) { + this.#uiManager.updateToolbar(mode); + this.#uiManager.updateMode(mode); + const { + offsetX, + offsetY + } = this.#getCenterPoint(); + const id = this.getNextId(); + const editor = this.#createNewEditor({ + parent: this, + id, + x: offsetX, + y: offsetY, + uiManager: this.#uiManager, + isCentered: true, + ...params + }); + if (editor) { + this.add(editor); + } + } + deserialize(data) { + return AnnotationEditorLayer.#editorTypes.get(data.annotationType ?? data.annotationEditorType)?.deserialize(data, this, this.#uiManager) || null; + } + createAndAddNewEditor(event, isCentered, data = {}) { + const id = this.getNextId(); + const editor = this.#createNewEditor({ + parent: this, + id, + x: event.offsetX, + y: event.offsetY, + uiManager: this.#uiManager, + isCentered, + ...data + }); + if (editor) { + this.add(editor); + } + return editor; + } + #getCenterPoint() { + const { + x, + y, + width, + height + } = this.div.getBoundingClientRect(); + const tlX = Math.max(0, x); + const tlY = Math.max(0, y); + const brX = Math.min(window.innerWidth, x + width); + const brY = Math.min(window.innerHeight, y + height); + const centerX = (tlX + brX) / 2 - x; + const centerY = (tlY + brY) / 2 - y; + const [offsetX, offsetY] = this.viewport.rotation % 180 === 0 ? [centerX, centerY] : [centerY, centerX]; + return { + offsetX, + offsetY + }; + } + addNewEditor() { + this.createAndAddNewEditor(this.#getCenterPoint(), true); + } + setSelected(editor) { + this.#uiManager.setSelected(editor); + } + toggleSelected(editor) { + this.#uiManager.toggleSelected(editor); + } + isSelected(editor) { + return this.#uiManager.isSelected(editor); + } + unselect(editor) { + this.#uiManager.unselect(editor); + } + pointerup(event) { + const { + isMac + } = util_FeatureTest.platform; + if (event.button !== 0 || event.ctrlKey && isMac) { + return; + } + if (event.target !== this.div) { + return; + } + if (!this.#hadPointerDown) { + return; + } + this.#hadPointerDown = false; + if (!this.#allowClick) { + this.#allowClick = true; + return; + } + if (this.#uiManager.getMode() === AnnotationEditorType.STAMP) { + this.#uiManager.unselectAll(); + return; + } + this.createAndAddNewEditor(event, false); + } + pointerdown(event) { + if (this.#uiManager.getMode() === AnnotationEditorType.HIGHLIGHT) { + this.enableTextSelection(); + } + if (this.#hadPointerDown) { + this.#hadPointerDown = false; + return; + } + const { + isMac + } = util_FeatureTest.platform; + if (event.button !== 0 || event.ctrlKey && isMac) { + return; + } + if (event.target !== this.div) { + return; + } + this.#hadPointerDown = true; + const editor = this.#uiManager.getActive(); + this.#allowClick = !editor || editor.isEmpty(); + } + findNewParent(editor, x, y) { + const layer = this.#uiManager.findParent(x, y); + if (layer === null || layer === this) { + return false; + } + layer.changeParent(editor); + return true; + } + destroy() { + if (this.#uiManager.getActive()?.parent === this) { + this.#uiManager.commitOrRemove(); + this.#uiManager.setActiveEditor(null); + } + if (this.#editorFocusTimeoutId) { + clearTimeout(this.#editorFocusTimeoutId); + this.#editorFocusTimeoutId = null; + } + for (const editor of this.#editors.values()) { + this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv); + editor.setParent(null); + editor.isAttachedToDOM = false; + editor.div.remove(); + } + this.div = null; + this.#editors.clear(); + this.#uiManager.removeLayer(this); + } + #cleanup() { + this.#isCleaningUp = true; + for (const editor of this.#editors.values()) { + if (editor.isEmpty()) { + editor.remove(); + } + } + this.#isCleaningUp = false; + } + render({ + viewport + }) { + this.viewport = viewport; + setLayerDimensions(this.div, viewport); + for (const editor of this.#uiManager.getEditors(this.pageIndex)) { + this.add(editor); + editor.rebuild(); + } + this.updateMode(); + } + update({ + viewport + }) { + this.#uiManager.commitOrRemove(); + this.#cleanup(); + const oldRotation = this.viewport.rotation; + const rotation = viewport.rotation; + this.viewport = viewport; + setLayerDimensions(this.div, { + rotation + }); + if (oldRotation !== rotation) { + for (const editor of this.#editors.values()) { + editor.rotate(rotation); + } + } + this.addInkEditorIfNeeded(false); + } + get pageDimensions() { + const { + pageWidth, + pageHeight + } = this.viewport.rawDims; + return [pageWidth, pageHeight]; + } + get scale() { + return this.#uiManager.viewParameters.realScale; + } +} + +;// CONCATENATED MODULE: ./src/display/draw_layer.js + + +class DrawLayer { + #parent = null; + #id = 0; + #mapping = new Map(); + #toUpdate = new Map(); + constructor({ + pageIndex + }) { + this.pageIndex = pageIndex; + } + setParent(parent) { + if (!this.#parent) { + this.#parent = parent; + return; + } + if (this.#parent !== parent) { + if (this.#mapping.size > 0) { + for (const root of this.#mapping.values()) { + root.remove(); + parent.append(root); + } + } + this.#parent = parent; + } + } + static get _svgFactory() { + return shadow(this, "_svgFactory", new DOMSVGFactory()); + } + static #setBox(element, { + x = 0, + y = 0, + width = 1, + height = 1 + } = {}) { + const { + style + } = element; + style.top = `${100 * y}%`; + style.left = `${100 * x}%`; + style.width = `${100 * width}%`; + style.height = `${100 * height}%`; + } + #createSVG(box) { + const svg = DrawLayer._svgFactory.create(1, 1, true); + this.#parent.append(svg); + svg.setAttribute("aria-hidden", true); + DrawLayer.#setBox(svg, box); + return svg; + } + #createClipPath(defs, pathId) { + const clipPath = DrawLayer._svgFactory.createElement("clipPath"); + defs.append(clipPath); + const clipPathId = `clip_${pathId}`; + clipPath.setAttribute("id", clipPathId); + clipPath.setAttribute("clipPathUnits", "objectBoundingBox"); + const clipPathUse = DrawLayer._svgFactory.createElement("use"); + clipPath.append(clipPathUse); + clipPathUse.setAttribute("href", `#${pathId}`); + clipPathUse.classList.add("clip"); + return clipPathId; + } + highlight(outlines, color, opacity, isPathUpdatable = false) { + const id = this.#id++; + const root = this.#createSVG(outlines.box); + root.classList.add("highlight"); + if (outlines.free) { + root.classList.add("free"); + } + const defs = DrawLayer._svgFactory.createElement("defs"); + root.append(defs); + const path = DrawLayer._svgFactory.createElement("path"); + defs.append(path); + const pathId = `path_p${this.pageIndex}_${id}`; + path.setAttribute("id", pathId); + path.setAttribute("d", outlines.toSVGPath()); + if (isPathUpdatable) { + this.#toUpdate.set(id, path); + } + const clipPathId = this.#createClipPath(defs, pathId); + const use = DrawLayer._svgFactory.createElement("use"); + root.append(use); + root.setAttribute("fill", color); + root.setAttribute("fill-opacity", opacity); + use.setAttribute("href", `#${pathId}`); + this.#mapping.set(id, root); + return { + id, + clipPathId: `url(#${clipPathId})` + }; + } + highlightOutline(outlines) { + const id = this.#id++; + const root = this.#createSVG(outlines.box); + root.classList.add("highlightOutline"); + const defs = DrawLayer._svgFactory.createElement("defs"); + root.append(defs); + const path = DrawLayer._svgFactory.createElement("path"); + defs.append(path); + const pathId = `path_p${this.pageIndex}_${id}`; + path.setAttribute("id", pathId); + path.setAttribute("d", outlines.toSVGPath()); + path.setAttribute("vector-effect", "non-scaling-stroke"); + let maskId; + if (outlines.free) { + root.classList.add("free"); + const mask = DrawLayer._svgFactory.createElement("mask"); + defs.append(mask); + maskId = `mask_p${this.pageIndex}_${id}`; + mask.setAttribute("id", maskId); + mask.setAttribute("maskUnits", "objectBoundingBox"); + const rect = DrawLayer._svgFactory.createElement("rect"); + mask.append(rect); + rect.setAttribute("width", "1"); + rect.setAttribute("height", "1"); + rect.setAttribute("fill", "white"); + const use = DrawLayer._svgFactory.createElement("use"); + mask.append(use); + use.setAttribute("href", `#${pathId}`); + use.setAttribute("stroke", "none"); + use.setAttribute("fill", "black"); + use.setAttribute("fill-rule", "nonzero"); + use.classList.add("mask"); + } + const use1 = DrawLayer._svgFactory.createElement("use"); + root.append(use1); + use1.setAttribute("href", `#${pathId}`); + if (maskId) { + use1.setAttribute("mask", `url(#${maskId})`); + } + const use2 = use1.cloneNode(); + root.append(use2); + use1.classList.add("mainOutline"); + use2.classList.add("secondaryOutline"); + this.#mapping.set(id, root); + return id; + } + finalizeLine(id, line) { + const path = this.#toUpdate.get(id); + this.#toUpdate.delete(id); + this.updateBox(id, line.box); + path.setAttribute("d", line.toSVGPath()); + } + updateLine(id, line) { + const root = this.#mapping.get(id); + const defs = root.firstChild; + const path = defs.firstChild; + path.setAttribute("d", line.toSVGPath()); + } + removeFreeHighlight(id) { + this.remove(id); + this.#toUpdate.delete(id); + } + updatePath(id, line) { + this.#toUpdate.get(id).setAttribute("d", line.toSVGPath()); + } + updateBox(id, box) { + DrawLayer.#setBox(this.#mapping.get(id), box); + } + show(id, visible) { + this.#mapping.get(id).classList.toggle("hidden", !visible); + } + rotate(id, angle) { + this.#mapping.get(id).setAttribute("data-main-rotation", angle); + } + changeColor(id, color) { + this.#mapping.get(id).setAttribute("fill", color); + } + changeOpacity(id, opacity) { + this.#mapping.get(id).setAttribute("fill-opacity", opacity); + } + addClass(id, className) { + this.#mapping.get(id).classList.add(className); + } + removeClass(id, className) { + this.#mapping.get(id).classList.remove(className); + } + remove(id) { + if (this.#parent === null) { + return; + } + this.#mapping.get(id).remove(); + this.#mapping.delete(id); + } + destroy() { + this.#parent = null; + for (const root of this.#mapping.values()) { + root.remove(); + } + this.#mapping.clear(); + } +} + +;// CONCATENATED MODULE: ./src/pdf.js + + + + + + + + + + + + +const pdfjsVersion = "4.6.82"; +const pdfjsBuild = "9b541910f"; + +var __webpack_exports__AbortException = __webpack_exports__.AbortException; +var __webpack_exports__AnnotationEditorLayer = __webpack_exports__.AnnotationEditorLayer; +var __webpack_exports__AnnotationEditorParamsType = __webpack_exports__.AnnotationEditorParamsType; +var __webpack_exports__AnnotationEditorType = __webpack_exports__.AnnotationEditorType; +var __webpack_exports__AnnotationEditorUIManager = __webpack_exports__.AnnotationEditorUIManager; +var __webpack_exports__AnnotationLayer = __webpack_exports__.AnnotationLayer; +var __webpack_exports__AnnotationMode = __webpack_exports__.AnnotationMode; +var __webpack_exports__CMapCompressionType = __webpack_exports__.CMapCompressionType; +var __webpack_exports__ColorPicker = __webpack_exports__.ColorPicker; +var __webpack_exports__DOMSVGFactory = __webpack_exports__.DOMSVGFactory; +var __webpack_exports__DrawLayer = __webpack_exports__.DrawLayer; +var __webpack_exports__FeatureTest = __webpack_exports__.FeatureTest; +var __webpack_exports__GlobalWorkerOptions = __webpack_exports__.GlobalWorkerOptions; +var __webpack_exports__ImageKind = __webpack_exports__.ImageKind; +var __webpack_exports__InvalidPDFException = __webpack_exports__.InvalidPDFException; +var __webpack_exports__MissingPDFException = __webpack_exports__.MissingPDFException; +var __webpack_exports__OPS = __webpack_exports__.OPS; +var __webpack_exports__PDFDataRangeTransport = __webpack_exports__.PDFDataRangeTransport; +var __webpack_exports__PDFDateString = __webpack_exports__.PDFDateString; +var __webpack_exports__PDFWorker = __webpack_exports__.PDFWorker; +var __webpack_exports__PasswordResponses = __webpack_exports__.PasswordResponses; +var __webpack_exports__PermissionFlag = __webpack_exports__.PermissionFlag; +var __webpack_exports__PixelsPerInch = __webpack_exports__.PixelsPerInch; +var __webpack_exports__RenderingCancelledException = __webpack_exports__.RenderingCancelledException; +var __webpack_exports__TextLayer = __webpack_exports__.TextLayer; +var __webpack_exports__UnexpectedResponseException = __webpack_exports__.UnexpectedResponseException; +var __webpack_exports__Util = __webpack_exports__.Util; +var __webpack_exports__VerbosityLevel = __webpack_exports__.VerbosityLevel; +var __webpack_exports__XfaLayer = __webpack_exports__.XfaLayer; +var __webpack_exports__build = __webpack_exports__.build; +var __webpack_exports__createValidAbsoluteUrl = __webpack_exports__.createValidAbsoluteUrl; +var __webpack_exports__fetchData = __webpack_exports__.fetchData; +var __webpack_exports__getDocument = __webpack_exports__.getDocument; +var __webpack_exports__getFilenameFromUrl = __webpack_exports__.getFilenameFromUrl; +var __webpack_exports__getPdfFilenameFromUrl = __webpack_exports__.getPdfFilenameFromUrl; +var __webpack_exports__getXfaPageViewport = __webpack_exports__.getXfaPageViewport; +var __webpack_exports__isDataScheme = __webpack_exports__.isDataScheme; +var __webpack_exports__isPdfFile = __webpack_exports__.isPdfFile; +var __webpack_exports__noContextMenu = __webpack_exports__.noContextMenu; +var __webpack_exports__normalizeUnicode = __webpack_exports__.normalizeUnicode; +var __webpack_exports__setLayerDimensions = __webpack_exports__.setLayerDimensions; +var __webpack_exports__shadow = __webpack_exports__.shadow; +var __webpack_exports__version = __webpack_exports__.version; +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__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 }; + +//# sourceMappingURL=pdf.mjs.map \ No newline at end of file diff --git a/vendor/pdfjs/pdf.mjs.map b/vendor/pdfjs/pdf.mjs.map new file mode 100644 index 0000000..af1c8d3 --- /dev/null +++ b/vendor/pdfjs/pdf.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"pdf.mjs","mappings":";;;;;;;;;;;;;;;;;;;;;;SAAA;SACA;;;;;UCDA;UACA;UACA;UACA;UACA,yCAAyC,wCAAwC;UACjF;UACA;UACA;;;;;UCPA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACoBA,MAAMA,QAAQ,GAEZ,OAAOC,OAAO,KAAK,QAAQ,IAC3BA,OAAO,GAAG,EAAE,KAAK,kBAAkB,IACnC,CAACA,OAAO,CAACC,QAAQ,CAACC,EAAE,IACpB,EAAEF,OAAO,CAACC,QAAQ,CAACE,QAAQ,IAAIH,OAAO,CAACI,IAAI,IAAIJ,OAAO,CAACI,IAAI,KAAK,SAAS,CAAC;AAE5E,MAAMC,eAAe,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;AAC1C,MAAMC,oBAAoB,GAAG,CAAC,KAAK,EAAE,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;AAEvD,MAAMC,uBAAuB,GAAG,IAAI;AAIpC,MAAMC,WAAW,GAAG,IAAI;AACxB,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CAAC,CAAC+xF,OAAO,CAACtkG,GAAG,CAACoE,EAAE,CAAC,CAACyP,SAAS,CAACC,GAAG,CAACvB,SAAS,CAAC;EAChD;EAEAwkF,WAAWA,CAAC3yF,EAAE,EAAEmO,SAAS,EAAE;IACzB,IAAI,CAAC,CAAC+xF,OAAO,CAACtkG,GAAG,CAACoE,EAAE,CAAC,CAACyP,SAAS,CAACjN,MAAM,CAAC2L,SAAS,CAAC;EACnD;EAEA3L,MAAMA,CAACxC,EAAE,EAAE;IACT,IAAI,IAAI,CAAC,CAACoR,MAAM,KAAK,IAAI,EAAE;MACzB;IACF;IACA,IAAI,CAAC,CAAC8uF,OAAO,CAACtkG,GAAG,CAACoE,EAAE,CAAC,CAACwC,MAAM,CAAC,CAAC;IAC9B,IAAI,CAAC,CAAC09F,OAAO,CAAChwF,MAAM,CAAClQ,EAAE,CAAC;EAC1B;EAEAtC,OAAOA,CAAA,EAAG;IACR,IAAI,CAAC,CAAC0T,MAAM,GAAG,IAAI;IACnB,KAAK,MAAMw+D,IAAI,IAAI,IAAI,CAAC,CAACswB,OAAO,CAACjkF,MAAM,CAAC,CAAC,EAAE;MACzC2zD,IAAI,CAACptE,MAAM,CAAC,CAAC;IACf;IACA,IAAI,CAAC,CAAC09F,OAAO,CAAC77F,KAAK,CAAC,CAAC;EACvB;AACF;;;ACvM0B;AAOA;AAcU;AACgD;AACd;AACN;AACD;AACX;AACc;AACV;AACJ;AACF;AAGlD,MAAM+8F,YAAY,GACkB,QAAwC;AAE5E,MAAMC,UAAU,GACoB,WAAsC","sources":["webpack://pdf.js/webpack/bootstrap","webpack://pdf.js/webpack/runtime/define property getters","webpack://pdf.js/webpack/runtime/hasOwnProperty shorthand","webpack://pdf.js/./src/shared/util.js","webpack://pdf.js/./src/display/base_factory.js","webpack://pdf.js/./src/display/display_utils.js","webpack://pdf.js/./src/display/editor/toolbar.js","webpack://pdf.js/./src/display/editor/tools.js","webpack://pdf.js/./src/display/editor/alt_text.js","webpack://pdf.js/./src/display/editor/editor.js","webpack://pdf.js/./src/shared/murmurhash3.js","webpack://pdf.js/./src/display/annotation_storage.js","webpack://pdf.js/./src/display/font_loader.js","webpack://pdf.js/./src/display/node_utils.js","webpack://pdf.js/./src/display/pattern_helper.js","webpack://pdf.js/./src/shared/image_utils.js","webpack://pdf.js/./src/display/canvas.js","webpack://pdf.js/./src/display/worker_options.js","webpack://pdf.js/./src/shared/message_handler.js","webpack://pdf.js/./src/display/metadata.js","webpack://pdf.js/./src/display/optional_content_config.js","webpack://pdf.js/./src/display/transport_stream.js","webpack://pdf.js/./src/display/content_disposition.js","webpack://pdf.js/./src/display/network_utils.js","webpack://pdf.js/./src/display/fetch_stream.js","webpack://pdf.js/./src/display/network.js","webpack://pdf.js/./src/display/node_stream.js","webpack://pdf.js/./src/display/text_layer.js","webpack://pdf.js/./src/display/xfa_text.js","webpack://pdf.js/./src/display/api.js","webpack://pdf.js/./src/shared/scripting_utils.js","webpack://pdf.js/./src/display/xfa_layer.js","webpack://pdf.js/./src/display/annotation_layer.js","webpack://pdf.js/./src/display/editor/freetext.js","webpack://pdf.js/./src/display/editor/outliner.js","webpack://pdf.js/./src/display/editor/color_picker.js","webpack://pdf.js/./src/display/editor/highlight.js","webpack://pdf.js/./src/display/editor/ink.js","webpack://pdf.js/./src/display/editor/stamp.js","webpack://pdf.js/./src/display/editor/annotation_editor_layer.js","webpack://pdf.js/./src/display/draw_layer.js","webpack://pdf.js/./src/pdf.js"],"sourcesContent":["// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","/* Copyright 2012 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/* globals process */\n\n// NW.js / Electron is a browser context, but copies some Node.js objects; see\n// http://docs.nwjs.io/en/latest/For%20Users/Advanced/JavaScript%20Contexts%20in%20NW.js/#access-nodejs-and-nwjs-api-in-browser-context\n// https://www.electronjs.org/docs/api/process#processversionselectron-readonly\n// https://www.electronjs.org/docs/api/process#processtype-readonly\nconst isNodeJS =\n (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"GENERIC\")) &&\n typeof process === \"object\" &&\n process + \"\" === \"[object process]\" &&\n !process.versions.nw &&\n !(process.versions.electron && process.type && process.type !== \"browser\");\n\nconst IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];\nconst FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];\n\nconst MAX_IMAGE_SIZE_TO_CACHE = 10e6; // Ten megabytes.\n\n// Represent the percentage of the height of a single-line field over\n// the font size. Acrobat seems to use this value.\nconst LINE_FACTOR = 1.35;\nconst LINE_DESCENT_FACTOR = 0.35;\nconst BASELINE_FACTOR = LINE_DESCENT_FACTOR / LINE_FACTOR;\n\n/**\n * Refer to the `WorkerTransport.getRenderingIntent`-method in the API, to see\n * how these flags are being used:\n * - ANY, DISPLAY, and PRINT are the normal rendering intents, note the\n * `PDFPageProxy.{render, getOperatorList, getAnnotations}`-methods.\n * - SAVE is used, on the worker-thread, when saving modified annotations.\n * - ANNOTATIONS_FORMS, ANNOTATIONS_STORAGE, ANNOTATIONS_DISABLE control which\n * annotations are rendered onto the canvas (i.e. by being included in the\n * operatorList), note the `PDFPageProxy.{render, getOperatorList}`-methods\n * and their `annotationMode`-option.\n * - IS_EDITING is used when editing is active in the viewer.\n * - OPLIST is used with the `PDFPageProxy.getOperatorList`-method, note the\n * `OperatorList`-constructor (on the worker-thread).\n */\nconst RenderingIntentFlag = {\n ANY: 0x01,\n DISPLAY: 0x02,\n PRINT: 0x04,\n SAVE: 0x08,\n ANNOTATIONS_FORMS: 0x10,\n ANNOTATIONS_STORAGE: 0x20,\n ANNOTATIONS_DISABLE: 0x40,\n IS_EDITING: 0x80,\n OPLIST: 0x100,\n};\n\nconst AnnotationMode = {\n DISABLE: 0,\n ENABLE: 1,\n ENABLE_FORMS: 2,\n ENABLE_STORAGE: 3,\n};\n\nconst AnnotationEditorPrefix = \"pdfjs_internal_editor_\";\n\nconst AnnotationEditorType = {\n DISABLE: -1,\n NONE: 0,\n FREETEXT: 3,\n HIGHLIGHT: 9,\n STAMP: 13,\n INK: 15,\n};\n\nconst AnnotationEditorParamsType = {\n RESIZE: 1,\n CREATE: 2,\n FREETEXT_SIZE: 11,\n FREETEXT_COLOR: 12,\n FREETEXT_OPACITY: 13,\n INK_COLOR: 21,\n INK_THICKNESS: 22,\n INK_OPACITY: 23,\n HIGHLIGHT_COLOR: 31,\n HIGHLIGHT_DEFAULT_COLOR: 32,\n HIGHLIGHT_THICKNESS: 33,\n HIGHLIGHT_FREE: 34,\n HIGHLIGHT_SHOW_ALL: 35,\n};\n\n// Permission flags from Table 22, Section 7.6.3.2 of the PDF specification.\nconst PermissionFlag = {\n PRINT: 0x04,\n MODIFY_CONTENTS: 0x08,\n COPY: 0x10,\n MODIFY_ANNOTATIONS: 0x20,\n FILL_INTERACTIVE_FORMS: 0x100,\n COPY_FOR_ACCESSIBILITY: 0x200,\n ASSEMBLE: 0x400,\n PRINT_HIGH_QUALITY: 0x800,\n};\n\nconst TextRenderingMode = {\n FILL: 0,\n STROKE: 1,\n FILL_STROKE: 2,\n INVISIBLE: 3,\n FILL_ADD_TO_PATH: 4,\n STROKE_ADD_TO_PATH: 5,\n FILL_STROKE_ADD_TO_PATH: 6,\n ADD_TO_PATH: 7,\n FILL_STROKE_MASK: 3,\n ADD_TO_PATH_FLAG: 4,\n};\n\nconst ImageKind = {\n GRAYSCALE_1BPP: 1,\n RGB_24BPP: 2,\n RGBA_32BPP: 3,\n};\n\nconst AnnotationType = {\n TEXT: 1,\n LINK: 2,\n FREETEXT: 3,\n LINE: 4,\n SQUARE: 5,\n CIRCLE: 6,\n POLYGON: 7,\n POLYLINE: 8,\n HIGHLIGHT: 9,\n UNDERLINE: 10,\n SQUIGGLY: 11,\n STRIKEOUT: 12,\n STAMP: 13,\n CARET: 14,\n INK: 15,\n POPUP: 16,\n FILEATTACHMENT: 17,\n SOUND: 18,\n MOVIE: 19,\n WIDGET: 20,\n SCREEN: 21,\n PRINTERMARK: 22,\n TRAPNET: 23,\n WATERMARK: 24,\n THREED: 25,\n REDACT: 26,\n};\n\nconst AnnotationReplyType = {\n GROUP: \"Group\",\n REPLY: \"R\",\n};\n\nconst AnnotationFlag = {\n INVISIBLE: 0x01,\n HIDDEN: 0x02,\n PRINT: 0x04,\n NOZOOM: 0x08,\n NOROTATE: 0x10,\n NOVIEW: 0x20,\n READONLY: 0x40,\n LOCKED: 0x80,\n TOGGLENOVIEW: 0x100,\n LOCKEDCONTENTS: 0x200,\n};\n\nconst AnnotationFieldFlag = {\n READONLY: 0x0000001,\n REQUIRED: 0x0000002,\n NOEXPORT: 0x0000004,\n MULTILINE: 0x0001000,\n PASSWORD: 0x0002000,\n NOTOGGLETOOFF: 0x0004000,\n RADIO: 0x0008000,\n PUSHBUTTON: 0x0010000,\n COMBO: 0x0020000,\n EDIT: 0x0040000,\n SORT: 0x0080000,\n FILESELECT: 0x0100000,\n MULTISELECT: 0x0200000,\n DONOTSPELLCHECK: 0x0400000,\n DONOTSCROLL: 0x0800000,\n COMB: 0x1000000,\n RICHTEXT: 0x2000000,\n RADIOSINUNISON: 0x2000000,\n COMMITONSELCHANGE: 0x4000000,\n};\n\nconst AnnotationBorderStyleType = {\n SOLID: 1,\n DASHED: 2,\n BEVELED: 3,\n INSET: 4,\n UNDERLINE: 5,\n};\n\nconst AnnotationActionEventType = {\n E: \"Mouse Enter\",\n X: \"Mouse Exit\",\n D: \"Mouse Down\",\n U: \"Mouse Up\",\n Fo: \"Focus\",\n Bl: \"Blur\",\n PO: \"PageOpen\",\n PC: \"PageClose\",\n PV: \"PageVisible\",\n PI: \"PageInvisible\",\n K: \"Keystroke\",\n F: \"Format\",\n V: \"Validate\",\n C: \"Calculate\",\n};\n\nconst DocumentActionEventType = {\n WC: \"WillClose\",\n WS: \"WillSave\",\n DS: \"DidSave\",\n WP: \"WillPrint\",\n DP: \"DidPrint\",\n};\n\nconst PageActionEventType = {\n O: \"PageOpen\",\n C: \"PageClose\",\n};\n\nconst VerbosityLevel = {\n ERRORS: 0,\n WARNINGS: 1,\n INFOS: 5,\n};\n\nconst CMapCompressionType = {\n NONE: 0,\n BINARY: 1,\n};\n\n// All the possible operations for an operator list.\nconst OPS = {\n // Intentionally start from 1 so it is easy to spot bad operators that will be\n // 0's.\n // PLEASE NOTE: We purposely keep any removed operators commented out, since\n // re-numbering the list would risk breaking third-party users.\n dependency: 1,\n setLineWidth: 2,\n setLineCap: 3,\n setLineJoin: 4,\n setMiterLimit: 5,\n setDash: 6,\n setRenderingIntent: 7,\n setFlatness: 8,\n setGState: 9,\n save: 10,\n restore: 11,\n transform: 12,\n moveTo: 13,\n lineTo: 14,\n curveTo: 15,\n curveTo2: 16,\n curveTo3: 17,\n closePath: 18,\n rectangle: 19,\n stroke: 20,\n closeStroke: 21,\n fill: 22,\n eoFill: 23,\n fillStroke: 24,\n eoFillStroke: 25,\n closeFillStroke: 26,\n closeEOFillStroke: 27,\n endPath: 28,\n clip: 29,\n eoClip: 30,\n beginText: 31,\n endText: 32,\n setCharSpacing: 33,\n setWordSpacing: 34,\n setHScale: 35,\n setLeading: 36,\n setFont: 37,\n setTextRenderingMode: 38,\n setTextRise: 39,\n moveText: 40,\n setLeadingMoveText: 41,\n setTextMatrix: 42,\n nextLine: 43,\n showText: 44,\n showSpacedText: 45,\n nextLineShowText: 46,\n nextLineSetSpacingShowText: 47,\n setCharWidth: 48,\n setCharWidthAndBounds: 49,\n setStrokeColorSpace: 50,\n setFillColorSpace: 51,\n setStrokeColor: 52,\n setStrokeColorN: 53,\n setFillColor: 54,\n setFillColorN: 55,\n setStrokeGray: 56,\n setFillGray: 57,\n setStrokeRGBColor: 58,\n setFillRGBColor: 59,\n setStrokeCMYKColor: 60,\n setFillCMYKColor: 61,\n shadingFill: 62,\n beginInlineImage: 63,\n beginImageData: 64,\n endInlineImage: 65,\n paintXObject: 66,\n markPoint: 67,\n markPointProps: 68,\n beginMarkedContent: 69,\n beginMarkedContentProps: 70,\n endMarkedContent: 71,\n beginCompat: 72,\n endCompat: 73,\n paintFormXObjectBegin: 74,\n paintFormXObjectEnd: 75,\n beginGroup: 76,\n endGroup: 77,\n // beginAnnotations: 78,\n // endAnnotations: 79,\n beginAnnotation: 80,\n endAnnotation: 81,\n // paintJpegXObject: 82,\n paintImageMaskXObject: 83,\n paintImageMaskXObjectGroup: 84,\n paintImageXObject: 85,\n paintInlineImageXObject: 86,\n paintInlineImageXObjectGroup: 87,\n paintImageXObjectRepeat: 88,\n paintImageMaskXObjectRepeat: 89,\n paintSolidColorImageMask: 90,\n constructPath: 91,\n setStrokeTransparent: 92,\n setFillTransparent: 93,\n};\n\nconst PasswordResponses = {\n NEED_PASSWORD: 1,\n INCORRECT_PASSWORD: 2,\n};\n\nlet verbosity = VerbosityLevel.WARNINGS;\n\nfunction setVerbosityLevel(level) {\n if (Number.isInteger(level)) {\n verbosity = level;\n }\n}\n\nfunction getVerbosityLevel() {\n return verbosity;\n}\n\n// A notice for devs. These are good for things that are helpful to devs, such\n// as warning that Workers were disabled, which is important to devs but not\n// end users.\nfunction info(msg) {\n if (verbosity >= VerbosityLevel.INFOS) {\n console.log(`Info: ${msg}`);\n }\n}\n\n// Non-fatal warnings.\nfunction warn(msg) {\n if (verbosity >= VerbosityLevel.WARNINGS) {\n console.log(`Warning: ${msg}`);\n }\n}\n\nfunction unreachable(msg) {\n throw new Error(msg);\n}\n\nfunction assert(cond, msg) {\n if (!cond) {\n unreachable(msg);\n }\n}\n\n// Checks if URLs use one of the allowed protocols, e.g. to avoid XSS.\nfunction _isValidProtocol(url) {\n switch (url?.protocol) {\n case \"http:\":\n case \"https:\":\n case \"ftp:\":\n case \"mailto:\":\n case \"tel:\":\n return true;\n default:\n return false;\n }\n}\n\n/**\n * Attempts to create a valid absolute URL.\n *\n * @param {URL|string} url - An absolute, or relative, URL.\n * @param {URL|string} [baseUrl] - An absolute URL.\n * @param {Object} [options]\n * @returns Either a valid {URL}, or `null` otherwise.\n */\nfunction createValidAbsoluteUrl(url, baseUrl = null, options = null) {\n if (!url) {\n return null;\n }\n try {\n if (options && typeof url === \"string\") {\n // Let URLs beginning with \"www.\" default to using the \"http://\" protocol.\n if (options.addDefaultProtocol && url.startsWith(\"www.\")) {\n const dots = url.match(/\\./g);\n // Avoid accidentally matching a *relative* URL pointing to a file named\n // e.g. \"www.pdf\" or similar.\n if (dots?.length >= 2) {\n url = `http://${url}`;\n }\n }\n\n // According to ISO 32000-1:2008, section 12.6.4.7, URIs should be encoded\n // in 7-bit ASCII. Some bad PDFs use UTF-8 encoding; see bug 1122280.\n if (options.tryConvertEncoding) {\n try {\n url = stringToUTF8String(url);\n } catch {}\n }\n }\n\n const absoluteUrl = baseUrl ? new URL(url, baseUrl) : new URL(url);\n if (_isValidProtocol(absoluteUrl)) {\n return absoluteUrl;\n }\n } catch {\n /* `new URL()` will throw on incorrect data. */\n }\n return null;\n}\n\nfunction shadow(obj, prop, value, nonSerializable = false) {\n if (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) {\n assert(\n prop in obj,\n `shadow: Property \"${prop && prop.toString()}\" not found in object.`\n );\n }\n Object.defineProperty(obj, prop, {\n value,\n enumerable: !nonSerializable,\n configurable: true,\n writable: false,\n });\n return value;\n}\n\n/**\n * @type {any}\n */\nconst BaseException = (function BaseExceptionClosure() {\n // eslint-disable-next-line no-shadow\n function BaseException(message, name) {\n if (\n (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) &&\n this.constructor === BaseException\n ) {\n unreachable(\"Cannot initialize BaseException.\");\n }\n this.message = message;\n this.name = name;\n }\n BaseException.prototype = new Error();\n BaseException.constructor = BaseException;\n\n return BaseException;\n})();\n\nclass PasswordException extends BaseException {\n constructor(msg, code) {\n super(msg, \"PasswordException\");\n this.code = code;\n }\n}\n\nclass UnknownErrorException extends BaseException {\n constructor(msg, details) {\n super(msg, \"UnknownErrorException\");\n this.details = details;\n }\n}\n\nclass InvalidPDFException extends BaseException {\n constructor(msg) {\n super(msg, \"InvalidPDFException\");\n }\n}\n\nclass MissingPDFException extends BaseException {\n constructor(msg) {\n super(msg, \"MissingPDFException\");\n }\n}\n\nclass UnexpectedResponseException extends BaseException {\n constructor(msg, status) {\n super(msg, \"UnexpectedResponseException\");\n this.status = status;\n }\n}\n\n/**\n * Error caused during parsing PDF data.\n */\nclass FormatError extends BaseException {\n constructor(msg) {\n super(msg, \"FormatError\");\n }\n}\n\n/**\n * Error used to indicate task cancellation.\n */\nclass AbortException extends BaseException {\n constructor(msg) {\n super(msg, \"AbortException\");\n }\n}\n\nfunction bytesToString(bytes) {\n if (typeof bytes !== \"object\" || bytes?.length === undefined) {\n unreachable(\"Invalid argument for bytesToString\");\n }\n const length = bytes.length;\n const MAX_ARGUMENT_COUNT = 8192;\n if (length < MAX_ARGUMENT_COUNT) {\n return String.fromCharCode.apply(null, bytes);\n }\n const strBuf = [];\n for (let i = 0; i < length; i += MAX_ARGUMENT_COUNT) {\n const chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);\n const chunk = bytes.subarray(i, chunkEnd);\n strBuf.push(String.fromCharCode.apply(null, chunk));\n }\n return strBuf.join(\"\");\n}\n\nfunction stringToBytes(str) {\n if (typeof str !== \"string\") {\n unreachable(\"Invalid argument for stringToBytes\");\n }\n const length = str.length;\n const bytes = new Uint8Array(length);\n for (let i = 0; i < length; ++i) {\n bytes[i] = str.charCodeAt(i) & 0xff;\n }\n return bytes;\n}\n\nfunction string32(value) {\n if (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) {\n assert(\n typeof value === \"number\" && Math.abs(value) < 2 ** 32,\n `string32: Unexpected input \"${value}\".`\n );\n }\n return String.fromCharCode(\n (value >> 24) & 0xff,\n (value >> 16) & 0xff,\n (value >> 8) & 0xff,\n value & 0xff\n );\n}\n\nfunction objectSize(obj) {\n return Object.keys(obj).length;\n}\n\n// Ensure that the returned Object has a `null` prototype; hence why\n// `Object.fromEntries(...)` is not used.\nfunction objectFromMap(map) {\n const obj = Object.create(null);\n for (const [key, value] of map) {\n obj[key] = value;\n }\n return obj;\n}\n\n// Checks the endianness of the platform.\nfunction isLittleEndian() {\n const buffer8 = new Uint8Array(4);\n buffer8[0] = 1;\n const view32 = new Uint32Array(buffer8.buffer, 0, 1);\n return view32[0] === 1;\n}\n\n// Checks if it's possible to eval JS expressions.\nfunction isEvalSupported() {\n try {\n new Function(\"\"); // eslint-disable-line no-new, no-new-func\n return true;\n } catch {\n return false;\n }\n}\n\nclass FeatureTest {\n static get isLittleEndian() {\n return shadow(this, \"isLittleEndian\", isLittleEndian());\n }\n\n static get isEvalSupported() {\n return shadow(this, \"isEvalSupported\", isEvalSupported());\n }\n\n static get isOffscreenCanvasSupported() {\n return shadow(\n this,\n \"isOffscreenCanvasSupported\",\n typeof OffscreenCanvas !== \"undefined\"\n );\n }\n\n static get platform() {\n if (\n (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) ||\n (typeof navigator !== \"undefined\" &&\n typeof navigator?.platform === \"string\")\n ) {\n return shadow(this, \"platform\", {\n isMac: navigator.platform.includes(\"Mac\"),\n });\n }\n return shadow(this, \"platform\", { isMac: false });\n }\n\n static get isCSSRoundSupported() {\n return shadow(\n this,\n \"isCSSRoundSupported\",\n globalThis.CSS?.supports?.(\"width: round(1.5px, 1px)\")\n );\n }\n}\n\nconst hexNumbers = Array.from(Array(256).keys(), n =>\n n.toString(16).padStart(2, \"0\")\n);\n\nclass Util {\n static makeHexColor(r, g, b) {\n return `#${hexNumbers[r]}${hexNumbers[g]}${hexNumbers[b]}`;\n }\n\n // Apply a scaling matrix to some min/max values.\n // If a scaling factor is negative then min and max must be\n // swapped.\n static scaleMinMax(transform, minMax) {\n let temp;\n if (transform[0]) {\n if (transform[0] < 0) {\n temp = minMax[0];\n minMax[0] = minMax[2];\n minMax[2] = temp;\n }\n minMax[0] *= transform[0];\n minMax[2] *= transform[0];\n\n if (transform[3] < 0) {\n temp = minMax[1];\n minMax[1] = minMax[3];\n minMax[3] = temp;\n }\n minMax[1] *= transform[3];\n minMax[3] *= transform[3];\n } else {\n temp = minMax[0];\n minMax[0] = minMax[1];\n minMax[1] = temp;\n temp = minMax[2];\n minMax[2] = minMax[3];\n minMax[3] = temp;\n\n if (transform[1] < 0) {\n temp = minMax[1];\n minMax[1] = minMax[3];\n minMax[3] = temp;\n }\n minMax[1] *= transform[1];\n minMax[3] *= transform[1];\n\n if (transform[2] < 0) {\n temp = minMax[0];\n minMax[0] = minMax[2];\n minMax[2] = temp;\n }\n minMax[0] *= transform[2];\n minMax[2] *= transform[2];\n }\n minMax[0] += transform[4];\n minMax[1] += transform[5];\n minMax[2] += transform[4];\n minMax[3] += transform[5];\n }\n\n // Concatenates two transformation matrices together and returns the result.\n static transform(m1, m2) {\n return [\n m1[0] * m2[0] + m1[2] * m2[1],\n m1[1] * m2[0] + m1[3] * m2[1],\n m1[0] * m2[2] + m1[2] * m2[3],\n m1[1] * m2[2] + m1[3] * m2[3],\n m1[0] * m2[4] + m1[2] * m2[5] + m1[4],\n m1[1] * m2[4] + m1[3] * m2[5] + m1[5],\n ];\n }\n\n // For 2d affine transforms\n static applyTransform(p, m) {\n const xt = p[0] * m[0] + p[1] * m[2] + m[4];\n const yt = p[0] * m[1] + p[1] * m[3] + m[5];\n return [xt, yt];\n }\n\n static applyInverseTransform(p, m) {\n const d = m[0] * m[3] - m[1] * m[2];\n const xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;\n const yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;\n return [xt, yt];\n }\n\n // Applies the transform to the rectangle and finds the minimum axially\n // aligned bounding box.\n static getAxialAlignedBoundingBox(r, m) {\n const p1 = this.applyTransform(r, m);\n const p2 = this.applyTransform(r.slice(2, 4), m);\n const p3 = this.applyTransform([r[0], r[3]], m);\n const p4 = this.applyTransform([r[2], r[1]], m);\n return [\n Math.min(p1[0], p2[0], p3[0], p4[0]),\n Math.min(p1[1], p2[1], p3[1], p4[1]),\n Math.max(p1[0], p2[0], p3[0], p4[0]),\n Math.max(p1[1], p2[1], p3[1], p4[1]),\n ];\n }\n\n static inverseTransform(m) {\n const d = m[0] * m[3] - m[1] * m[2];\n return [\n m[3] / d,\n -m[1] / d,\n -m[2] / d,\n m[0] / d,\n (m[2] * m[5] - m[4] * m[3]) / d,\n (m[4] * m[1] - m[5] * m[0]) / d,\n ];\n }\n\n // This calculation uses Singular Value Decomposition.\n // The SVD can be represented with formula A = USV. We are interested in the\n // matrix S here because it represents the scale values.\n static singularValueDecompose2dScale(m) {\n const transpose = [m[0], m[2], m[1], m[3]];\n\n // Multiply matrix m with its transpose.\n const a = m[0] * transpose[0] + m[1] * transpose[2];\n const b = m[0] * transpose[1] + m[1] * transpose[3];\n const c = m[2] * transpose[0] + m[3] * transpose[2];\n const d = m[2] * transpose[1] + m[3] * transpose[3];\n\n // Solve the second degree polynomial to get roots.\n const first = (a + d) / 2;\n const second = Math.sqrt((a + d) ** 2 - 4 * (a * d - c * b)) / 2;\n const sx = first + second || 1;\n const sy = first - second || 1;\n\n // Scale values are the square roots of the eigenvalues.\n return [Math.sqrt(sx), Math.sqrt(sy)];\n }\n\n // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)\n // For coordinate systems whose origin lies in the bottom-left, this\n // means normalization to (BL,TR) ordering. For systems with origin in the\n // top-left, this means (TL,BR) ordering.\n static normalizeRect(rect) {\n const r = rect.slice(0); // clone rect\n if (rect[0] > rect[2]) {\n r[0] = rect[2];\n r[2] = rect[0];\n }\n if (rect[1] > rect[3]) {\n r[1] = rect[3];\n r[3] = rect[1];\n }\n return r;\n }\n\n // Returns a rectangle [x1, y1, x2, y2] corresponding to the\n // intersection of rect1 and rect2. If no intersection, returns 'null'\n // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]\n static intersect(rect1, rect2) {\n const xLow = Math.max(\n Math.min(rect1[0], rect1[2]),\n Math.min(rect2[0], rect2[2])\n );\n const xHigh = Math.min(\n Math.max(rect1[0], rect1[2]),\n Math.max(rect2[0], rect2[2])\n );\n if (xLow > xHigh) {\n return null;\n }\n const yLow = Math.max(\n Math.min(rect1[1], rect1[3]),\n Math.min(rect2[1], rect2[3])\n );\n const yHigh = Math.min(\n Math.max(rect1[1], rect1[3]),\n Math.max(rect2[1], rect2[3])\n );\n if (yLow > yHigh) {\n return null;\n }\n\n return [xLow, yLow, xHigh, yHigh];\n }\n\n static #getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, t, minMax) {\n if (t <= 0 || t >= 1) {\n return;\n }\n const mt = 1 - t;\n const tt = t * t;\n const ttt = tt * t;\n const x = mt * (mt * (mt * x0 + 3 * t * x1) + 3 * tt * x2) + ttt * x3;\n const y = mt * (mt * (mt * y0 + 3 * t * y1) + 3 * tt * y2) + ttt * y3;\n minMax[0] = Math.min(minMax[0], x);\n minMax[1] = Math.min(minMax[1], y);\n minMax[2] = Math.max(minMax[2], x);\n minMax[3] = Math.max(minMax[3], y);\n }\n\n static #getExtremum(x0, x1, x2, x3, y0, y1, y2, y3, a, b, c, minMax) {\n if (Math.abs(a) < 1e-12) {\n if (Math.abs(b) >= 1e-12) {\n this.#getExtremumOnCurve(\n x0,\n x1,\n x2,\n x3,\n y0,\n y1,\n y2,\n y3,\n -c / b,\n minMax\n );\n }\n return;\n }\n\n const delta = b ** 2 - 4 * c * a;\n if (delta < 0) {\n return;\n }\n const sqrtDelta = Math.sqrt(delta);\n const a2 = 2 * a;\n this.#getExtremumOnCurve(\n x0,\n x1,\n x2,\n x3,\n y0,\n y1,\n y2,\n y3,\n (-b + sqrtDelta) / a2,\n minMax\n );\n this.#getExtremumOnCurve(\n x0,\n x1,\n x2,\n x3,\n y0,\n y1,\n y2,\n y3,\n (-b - sqrtDelta) / a2,\n minMax\n );\n }\n\n // From https://github.com/adobe-webplatform/Snap.svg/blob/b365287722a72526000ac4bfcf0ce4cac2faa015/src/path.js#L852\n static bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3, minMax) {\n if (minMax) {\n minMax[0] = Math.min(minMax[0], x0, x3);\n minMax[1] = Math.min(minMax[1], y0, y3);\n minMax[2] = Math.max(minMax[2], x0, x3);\n minMax[3] = Math.max(minMax[3], y0, y3);\n } else {\n minMax = [\n Math.min(x0, x3),\n Math.min(y0, y3),\n Math.max(x0, x3),\n Math.max(y0, y3),\n ];\n }\n this.#getExtremum(\n x0,\n x1,\n x2,\n x3,\n y0,\n y1,\n y2,\n y3,\n 3 * (-x0 + 3 * (x1 - x2) + x3),\n 6 * (x0 - 2 * x1 + x2),\n 3 * (x1 - x0),\n minMax\n );\n this.#getExtremum(\n x0,\n x1,\n x2,\n x3,\n y0,\n y1,\n y2,\n y3,\n 3 * (-y0 + 3 * (y1 - y2) + y3),\n 6 * (y0 - 2 * y1 + y2),\n 3 * (y1 - y0),\n minMax\n );\n return minMax;\n }\n}\n\nconst PDFStringTranslateTable = [\n 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,\n 0x2c7, 0x2c6, 0x2d9, 0x2dd, 0x2db, 0x2da, 0x2dc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 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,\n 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,\n 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,\n 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x192,\n 0x2044, 0x2039, 0x203a, 0x2212, 0x2030, 0x201e, 0x201c, 0x201d, 0x2018,\n 0x2019, 0x201a, 0x2122, 0xfb01, 0xfb02, 0x141, 0x152, 0x160, 0x178, 0x17d,\n 0x131, 0x142, 0x153, 0x161, 0x17e, 0, 0x20ac,\n];\n\nfunction stringToPDFString(str) {\n // See section 7.9.2.2 Text String Type.\n // The string can contain some language codes bracketed with 0x0b,\n // so we must remove them.\n if (str[0] >= \"\\xEF\") {\n let encoding;\n if (str[0] === \"\\xFE\" && str[1] === \"\\xFF\") {\n encoding = \"utf-16be\";\n if (str.length % 2 === 1) {\n str = str.slice(0, -1);\n }\n } else if (str[0] === \"\\xFF\" && str[1] === \"\\xFE\") {\n encoding = \"utf-16le\";\n if (str.length % 2 === 1) {\n str = str.slice(0, -1);\n }\n } else if (str[0] === \"\\xEF\" && str[1] === \"\\xBB\" && str[2] === \"\\xBF\") {\n encoding = \"utf-8\";\n }\n\n if (encoding) {\n try {\n const decoder = new TextDecoder(encoding, { fatal: true });\n const buffer = stringToBytes(str);\n const decoded = decoder.decode(buffer);\n if (!decoded.includes(\"\\x1b\")) {\n return decoded;\n }\n return decoded.replaceAll(/\\x1b[^\\x1b]*(?:\\x1b|$)/g, \"\");\n } catch (ex) {\n warn(`stringToPDFString: \"${ex}\".`);\n }\n }\n }\n // ISO Latin 1\n const strBuf = [];\n for (let i = 0, ii = str.length; i < ii; i++) {\n const charCode = str.charCodeAt(i);\n if (charCode === 0x1b) {\n // eslint-disable-next-line no-empty\n while (++i < ii && str.charCodeAt(i) !== 0x1b) {}\n continue;\n }\n const code = PDFStringTranslateTable[charCode];\n strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));\n }\n return strBuf.join(\"\");\n}\n\nfunction stringToUTF8String(str) {\n return decodeURIComponent(escape(str));\n}\n\nfunction utf8StringToString(str) {\n return unescape(encodeURIComponent(str));\n}\n\nfunction isArrayEqual(arr1, arr2) {\n if (arr1.length !== arr2.length) {\n return false;\n }\n for (let i = 0, ii = arr1.length; i < ii; i++) {\n if (arr1[i] !== arr2[i]) {\n return false;\n }\n }\n return true;\n}\n\nfunction getModificationDate(date = new Date()) {\n const buffer = [\n date.getUTCFullYear().toString(),\n (date.getUTCMonth() + 1).toString().padStart(2, \"0\"),\n date.getUTCDate().toString().padStart(2, \"0\"),\n date.getUTCHours().toString().padStart(2, \"0\"),\n date.getUTCMinutes().toString().padStart(2, \"0\"),\n date.getUTCSeconds().toString().padStart(2, \"0\"),\n ];\n\n return buffer.join(\"\");\n}\n\nlet NormalizeRegex = null;\nlet NormalizationMap = null;\nfunction normalizeUnicode(str) {\n if (!NormalizeRegex) {\n // In order to generate the following regex:\n // - create a PDF containing all the chars in the range 0000-FFFF with\n // a NFKC which is different of the char.\n // - copy and paste all those chars and get the ones where NFKC is\n // required.\n // It appears that most the chars here contain some ligatures.\n NormalizeRegex =\n /([\\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;\n NormalizationMap = new Map([[\"ſt\", \"ſt\"]]);\n }\n return str.replaceAll(NormalizeRegex, (_, p1, p2) =>\n p1 ? p1.normalize(\"NFKC\") : NormalizationMap.get(p2)\n );\n}\n\nfunction getUuid() {\n if (\n (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) ||\n (typeof crypto !== \"undefined\" && typeof crypto?.randomUUID === \"function\")\n ) {\n return crypto.randomUUID();\n }\n const buf = new Uint8Array(32);\n if (\n typeof crypto !== \"undefined\" &&\n typeof crypto?.getRandomValues === \"function\"\n ) {\n crypto.getRandomValues(buf);\n } else {\n for (let i = 0; i < 32; i++) {\n buf[i] = Math.floor(Math.random() * 255);\n }\n }\n return bytesToString(buf);\n}\n\nconst AnnotationPrefix = \"pdfjs_internal_id_\";\n\nconst FontRenderOps = {\n BEZIER_CURVE_TO: 0,\n MOVE_TO: 1,\n LINE_TO: 2,\n QUADRATIC_CURVE_TO: 3,\n RESTORE: 4,\n SAVE: 5,\n SCALE: 6,\n TRANSFORM: 7,\n TRANSLATE: 8,\n};\n\nexport {\n AbortException,\n AnnotationActionEventType,\n AnnotationBorderStyleType,\n AnnotationEditorParamsType,\n AnnotationEditorPrefix,\n AnnotationEditorType,\n AnnotationFieldFlag,\n AnnotationFlag,\n AnnotationMode,\n AnnotationPrefix,\n AnnotationReplyType,\n AnnotationType,\n assert,\n BaseException,\n BASELINE_FACTOR,\n bytesToString,\n CMapCompressionType,\n createValidAbsoluteUrl,\n DocumentActionEventType,\n FeatureTest,\n FONT_IDENTITY_MATRIX,\n FontRenderOps,\n FormatError,\n getModificationDate,\n getUuid,\n getVerbosityLevel,\n IDENTITY_MATRIX,\n ImageKind,\n info,\n InvalidPDFException,\n isArrayEqual,\n isNodeJS,\n LINE_DESCENT_FACTOR,\n LINE_FACTOR,\n MAX_IMAGE_SIZE_TO_CACHE,\n MissingPDFException,\n normalizeUnicode,\n objectFromMap,\n objectSize,\n OPS,\n PageActionEventType,\n PasswordException,\n PasswordResponses,\n PermissionFlag,\n RenderingIntentFlag,\n setVerbosityLevel,\n shadow,\n string32,\n stringToBytes,\n stringToPDFString,\n stringToUTF8String,\n TextRenderingMode,\n UnexpectedResponseException,\n UnknownErrorException,\n unreachable,\n utf8StringToString,\n Util,\n VerbosityLevel,\n warn,\n};\n","/* Copyright 2015 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CMapCompressionType, unreachable } from \"../shared/util.js\";\n\nclass BaseFilterFactory {\n constructor() {\n if (\n (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) &&\n this.constructor === BaseFilterFactory\n ) {\n unreachable(\"Cannot initialize BaseFilterFactory.\");\n }\n }\n\n addFilter(maps) {\n return \"none\";\n }\n\n addHCMFilter(fgColor, bgColor) {\n return \"none\";\n }\n\n addAlphaFilter(map) {\n return \"none\";\n }\n\n addLuminosityFilter(map) {\n return \"none\";\n }\n\n addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) {\n return \"none\";\n }\n\n destroy(keepHCM = false) {}\n}\n\nclass BaseCanvasFactory {\n #enableHWA = false;\n\n constructor({ enableHWA = false } = {}) {\n if (\n (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) &&\n this.constructor === BaseCanvasFactory\n ) {\n unreachable(\"Cannot initialize BaseCanvasFactory.\");\n }\n this.#enableHWA = enableHWA;\n }\n\n create(width, height) {\n if (width <= 0 || height <= 0) {\n throw new Error(\"Invalid canvas size\");\n }\n const canvas = this._createCanvas(width, height);\n return {\n canvas,\n context: canvas.getContext(\"2d\", {\n willReadFrequently: !this.#enableHWA,\n }),\n };\n }\n\n reset(canvasAndContext, width, height) {\n if (!canvasAndContext.canvas) {\n throw new Error(\"Canvas is not specified\");\n }\n if (width <= 0 || height <= 0) {\n throw new Error(\"Invalid canvas size\");\n }\n canvasAndContext.canvas.width = width;\n canvasAndContext.canvas.height = height;\n }\n\n destroy(canvasAndContext) {\n if (!canvasAndContext.canvas) {\n throw new Error(\"Canvas is not specified\");\n }\n // Zeroing the width and height cause Firefox to release graphics\n // resources immediately, which can greatly reduce memory consumption.\n canvasAndContext.canvas.width = 0;\n canvasAndContext.canvas.height = 0;\n canvasAndContext.canvas = null;\n canvasAndContext.context = null;\n }\n\n /**\n * @ignore\n */\n _createCanvas(width, height) {\n unreachable(\"Abstract method `_createCanvas` called.\");\n }\n}\n\nclass BaseCMapReaderFactory {\n constructor({ baseUrl = null, isCompressed = true }) {\n if (\n (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) &&\n this.constructor === BaseCMapReaderFactory\n ) {\n unreachable(\"Cannot initialize BaseCMapReaderFactory.\");\n }\n this.baseUrl = baseUrl;\n this.isCompressed = isCompressed;\n }\n\n async fetch({ name }) {\n if (!this.baseUrl) {\n throw new Error(\n \"Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.\"\n );\n }\n if (!name) {\n throw new Error(\"CMap name must be specified.\");\n }\n const url = this.baseUrl + name + (this.isCompressed ? \".bcmap\" : \"\");\n const compressionType = this.isCompressed\n ? CMapCompressionType.BINARY\n : CMapCompressionType.NONE;\n\n return this._fetchData(url, compressionType).catch(reason => {\n throw new Error(\n `Unable to load ${this.isCompressed ? \"binary \" : \"\"}CMap at: ${url}`\n );\n });\n }\n\n /**\n * @ignore\n */\n _fetchData(url, compressionType) {\n unreachable(\"Abstract method `_fetchData` called.\");\n }\n}\n\nclass BaseStandardFontDataFactory {\n constructor({ baseUrl = null }) {\n if (\n (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) &&\n this.constructor === BaseStandardFontDataFactory\n ) {\n unreachable(\"Cannot initialize BaseStandardFontDataFactory.\");\n }\n this.baseUrl = baseUrl;\n }\n\n async fetch({ filename }) {\n if (!this.baseUrl) {\n throw new Error(\n \"Ensure that the `standardFontDataUrl` API parameter is provided.\"\n );\n }\n if (!filename) {\n throw new Error(\"Font filename must be specified.\");\n }\n const url = `${this.baseUrl}${filename}`;\n\n return this._fetchData(url).catch(reason => {\n throw new Error(`Unable to load font data at: ${url}`);\n });\n }\n\n /**\n * @ignore\n */\n _fetchData(url) {\n unreachable(\"Abstract method `_fetchData` called.\");\n }\n}\n\nclass BaseSVGFactory {\n constructor() {\n if (\n (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) &&\n this.constructor === BaseSVGFactory\n ) {\n unreachable(\"Cannot initialize BaseSVGFactory.\");\n }\n }\n\n create(width, height, skipDimensions = false) {\n if (width <= 0 || height <= 0) {\n throw new Error(\"Invalid SVG dimensions\");\n }\n const svg = this._createSVG(\"svg:svg\");\n svg.setAttribute(\"version\", \"1.1\");\n\n if (!skipDimensions) {\n svg.setAttribute(\"width\", `${width}px`);\n svg.setAttribute(\"height\", `${height}px`);\n }\n\n svg.setAttribute(\"preserveAspectRatio\", \"none\");\n svg.setAttribute(\"viewBox\", `0 0 ${width} ${height}`);\n\n return svg;\n }\n\n createElement(type) {\n if (typeof type !== \"string\") {\n throw new Error(\"Invalid SVG element type\");\n }\n return this._createSVG(type);\n }\n\n /**\n * @ignore\n */\n _createSVG(type) {\n unreachable(\"Abstract method `_createSVG` called.\");\n }\n}\n\nexport {\n BaseCanvasFactory,\n BaseCMapReaderFactory,\n BaseFilterFactory,\n BaseStandardFontDataFactory,\n BaseSVGFactory,\n};\n","/* Copyright 2015 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n BaseCanvasFactory,\n BaseCMapReaderFactory,\n BaseFilterFactory,\n BaseStandardFontDataFactory,\n BaseSVGFactory,\n} from \"./base_factory.js\";\nimport {\n BaseException,\n FeatureTest,\n shadow,\n stringToBytes,\n Util,\n warn,\n} from \"../shared/util.js\";\n\nconst SVG_NS = \"http://www.w3.org/2000/svg\";\n\nclass PixelsPerInch {\n static CSS = 96.0;\n\n static PDF = 72.0;\n\n static PDF_TO_CSS_UNITS = this.CSS / this.PDF;\n}\n\n/**\n * FilterFactory aims to create some SVG filters we can use when drawing an\n * image (or whatever) on a canvas.\n * Filters aren't applied with ctx.putImageData because it just overwrites the\n * underlying pixels.\n * With these filters, it's possible for example to apply some transfer maps on\n * an image without the need to apply them on the pixel arrays: the renderer\n * does the magic for us.\n */\nclass DOMFilterFactory extends BaseFilterFactory {\n #baseUrl;\n\n #_cache;\n\n #_defs;\n\n #docId;\n\n #document;\n\n #_hcmCache;\n\n #id = 0;\n\n constructor({ docId, ownerDocument = globalThis.document } = {}) {\n super();\n this.#docId = docId;\n this.#document = ownerDocument;\n }\n\n get #cache() {\n return (this.#_cache ||= new Map());\n }\n\n get #hcmCache() {\n return (this.#_hcmCache ||= new Map());\n }\n\n get #defs() {\n if (!this.#_defs) {\n const div = this.#document.createElement(\"div\");\n const { style } = div;\n style.visibility = \"hidden\";\n style.contain = \"strict\";\n style.width = style.height = 0;\n style.position = \"absolute\";\n style.top = style.left = 0;\n style.zIndex = -1;\n\n const svg = this.#document.createElementNS(SVG_NS, \"svg\");\n svg.setAttribute(\"width\", 0);\n svg.setAttribute(\"height\", 0);\n this.#_defs = this.#document.createElementNS(SVG_NS, \"defs\");\n div.append(svg);\n svg.append(this.#_defs);\n this.#document.body.append(div);\n }\n return this.#_defs;\n }\n\n #createTables(maps) {\n if (maps.length === 1) {\n const mapR = maps[0];\n const buffer = new Array(256);\n for (let i = 0; i < 256; i++) {\n buffer[i] = mapR[i] / 255;\n }\n\n const table = buffer.join(\",\");\n return [table, table, table];\n }\n\n const [mapR, mapG, mapB] = maps;\n const bufferR = new Array(256);\n const bufferG = new Array(256);\n const bufferB = new Array(256);\n for (let i = 0; i < 256; i++) {\n bufferR[i] = mapR[i] / 255;\n bufferG[i] = mapG[i] / 255;\n bufferB[i] = mapB[i] / 255;\n }\n return [bufferR.join(\",\"), bufferG.join(\",\"), bufferB.join(\",\")];\n }\n\n #createUrl(id) {\n if (this.#baseUrl === undefined) {\n // Unless a ``-element is present a relative URL should work.\n this.#baseUrl = \"\";\n\n const url = this.#document.URL;\n if (url !== this.#document.baseURI) {\n if (isDataScheme(url)) {\n warn('#createUrl: ignore \"data:\"-URL for performance reasons.');\n } else {\n this.#baseUrl = url.split(\"#\", 1)[0];\n }\n }\n }\n return `url(${this.#baseUrl}#${id})`;\n }\n\n addFilter(maps) {\n if (!maps) {\n return \"none\";\n }\n\n // When a page is zoomed the page is re-drawn but the maps are likely\n // the same.\n let value = this.#cache.get(maps);\n if (value) {\n return value;\n }\n\n const [tableR, tableG, tableB] = this.#createTables(maps);\n const key = maps.length === 1 ? tableR : `${tableR}${tableG}${tableB}`;\n\n value = this.#cache.get(key);\n if (value) {\n this.#cache.set(maps, value);\n return value;\n }\n\n // We create a SVG filter: feComponentTransferElement\n // https://www.w3.org/TR/SVG11/filters.html#feComponentTransferElement\n\n const id = `g_${this.#docId}_transfer_map_${this.#id++}`;\n const url = this.#createUrl(id);\n this.#cache.set(maps, url);\n this.#cache.set(key, url);\n\n const filter = this.#createFilter(id);\n this.#addTransferMapConversion(tableR, tableG, tableB, filter);\n\n return url;\n }\n\n addHCMFilter(fgColor, bgColor) {\n const key = `${fgColor}-${bgColor}`;\n const filterName = \"base\";\n let info = this.#hcmCache.get(filterName);\n if (info?.key === key) {\n return info.url;\n }\n\n if (info) {\n info.filter?.remove();\n info.key = key;\n info.url = \"none\";\n info.filter = null;\n } else {\n info = {\n key,\n url: \"none\",\n filter: null,\n };\n this.#hcmCache.set(filterName, info);\n }\n\n if (!fgColor || !bgColor) {\n return info.url;\n }\n\n const fgRGB = this.#getRGB(fgColor);\n fgColor = Util.makeHexColor(...fgRGB);\n const bgRGB = this.#getRGB(bgColor);\n bgColor = Util.makeHexColor(...bgRGB);\n this.#defs.style.color = \"\";\n\n if (\n (fgColor === \"#000000\" && bgColor === \"#ffffff\") ||\n fgColor === bgColor\n ) {\n return info.url;\n }\n\n // https://developer.mozilla.org/en-US/docs/Web/Accessibility/Understanding_Colors_and_Luminance\n //\n // Relative luminance:\n // https://www.w3.org/TR/WCAG20/#relativeluminancedef\n //\n // We compute the rounded luminance of the default background color.\n // Then for every color in the pdf, if its rounded luminance is the\n // same as the background one then it's replaced by the new\n // background color else by the foreground one.\n const map = new Array(256);\n for (let i = 0; i <= 255; i++) {\n const x = i / 255;\n map[i] = x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;\n }\n const table = map.join(\",\");\n\n const id = `g_${this.#docId}_hcm_filter`;\n const filter = (info.filter = this.#createFilter(id));\n this.#addTransferMapConversion(table, table, table, filter);\n this.#addGrayConversion(filter);\n\n const getSteps = (c, n) => {\n const start = fgRGB[c] / 255;\n const end = bgRGB[c] / 255;\n const arr = new Array(n + 1);\n for (let i = 0; i <= n; i++) {\n arr[i] = start + (i / n) * (end - start);\n }\n return arr.join(\",\");\n };\n this.#addTransferMapConversion(\n getSteps(0, 5),\n getSteps(1, 5),\n getSteps(2, 5),\n filter\n );\n\n info.url = this.#createUrl(id);\n return info.url;\n }\n\n addAlphaFilter(map) {\n // When a page is zoomed the page is re-drawn but the maps are likely\n // the same.\n let value = this.#cache.get(map);\n if (value) {\n return value;\n }\n\n const [tableA] = this.#createTables([map]);\n const key = `alpha_${tableA}`;\n\n value = this.#cache.get(key);\n if (value) {\n this.#cache.set(map, value);\n return value;\n }\n\n const id = `g_${this.#docId}_alpha_map_${this.#id++}`;\n const url = this.#createUrl(id);\n this.#cache.set(map, url);\n this.#cache.set(key, url);\n\n const filter = this.#createFilter(id);\n this.#addTransferMapAlphaConversion(tableA, filter);\n\n return url;\n }\n\n addLuminosityFilter(map) {\n // When a page is zoomed the page is re-drawn but the maps are likely\n // the same.\n let value = this.#cache.get(map || \"luminosity\");\n if (value) {\n return value;\n }\n\n let tableA, key;\n if (map) {\n [tableA] = this.#createTables([map]);\n key = `luminosity_${tableA}`;\n } else {\n key = \"luminosity\";\n }\n\n value = this.#cache.get(key);\n if (value) {\n this.#cache.set(map, value);\n return value;\n }\n\n const id = `g_${this.#docId}_luminosity_map_${this.#id++}`;\n const url = this.#createUrl(id);\n this.#cache.set(map, url);\n this.#cache.set(key, url);\n\n const filter = this.#createFilter(id);\n this.#addLuminosityConversion(filter);\n if (map) {\n this.#addTransferMapAlphaConversion(tableA, filter);\n }\n\n return url;\n }\n\n addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) {\n const key = `${fgColor}-${bgColor}-${newFgColor}-${newBgColor}`;\n let info = this.#hcmCache.get(filterName);\n if (info?.key === key) {\n return info.url;\n }\n\n if (info) {\n info.filter?.remove();\n info.key = key;\n info.url = \"none\";\n info.filter = null;\n } else {\n info = {\n key,\n url: \"none\",\n filter: null,\n };\n this.#hcmCache.set(filterName, info);\n }\n\n if (!fgColor || !bgColor) {\n return info.url;\n }\n\n const [fgRGB, bgRGB] = [fgColor, bgColor].map(this.#getRGB.bind(this));\n let fgGray = Math.round(\n 0.2126 * fgRGB[0] + 0.7152 * fgRGB[1] + 0.0722 * fgRGB[2]\n );\n let bgGray = Math.round(\n 0.2126 * bgRGB[0] + 0.7152 * bgRGB[1] + 0.0722 * bgRGB[2]\n );\n let [newFgRGB, newBgRGB] = [newFgColor, newBgColor].map(\n this.#getRGB.bind(this)\n );\n if (bgGray < fgGray) {\n [fgGray, bgGray, newFgRGB, newBgRGB] = [\n bgGray,\n fgGray,\n newBgRGB,\n newFgRGB,\n ];\n }\n this.#defs.style.color = \"\";\n\n // Now we can create the filters to highlight some canvas parts.\n // The colors in the pdf will almost be Canvas and CanvasText, hence we\n // want to filter them to finally get Highlight and HighlightText.\n // Since we're in HCM the background color and the foreground color should\n // be really different when converted to grayscale (if they're not then it\n // means that we've a poor contrast). Once the canvas colors are converted\n // to grayscale we can easily map them on their new colors.\n // The grayscale step is important because if we've something like:\n // fgColor = #FF....\n // bgColor = #FF....\n // then we are enable to map the red component on the new red components\n // which can be different.\n\n const getSteps = (fg, bg, n) => {\n const arr = new Array(256);\n const step = (bgGray - fgGray) / n;\n const newStart = fg / 255;\n const newStep = (bg - fg) / (255 * n);\n let prev = 0;\n for (let i = 0; i <= n; i++) {\n const k = Math.round(fgGray + i * step);\n const value = newStart + i * newStep;\n for (let j = prev; j <= k; j++) {\n arr[j] = value;\n }\n prev = k + 1;\n }\n for (let i = prev; i < 256; i++) {\n arr[i] = arr[prev - 1];\n }\n return arr.join(\",\");\n };\n\n const id = `g_${this.#docId}_hcm_${filterName}_filter`;\n const filter = (info.filter = this.#createFilter(id));\n\n this.#addGrayConversion(filter);\n this.#addTransferMapConversion(\n getSteps(newFgRGB[0], newBgRGB[0], 5),\n getSteps(newFgRGB[1], newBgRGB[1], 5),\n getSteps(newFgRGB[2], newBgRGB[2], 5),\n filter\n );\n\n info.url = this.#createUrl(id);\n return info.url;\n }\n\n destroy(keepHCM = false) {\n if (keepHCM && this.#hcmCache.size !== 0) {\n return;\n }\n if (this.#_defs) {\n this.#_defs.parentNode.parentNode.remove();\n this.#_defs = null;\n }\n if (this.#_cache) {\n this.#_cache.clear();\n this.#_cache = null;\n }\n this.#id = 0;\n }\n\n #addLuminosityConversion(filter) {\n const feColorMatrix = this.#document.createElementNS(\n SVG_NS,\n \"feColorMatrix\"\n );\n feColorMatrix.setAttribute(\"type\", \"matrix\");\n feColorMatrix.setAttribute(\n \"values\",\n \"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0\"\n );\n filter.append(feColorMatrix);\n }\n\n #addGrayConversion(filter) {\n const feColorMatrix = this.#document.createElementNS(\n SVG_NS,\n \"feColorMatrix\"\n );\n feColorMatrix.setAttribute(\"type\", \"matrix\");\n feColorMatrix.setAttribute(\n \"values\",\n \"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\"\n );\n filter.append(feColorMatrix);\n }\n\n #createFilter(id) {\n const filter = this.#document.createElementNS(SVG_NS, \"filter\");\n filter.setAttribute(\"color-interpolation-filters\", \"sRGB\");\n filter.setAttribute(\"id\", id);\n this.#defs.append(filter);\n\n return filter;\n }\n\n #appendFeFunc(feComponentTransfer, func, table) {\n const feFunc = this.#document.createElementNS(SVG_NS, func);\n feFunc.setAttribute(\"type\", \"discrete\");\n feFunc.setAttribute(\"tableValues\", table);\n feComponentTransfer.append(feFunc);\n }\n\n #addTransferMapConversion(rTable, gTable, bTable, filter) {\n const feComponentTransfer = this.#document.createElementNS(\n SVG_NS,\n \"feComponentTransfer\"\n );\n filter.append(feComponentTransfer);\n this.#appendFeFunc(feComponentTransfer, \"feFuncR\", rTable);\n this.#appendFeFunc(feComponentTransfer, \"feFuncG\", gTable);\n this.#appendFeFunc(feComponentTransfer, \"feFuncB\", bTable);\n }\n\n #addTransferMapAlphaConversion(aTable, filter) {\n const feComponentTransfer = this.#document.createElementNS(\n SVG_NS,\n \"feComponentTransfer\"\n );\n filter.append(feComponentTransfer);\n this.#appendFeFunc(feComponentTransfer, \"feFuncA\", aTable);\n }\n\n #getRGB(color) {\n this.#defs.style.color = color;\n return getRGB(getComputedStyle(this.#defs).getPropertyValue(\"color\"));\n }\n}\n\nclass DOMCanvasFactory extends BaseCanvasFactory {\n constructor({ ownerDocument = globalThis.document, enableHWA = false } = {}) {\n super({ enableHWA });\n this._document = ownerDocument;\n }\n\n /**\n * @ignore\n */\n _createCanvas(width, height) {\n const canvas = this._document.createElement(\"canvas\");\n canvas.width = width;\n canvas.height = height;\n return canvas;\n }\n}\n\nasync function fetchData(url, type = \"text\") {\n if (\n (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) ||\n isValidFetchUrl(url, document.baseURI)\n ) {\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(response.statusText);\n }\n switch (type) {\n case \"arraybuffer\":\n return response.arrayBuffer();\n case \"blob\":\n return response.blob();\n case \"json\":\n return response.json();\n }\n return response.text();\n }\n\n // The Fetch API is not supported.\n return new Promise((resolve, reject) => {\n const request = new XMLHttpRequest();\n request.open(\"GET\", url, /* async = */ true);\n request.responseType = type;\n\n request.onreadystatechange = () => {\n if (request.readyState !== XMLHttpRequest.DONE) {\n return;\n }\n if (request.status === 200 || request.status === 0) {\n switch (type) {\n case \"arraybuffer\":\n case \"blob\":\n case \"json\":\n resolve(request.response);\n return;\n }\n resolve(request.responseText);\n return;\n }\n reject(new Error(request.statusText));\n };\n\n request.send(null);\n });\n}\n\nclass DOMCMapReaderFactory extends BaseCMapReaderFactory {\n /**\n * @ignore\n */\n _fetchData(url, compressionType) {\n return fetchData(\n url,\n /* type = */ this.isCompressed ? \"arraybuffer\" : \"text\"\n ).then(data => ({\n cMapData:\n data instanceof ArrayBuffer\n ? new Uint8Array(data)\n : stringToBytes(data),\n compressionType,\n }));\n }\n}\n\nclass DOMStandardFontDataFactory extends BaseStandardFontDataFactory {\n /**\n * @ignore\n */\n _fetchData(url) {\n return fetchData(url, /* type = */ \"arraybuffer\").then(\n data => new Uint8Array(data)\n );\n }\n}\n\nclass DOMSVGFactory extends BaseSVGFactory {\n /**\n * @ignore\n */\n _createSVG(type) {\n return document.createElementNS(SVG_NS, type);\n }\n}\n\n/**\n * @typedef {Object} PageViewportParameters\n * @property {Array} viewBox - The xMin, yMin, xMax and\n * yMax coordinates.\n * @property {number} scale - The scale of the viewport.\n * @property {number} rotation - The rotation, in degrees, of the viewport.\n * @property {number} [offsetX] - The horizontal, i.e. x-axis, offset. The\n * default value is `0`.\n * @property {number} [offsetY] - The vertical, i.e. y-axis, offset. The\n * default value is `0`.\n * @property {boolean} [dontFlip] - If true, the y-axis will not be flipped.\n * The default value is `false`.\n */\n\n/**\n * @typedef {Object} PageViewportCloneParameters\n * @property {number} [scale] - The scale, overriding the one in the cloned\n * viewport. The default value is `this.scale`.\n * @property {number} [rotation] - The rotation, in degrees, overriding the one\n * in the cloned viewport. The default value is `this.rotation`.\n * @property {number} [offsetX] - The horizontal, i.e. x-axis, offset.\n * The default value is `this.offsetX`.\n * @property {number} [offsetY] - The vertical, i.e. y-axis, offset.\n * The default value is `this.offsetY`.\n * @property {boolean} [dontFlip] - If true, the x-axis will not be flipped.\n * The default value is `false`.\n */\n\n/**\n * PDF page viewport created based on scale, rotation and offset.\n */\nclass PageViewport {\n /**\n * @param {PageViewportParameters}\n */\n constructor({\n viewBox,\n scale,\n rotation,\n offsetX = 0,\n offsetY = 0,\n dontFlip = false,\n }) {\n this.viewBox = viewBox;\n this.scale = scale;\n this.rotation = rotation;\n this.offsetX = offsetX;\n this.offsetY = offsetY;\n\n // creating transform to convert pdf coordinate system to the normal\n // canvas like coordinates taking in account scale and rotation\n const centerX = (viewBox[2] + viewBox[0]) / 2;\n const centerY = (viewBox[3] + viewBox[1]) / 2;\n let rotateA, rotateB, rotateC, rotateD;\n // Normalize the rotation, by clamping it to the [0, 360) range.\n rotation %= 360;\n if (rotation < 0) {\n rotation += 360;\n }\n switch (rotation) {\n case 180:\n rotateA = -1;\n rotateB = 0;\n rotateC = 0;\n rotateD = 1;\n break;\n case 90:\n rotateA = 0;\n rotateB = 1;\n rotateC = 1;\n rotateD = 0;\n break;\n case 270:\n rotateA = 0;\n rotateB = -1;\n rotateC = -1;\n rotateD = 0;\n break;\n case 0:\n rotateA = 1;\n rotateB = 0;\n rotateC = 0;\n rotateD = -1;\n break;\n default:\n throw new Error(\n \"PageViewport: Invalid rotation, must be a multiple of 90 degrees.\"\n );\n }\n\n if (dontFlip) {\n rotateC = -rotateC;\n rotateD = -rotateD;\n }\n\n let offsetCanvasX, offsetCanvasY;\n let width, height;\n if (rotateA === 0) {\n offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;\n offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;\n width = (viewBox[3] - viewBox[1]) * scale;\n height = (viewBox[2] - viewBox[0]) * scale;\n } else {\n offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;\n offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;\n width = (viewBox[2] - viewBox[0]) * scale;\n height = (viewBox[3] - viewBox[1]) * scale;\n }\n // creating transform for the following operations:\n // translate(-centerX, -centerY), rotate and flip vertically,\n // scale, and translate(offsetCanvasX, offsetCanvasY)\n this.transform = [\n rotateA * scale,\n rotateB * scale,\n rotateC * scale,\n rotateD * scale,\n offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,\n offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY,\n ];\n\n this.width = width;\n this.height = height;\n }\n\n /**\n * The original, un-scaled, viewport dimensions.\n * @type {Object}\n */\n get rawDims() {\n const { viewBox } = this;\n return shadow(this, \"rawDims\", {\n pageWidth: viewBox[2] - viewBox[0],\n pageHeight: viewBox[3] - viewBox[1],\n pageX: viewBox[0],\n pageY: viewBox[1],\n });\n }\n\n /**\n * Clones viewport, with optional additional properties.\n * @param {PageViewportCloneParameters} [params]\n * @returns {PageViewport} Cloned viewport.\n */\n clone({\n scale = this.scale,\n rotation = this.rotation,\n offsetX = this.offsetX,\n offsetY = this.offsetY,\n dontFlip = false,\n } = {}) {\n return new PageViewport({\n viewBox: this.viewBox.slice(),\n scale,\n rotation,\n offsetX,\n offsetY,\n dontFlip,\n });\n }\n\n /**\n * Converts PDF point to the viewport coordinates. For examples, useful for\n * converting PDF location into canvas pixel coordinates.\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @returns {Array} Array containing `x`- and `y`-coordinates of the\n * point in the viewport coordinate space.\n * @see {@link convertToPdfPoint}\n * @see {@link convertToViewportRectangle}\n */\n convertToViewportPoint(x, y) {\n return Util.applyTransform([x, y], this.transform);\n }\n\n /**\n * Converts PDF rectangle to the viewport coordinates.\n * @param {Array} rect - The xMin, yMin, xMax and yMax coordinates.\n * @returns {Array} Array containing corresponding coordinates of the\n * rectangle in the viewport coordinate space.\n * @see {@link convertToViewportPoint}\n */\n convertToViewportRectangle(rect) {\n const topLeft = Util.applyTransform([rect[0], rect[1]], this.transform);\n const bottomRight = Util.applyTransform([rect[2], rect[3]], this.transform);\n return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];\n }\n\n /**\n * Converts viewport coordinates to the PDF location. For examples, useful\n * for converting canvas pixel location into PDF one.\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @returns {Array} Array containing `x`- and `y`-coordinates of the\n * point in the PDF coordinate space.\n * @see {@link convertToViewportPoint}\n */\n convertToPdfPoint(x, y) {\n return Util.applyInverseTransform([x, y], this.transform);\n }\n}\n\nclass RenderingCancelledException extends BaseException {\n constructor(msg, extraDelay = 0) {\n super(msg, \"RenderingCancelledException\");\n this.extraDelay = extraDelay;\n }\n}\n\nfunction isDataScheme(url) {\n const ii = url.length;\n let i = 0;\n while (i < ii && url[i].trim() === \"\") {\n i++;\n }\n return url.substring(i, i + 5).toLowerCase() === \"data:\";\n}\n\nfunction isPdfFile(filename) {\n return typeof filename === \"string\" && /\\.pdf$/i.test(filename);\n}\n\n/**\n * Gets the filename from a given URL.\n * @param {string} url\n * @returns {string}\n */\nfunction getFilenameFromUrl(url) {\n [url] = url.split(/[#?]/, 1);\n return url.substring(url.lastIndexOf(\"/\") + 1);\n}\n\n/**\n * Returns the filename or guessed filename from the url (see issue 3455).\n * @param {string} url - The original PDF location.\n * @param {string} defaultFilename - The value returned if the filename is\n * unknown, or the protocol is unsupported.\n * @returns {string} Guessed PDF filename.\n */\nfunction getPdfFilenameFromUrl(url, defaultFilename = \"document.pdf\") {\n if (typeof url !== \"string\") {\n return defaultFilename;\n }\n if (isDataScheme(url)) {\n warn('getPdfFilenameFromUrl: ignore \"data:\"-URL for performance reasons.');\n return defaultFilename;\n }\n const reURI = /^(?:(?:[^:]+:)?\\/\\/[^/]+)?([^?#]*)(\\?[^#]*)?(#.*)?$/;\n // SCHEME HOST 1.PATH 2.QUERY 3.REF\n // Pattern to get last matching NAME.pdf\n const reFilename = /[^/?#=]+\\.pdf\\b(?!.*\\.pdf\\b)/i;\n const splitURI = reURI.exec(url);\n let suggestedFilename =\n reFilename.exec(splitURI[1]) ||\n reFilename.exec(splitURI[2]) ||\n reFilename.exec(splitURI[3]);\n if (suggestedFilename) {\n suggestedFilename = suggestedFilename[0];\n if (suggestedFilename.includes(\"%\")) {\n // URL-encoded %2Fpath%2Fto%2Ffile.pdf should be file.pdf\n try {\n suggestedFilename = reFilename.exec(\n decodeURIComponent(suggestedFilename)\n )[0];\n } catch {\n // Possible (extremely rare) errors:\n // URIError \"Malformed URI\", e.g. for \"%AA.pdf\"\n // TypeError \"null has no properties\", e.g. for \"%2F.pdf\"\n }\n }\n }\n return suggestedFilename || defaultFilename;\n}\n\nclass StatTimer {\n started = Object.create(null);\n\n times = [];\n\n time(name) {\n if (name in this.started) {\n warn(`Timer is already running for ${name}`);\n }\n this.started[name] = Date.now();\n }\n\n timeEnd(name) {\n if (!(name in this.started)) {\n warn(`Timer has not been started for ${name}`);\n }\n this.times.push({\n name,\n start: this.started[name],\n end: Date.now(),\n });\n // Remove timer from started so it can be called again.\n delete this.started[name];\n }\n\n toString() {\n // Find the longest name for padding purposes.\n const outBuf = [];\n let longest = 0;\n for (const { name } of this.times) {\n longest = Math.max(name.length, longest);\n }\n for (const { name, start, end } of this.times) {\n outBuf.push(`${name.padEnd(longest)} ${end - start}ms\\n`);\n }\n return outBuf.join(\"\");\n }\n}\n\nfunction isValidFetchUrl(url, baseUrl) {\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n throw new Error(\"Not implemented: isValidFetchUrl\");\n }\n try {\n const { protocol } = baseUrl ? new URL(url, baseUrl) : new URL(url);\n // The Fetch API only supports the http/https protocols, and not file/ftp.\n return protocol === \"http:\" || protocol === \"https:\";\n } catch {\n return false; // `new URL()` will throw on incorrect data.\n }\n}\n\n/**\n * Event handler to suppress context menu.\n */\nfunction noContextMenu(e) {\n e.preventDefault();\n}\n\n// Deprecated API function -- display regardless of the `verbosity` setting.\nfunction deprecated(details) {\n console.log(\"Deprecated API usage: \" + details);\n}\n\nlet pdfDateStringRegex;\n\nclass PDFDateString {\n /**\n * Convert a PDF date string to a JavaScript `Date` object.\n *\n * The PDF date string format is described in section 7.9.4 of the official\n * PDF 32000-1:2008 specification. However, in the PDF 1.7 reference (sixth\n * edition) Adobe describes the same format including a trailing apostrophe.\n * This syntax in incorrect, but Adobe Acrobat creates PDF files that contain\n * them. We ignore all apostrophes as they are not necessary for date parsing.\n *\n * Moreover, Adobe Acrobat doesn't handle changing the date to universal time\n * and doesn't use the user's time zone (effectively ignoring the HH' and mm'\n * parts of the date string).\n *\n * @param {string} input\n * @returns {Date|null}\n */\n static toDateObject(input) {\n if (!input || typeof input !== \"string\") {\n return null;\n }\n\n // Lazily initialize the regular expression.\n pdfDateStringRegex ||= new RegExp(\n \"^D:\" + // Prefix (required)\n \"(\\\\d{4})\" + // Year (required)\n \"(\\\\d{2})?\" + // Month (optional)\n \"(\\\\d{2})?\" + // Day (optional)\n \"(\\\\d{2})?\" + // Hour (optional)\n \"(\\\\d{2})?\" + // Minute (optional)\n \"(\\\\d{2})?\" + // Second (optional)\n \"([Z|+|-])?\" + // Universal time relation (optional)\n \"(\\\\d{2})?\" + // Offset hour (optional)\n \"'?\" + // Splitting apostrophe (optional)\n \"(\\\\d{2})?\" + // Offset minute (optional)\n \"'?\" // Trailing apostrophe (optional)\n );\n\n // Optional fields that don't satisfy the requirements from the regular\n // expression (such as incorrect digit counts or numbers that are out of\n // range) will fall back the defaults from the specification.\n const matches = pdfDateStringRegex.exec(input);\n if (!matches) {\n return null;\n }\n\n // JavaScript's `Date` object expects the month to be between 0 and 11\n // instead of 1 and 12, so we have to correct for that.\n const year = parseInt(matches[1], 10);\n let month = parseInt(matches[2], 10);\n month = month >= 1 && month <= 12 ? month - 1 : 0;\n let day = parseInt(matches[3], 10);\n day = day >= 1 && day <= 31 ? day : 1;\n let hour = parseInt(matches[4], 10);\n hour = hour >= 0 && hour <= 23 ? hour : 0;\n let minute = parseInt(matches[5], 10);\n minute = minute >= 0 && minute <= 59 ? minute : 0;\n let second = parseInt(matches[6], 10);\n second = second >= 0 && second <= 59 ? second : 0;\n const universalTimeRelation = matches[7] || \"Z\";\n let offsetHour = parseInt(matches[8], 10);\n offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;\n let offsetMinute = parseInt(matches[9], 10) || 0;\n offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;\n\n // Universal time relation 'Z' means that the local time is equal to the\n // universal time, whereas the relations '+'/'-' indicate that the local\n // time is later respectively earlier than the universal time. Every date\n // is normalized to universal time.\n if (universalTimeRelation === \"-\") {\n hour += offsetHour;\n minute += offsetMinute;\n } else if (universalTimeRelation === \"+\") {\n hour -= offsetHour;\n minute -= offsetMinute;\n }\n\n return new Date(Date.UTC(year, month, day, hour, minute, second));\n }\n}\n\n/**\n * NOTE: This is (mostly) intended to support printing of XFA forms.\n */\nfunction getXfaPageViewport(xfaPage, { scale = 1, rotation = 0 }) {\n const { width, height } = xfaPage.attributes.style;\n const viewBox = [0, 0, parseInt(width), parseInt(height)];\n\n return new PageViewport({\n viewBox,\n scale,\n rotation,\n });\n}\n\nfunction getRGB(color) {\n if (color.startsWith(\"#\")) {\n const colorRGB = parseInt(color.slice(1), 16);\n return [\n (colorRGB & 0xff0000) >> 16,\n (colorRGB & 0x00ff00) >> 8,\n colorRGB & 0x0000ff,\n ];\n }\n\n if (color.startsWith(\"rgb(\")) {\n // getComputedStyle(...).color returns a `rgb(R, G, B)` color.\n return color\n .slice(/* \"rgb(\".length */ 4, -1) // Strip out \"rgb(\" and \")\".\n .split(\",\")\n .map(x => parseInt(x));\n }\n\n if (color.startsWith(\"rgba(\")) {\n return color\n .slice(/* \"rgba(\".length */ 5, -1) // Strip out \"rgba(\" and \")\".\n .split(\",\")\n .map(x => parseInt(x))\n .slice(0, 3);\n }\n\n warn(`Not a valid color format: \"${color}\"`);\n return [0, 0, 0];\n}\n\nfunction getColorValues(colors) {\n const span = document.createElement(\"span\");\n span.style.visibility = \"hidden\";\n document.body.append(span);\n for (const name of colors.keys()) {\n span.style.color = name;\n const computedColor = window.getComputedStyle(span).color;\n colors.set(name, getRGB(computedColor));\n }\n span.remove();\n}\n\nfunction getCurrentTransform(ctx) {\n const { a, b, c, d, e, f } = ctx.getTransform();\n return [a, b, c, d, e, f];\n}\n\nfunction getCurrentTransformInverse(ctx) {\n const { a, b, c, d, e, f } = ctx.getTransform().invertSelf();\n return [a, b, c, d, e, f];\n}\n\n/**\n * @param {HTMLDivElement} div\n * @param {PageViewport} viewport\n * @param {boolean} mustFlip\n * @param {boolean} mustRotate\n */\nfunction setLayerDimensions(\n div,\n viewport,\n mustFlip = false,\n mustRotate = true\n) {\n if (viewport instanceof PageViewport) {\n const { pageWidth, pageHeight } = viewport.rawDims;\n const { style } = div;\n const useRound = FeatureTest.isCSSRoundSupported;\n\n const w = `var(--scale-factor) * ${pageWidth}px`,\n h = `var(--scale-factor) * ${pageHeight}px`;\n const widthStr = useRound ? `round(${w}, 1px)` : `calc(${w})`,\n heightStr = useRound ? `round(${h}, 1px)` : `calc(${h})`;\n\n if (!mustFlip || viewport.rotation % 180 === 0) {\n style.width = widthStr;\n style.height = heightStr;\n } else {\n style.width = heightStr;\n style.height = widthStr;\n }\n }\n\n if (mustRotate) {\n div.setAttribute(\"data-main-rotation\", viewport.rotation);\n }\n}\n\nexport {\n deprecated,\n DOMCanvasFactory,\n DOMCMapReaderFactory,\n DOMFilterFactory,\n DOMStandardFontDataFactory,\n DOMSVGFactory,\n fetchData,\n getColorValues,\n getCurrentTransform,\n getCurrentTransformInverse,\n getFilenameFromUrl,\n getPdfFilenameFromUrl,\n getRGB,\n getXfaPageViewport,\n isDataScheme,\n isPdfFile,\n isValidFetchUrl,\n noContextMenu,\n PageViewport,\n PDFDateString,\n PixelsPerInch,\n RenderingCancelledException,\n setLayerDimensions,\n StatTimer,\n};\n","/* Copyright 2023 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { noContextMenu } from \"../display_utils.js\";\n\nclass EditorToolbar {\n #toolbar = null;\n\n #colorPicker = null;\n\n #editor;\n\n #buttons = null;\n\n #altText = null;\n\n static #l10nRemove = null;\n\n constructor(editor) {\n this.#editor = editor;\n\n EditorToolbar.#l10nRemove ||= Object.freeze({\n freetext: \"pdfjs-editor-remove-freetext-button\",\n highlight: \"pdfjs-editor-remove-highlight-button\",\n ink: \"pdfjs-editor-remove-ink-button\",\n stamp: \"pdfjs-editor-remove-stamp-button\",\n });\n }\n\n render() {\n const editToolbar = (this.#toolbar = document.createElement(\"div\"));\n editToolbar.className = \"editToolbar\";\n editToolbar.setAttribute(\"role\", \"toolbar\");\n const signal = this.#editor._uiManager._signal;\n editToolbar.addEventListener(\"contextmenu\", noContextMenu, { signal });\n editToolbar.addEventListener(\"pointerdown\", EditorToolbar.#pointerDown, {\n signal,\n });\n\n const buttons = (this.#buttons = document.createElement(\"div\"));\n buttons.className = \"buttons\";\n editToolbar.append(buttons);\n\n const position = this.#editor.toolbarPosition;\n if (position) {\n const { style } = editToolbar;\n const x =\n this.#editor._uiManager.direction === \"ltr\"\n ? 1 - position[0]\n : position[0];\n style.insetInlineEnd = `${100 * x}%`;\n style.top = `calc(${\n 100 * position[1]\n }% + var(--editor-toolbar-vert-offset))`;\n }\n\n this.#addDeleteButton();\n\n return editToolbar;\n }\n\n static #pointerDown(e) {\n e.stopPropagation();\n }\n\n #focusIn(e) {\n this.#editor._focusEventsAllowed = false;\n e.preventDefault();\n e.stopPropagation();\n }\n\n #focusOut(e) {\n this.#editor._focusEventsAllowed = true;\n e.preventDefault();\n e.stopPropagation();\n }\n\n #addListenersToElement(element) {\n // If we're clicking on a button with the keyboard or with\n // the mouse, we don't want to trigger any focus events on\n // the editor.\n const signal = this.#editor._uiManager._signal;\n element.addEventListener(\"focusin\", this.#focusIn.bind(this), {\n capture: true,\n signal,\n });\n element.addEventListener(\"focusout\", this.#focusOut.bind(this), {\n capture: true,\n signal,\n });\n element.addEventListener(\"contextmenu\", noContextMenu, { signal });\n }\n\n hide() {\n this.#toolbar.classList.add(\"hidden\");\n this.#colorPicker?.hideDropdown();\n }\n\n show() {\n this.#toolbar.classList.remove(\"hidden\");\n this.#altText?.shown();\n }\n\n #addDeleteButton() {\n const { editorType, _uiManager } = this.#editor;\n\n const button = document.createElement(\"button\");\n button.className = \"delete\";\n button.tabIndex = 0;\n button.setAttribute(\"data-l10n-id\", EditorToolbar.#l10nRemove[editorType]);\n this.#addListenersToElement(button);\n button.addEventListener(\n \"click\",\n e => {\n _uiManager.delete();\n },\n { signal: _uiManager._signal }\n );\n this.#buttons.append(button);\n }\n\n get #divider() {\n const divider = document.createElement(\"div\");\n divider.className = \"divider\";\n return divider;\n }\n\n async addAltText(altText) {\n const button = await altText.render();\n this.#addListenersToElement(button);\n this.#buttons.prepend(button, this.#divider);\n this.#altText = altText;\n }\n\n addColorPicker(colorPicker) {\n this.#colorPicker = colorPicker;\n const button = colorPicker.renderButton();\n this.#addListenersToElement(button);\n this.#buttons.prepend(button, this.#divider);\n }\n\n remove() {\n this.#toolbar.remove();\n this.#colorPicker?.destroy();\n this.#colorPicker = null;\n }\n}\n\nclass HighlightToolbar {\n #buttons = null;\n\n #toolbar = null;\n\n #uiManager;\n\n constructor(uiManager) {\n this.#uiManager = uiManager;\n }\n\n #render() {\n const editToolbar = (this.#toolbar = document.createElement(\"div\"));\n editToolbar.className = \"editToolbar\";\n editToolbar.setAttribute(\"role\", \"toolbar\");\n editToolbar.addEventListener(\"contextmenu\", noContextMenu, {\n signal: this.#uiManager._signal,\n });\n\n const buttons = (this.#buttons = document.createElement(\"div\"));\n buttons.className = \"buttons\";\n editToolbar.append(buttons);\n\n this.#addHighlightButton();\n\n return editToolbar;\n }\n\n #getLastPoint(boxes, isLTR) {\n let lastY = 0;\n let lastX = 0;\n for (const box of boxes) {\n const y = box.y + box.height;\n if (y < lastY) {\n continue;\n }\n const x = box.x + (isLTR ? box.width : 0);\n if (y > lastY) {\n lastX = x;\n lastY = y;\n continue;\n }\n if (isLTR) {\n if (x > lastX) {\n lastX = x;\n }\n } else if (x < lastX) {\n lastX = x;\n }\n }\n return [isLTR ? 1 - lastX : lastX, lastY];\n }\n\n show(parent, boxes, isLTR) {\n const [x, y] = this.#getLastPoint(boxes, isLTR);\n const { style } = (this.#toolbar ||= this.#render());\n parent.append(this.#toolbar);\n style.insetInlineEnd = `${100 * x}%`;\n style.top = `calc(${100 * y}% + var(--editor-toolbar-vert-offset))`;\n }\n\n hide() {\n this.#toolbar.remove();\n }\n\n #addHighlightButton() {\n const button = document.createElement(\"button\");\n button.className = \"highlightButton\";\n button.tabIndex = 0;\n button.setAttribute(\"data-l10n-id\", `pdfjs-highlight-floating-button1`);\n const span = document.createElement(\"span\");\n button.append(span);\n span.className = \"visuallyHidden\";\n span.setAttribute(\"data-l10n-id\", \"pdfjs-highlight-floating-button-label\");\n const signal = this.#uiManager._signal;\n button.addEventListener(\"contextmenu\", noContextMenu, { signal });\n button.addEventListener(\n \"click\",\n () => {\n this.#uiManager.highlightSelection(\"floating_button\");\n },\n { signal }\n );\n this.#buttons.append(button);\n }\n}\n\nexport { EditorToolbar, HighlightToolbar };\n","/* Copyright 2022 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** @typedef {import(\"./editor.js\").AnnotationEditor} AnnotationEditor */\n// eslint-disable-next-line max-len\n/** @typedef {import(\"./annotation_editor_layer.js\").AnnotationEditorLayer} AnnotationEditorLayer */\n\nimport {\n AnnotationEditorParamsType,\n AnnotationEditorPrefix,\n AnnotationEditorType,\n FeatureTest,\n getUuid,\n shadow,\n Util,\n warn,\n} from \"../../shared/util.js\";\nimport {\n fetchData,\n getColorValues,\n getRGB,\n PixelsPerInch,\n} from \"../display_utils.js\";\nimport { HighlightToolbar } from \"./toolbar.js\";\n\nfunction bindEvents(obj, element, names) {\n for (const name of names) {\n element.addEventListener(name, obj[name].bind(obj));\n }\n}\n\n/**\n * Convert a number between 0 and 100 into an hex number between 0 and 255.\n * @param {number} opacity\n * @return {string}\n */\nfunction opacityToHex(opacity) {\n return Math.round(Math.min(255, Math.max(1, 255 * opacity)))\n .toString(16)\n .padStart(2, \"0\");\n}\n\n/**\n * Class to create some unique ids for the different editors.\n */\nclass IdManager {\n #id = 0;\n\n constructor() {\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"TESTING\")) {\n Object.defineProperty(this, \"reset\", {\n value: () => (this.#id = 0),\n });\n }\n }\n\n /**\n * Get a unique id.\n * @returns {string}\n */\n get id() {\n return `${AnnotationEditorPrefix}${this.#id++}`;\n }\n}\n\n/**\n * Class to manage the images used by the editors.\n * The main idea is to try to minimize the memory used by the images.\n * The images are cached and reused when possible\n * We use a refCounter to know when an image is not used anymore but we need to\n * be able to restore an image after a remove+undo, so we keep a file reference\n * or an url one.\n */\nclass ImageManager {\n #baseId = getUuid();\n\n #id = 0;\n\n #cache = null;\n\n static get _isSVGFittingCanvas() {\n // By default, Firefox doesn't rescale without preserving the aspect ratio\n // when drawing an SVG image on a canvas, see https://bugzilla.mozilla.org/1547776.\n // The \"workaround\" is to append \"svgView(preserveAspectRatio(none))\" to the\n // url, but according to comment #15, it seems that it leads to unexpected\n // behavior in Safari.\n const svg = `data:image/svg+xml;charset=UTF-8,`;\n const canvas = new OffscreenCanvas(1, 3);\n const ctx = canvas.getContext(\"2d\", { willReadFrequently: true });\n const image = new Image();\n image.src = svg;\n const promise = image.decode().then(() => {\n ctx.drawImage(image, 0, 0, 1, 1, 0, 0, 1, 3);\n return new Uint32Array(ctx.getImageData(0, 0, 1, 1).data.buffer)[0] === 0;\n });\n\n return shadow(this, \"_isSVGFittingCanvas\", promise);\n }\n\n async #get(key, rawData) {\n this.#cache ||= new Map();\n let data = this.#cache.get(key);\n if (data === null) {\n // We already tried to load the image but it failed.\n return null;\n }\n if (data?.bitmap) {\n data.refCounter += 1;\n return data;\n }\n try {\n data ||= {\n bitmap: null,\n id: `image_${this.#baseId}_${this.#id++}`,\n refCounter: 0,\n isSvg: false,\n };\n let image;\n if (typeof rawData === \"string\") {\n data.url = rawData;\n image = await fetchData(rawData, \"blob\");\n } else {\n image = data.file = rawData;\n }\n\n if (image.type === \"image/svg+xml\") {\n // Unfortunately, createImageBitmap doesn't work with SVG images.\n // (see https://bugzilla.mozilla.org/1841972).\n const mustRemoveAspectRatioPromise = ImageManager._isSVGFittingCanvas;\n const fileReader = new FileReader();\n const imageElement = new Image();\n const imagePromise = new Promise((resolve, reject) => {\n imageElement.onload = () => {\n data.bitmap = imageElement;\n data.isSvg = true;\n resolve();\n };\n fileReader.onload = async () => {\n const url = (data.svgUrl = fileReader.result);\n // We need to set the preserveAspectRatio to none in order to let\n // the image fits the canvas when resizing.\n imageElement.src = (await mustRemoveAspectRatioPromise)\n ? `${url}#svgView(preserveAspectRatio(none))`\n : url;\n };\n imageElement.onerror = fileReader.onerror = reject;\n });\n fileReader.readAsDataURL(image);\n await imagePromise;\n } else {\n data.bitmap = await createImageBitmap(image);\n }\n data.refCounter = 1;\n } catch (e) {\n console.error(e);\n data = null;\n }\n this.#cache.set(key, data);\n if (data) {\n this.#cache.set(data.id, data);\n }\n return data;\n }\n\n async getFromFile(file) {\n const { lastModified, name, size, type } = file;\n return this.#get(`${lastModified}_${name}_${size}_${type}`, file);\n }\n\n async getFromUrl(url) {\n return this.#get(url, url);\n }\n\n async getFromId(id) {\n this.#cache ||= new Map();\n const data = this.#cache.get(id);\n if (!data) {\n return null;\n }\n if (data.bitmap) {\n data.refCounter += 1;\n return data;\n }\n\n if (data.file) {\n return this.getFromFile(data.file);\n }\n return this.getFromUrl(data.url);\n }\n\n getSvgUrl(id) {\n const data = this.#cache.get(id);\n if (!data?.isSvg) {\n return null;\n }\n return data.svgUrl;\n }\n\n deleteId(id) {\n this.#cache ||= new Map();\n const data = this.#cache.get(id);\n if (!data) {\n return;\n }\n data.refCounter -= 1;\n if (data.refCounter !== 0) {\n return;\n }\n data.bitmap = null;\n }\n\n // We can use the id only if it belongs this manager.\n // We must take care of having the right manager because we can copy/paste\n // some images from other documents, hence it'd be a pity to use an id from an\n // other manager.\n isValidId(id) {\n return id.startsWith(`image_${this.#baseId}_`);\n }\n}\n\n/**\n * Class to handle undo/redo.\n * Commands are just saved in a buffer.\n * If we hit some memory issues we could likely use a circular buffer.\n * It has to be used as a singleton.\n */\nclass CommandManager {\n #commands = [];\n\n #locked = false;\n\n #maxSize;\n\n #position = -1;\n\n constructor(maxSize = 128) {\n this.#maxSize = maxSize;\n }\n\n /**\n * @typedef {Object} addOptions\n * @property {function} cmd\n * @property {function} undo\n * @property {function} [post]\n * @property {boolean} mustExec\n * @property {number} type\n * @property {boolean} overwriteIfSameType\n * @property {boolean} keepUndo\n */\n\n /**\n * Add a new couple of commands to be used in case of redo/undo.\n * @param {addOptions} options\n */\n add({\n cmd,\n undo,\n post,\n mustExec,\n type = NaN,\n overwriteIfSameType = false,\n keepUndo = false,\n }) {\n if (mustExec) {\n cmd();\n }\n\n if (this.#locked) {\n return;\n }\n\n const save = { cmd, undo, post, type };\n if (this.#position === -1) {\n if (this.#commands.length > 0) {\n // All the commands have been undone and then a new one is added\n // hence we clear the queue.\n this.#commands.length = 0;\n }\n this.#position = 0;\n this.#commands.push(save);\n return;\n }\n\n if (overwriteIfSameType && this.#commands[this.#position].type === type) {\n // For example when we change a color we don't want to\n // be able to undo all the steps, hence we only want to\n // keep the last undoable action in this sequence of actions.\n if (keepUndo) {\n save.undo = this.#commands[this.#position].undo;\n }\n this.#commands[this.#position] = save;\n return;\n }\n\n const next = this.#position + 1;\n if (next === this.#maxSize) {\n this.#commands.splice(0, 1);\n } else {\n this.#position = next;\n if (next < this.#commands.length) {\n this.#commands.splice(next);\n }\n }\n\n this.#commands.push(save);\n }\n\n /**\n * Undo the last command.\n */\n undo() {\n if (this.#position === -1) {\n // Nothing to undo.\n return;\n }\n\n // Avoid to insert something during the undo execution.\n this.#locked = true;\n const { undo, post } = this.#commands[this.#position];\n undo();\n post?.();\n this.#locked = false;\n\n this.#position -= 1;\n }\n\n /**\n * Redo the last command.\n */\n redo() {\n if (this.#position < this.#commands.length - 1) {\n this.#position += 1;\n\n // Avoid to insert something during the redo execution.\n this.#locked = true;\n const { cmd, post } = this.#commands[this.#position];\n cmd();\n post?.();\n this.#locked = false;\n }\n }\n\n /**\n * Check if there is something to undo.\n * @returns {boolean}\n */\n hasSomethingToUndo() {\n return this.#position !== -1;\n }\n\n /**\n * Check if there is something to redo.\n * @returns {boolean}\n */\n hasSomethingToRedo() {\n return this.#position < this.#commands.length - 1;\n }\n\n destroy() {\n this.#commands = null;\n }\n}\n\n/**\n * Class to handle the different keyboards shortcuts we can have on mac or\n * non-mac OSes.\n */\nclass KeyboardManager {\n /**\n * Create a new keyboard manager class.\n * @param {Array} callbacks - an array containing an array of shortcuts\n * and a callback to call.\n * A shortcut is a string like `ctrl+c` or `mac+ctrl+c` for mac OS.\n */\n constructor(callbacks) {\n this.buffer = [];\n this.callbacks = new Map();\n this.allKeys = new Set();\n\n const { isMac } = FeatureTest.platform;\n for (const [keys, callback, options = {}] of callbacks) {\n for (const key of keys) {\n const isMacKey = key.startsWith(\"mac+\");\n if (isMac && isMacKey) {\n this.callbacks.set(key.slice(4), { callback, options });\n this.allKeys.add(key.split(\"+\").at(-1));\n } else if (!isMac && !isMacKey) {\n this.callbacks.set(key, { callback, options });\n this.allKeys.add(key.split(\"+\").at(-1));\n }\n }\n }\n }\n\n /**\n * Serialize an event into a string in order to match a\n * potential key for a callback.\n * @param {KeyboardEvent} event\n * @returns {string}\n */\n #serialize(event) {\n if (event.altKey) {\n this.buffer.push(\"alt\");\n }\n if (event.ctrlKey) {\n this.buffer.push(\"ctrl\");\n }\n if (event.metaKey) {\n this.buffer.push(\"meta\");\n }\n if (event.shiftKey) {\n this.buffer.push(\"shift\");\n }\n this.buffer.push(event.key);\n const str = this.buffer.join(\"+\");\n this.buffer.length = 0;\n\n return str;\n }\n\n /**\n * Execute a callback, if any, for a given keyboard event.\n * The self is used as `this` in the callback.\n * @param {Object} self\n * @param {KeyboardEvent} event\n * @returns\n */\n exec(self, event) {\n if (!this.allKeys.has(event.key)) {\n return;\n }\n const info = this.callbacks.get(this.#serialize(event));\n if (!info) {\n return;\n }\n const {\n callback,\n options: { bubbles = false, args = [], checker = null },\n } = info;\n\n if (checker && !checker(self, event)) {\n return;\n }\n callback.bind(self, ...args, event)();\n\n // For example, ctrl+s in a FreeText must be handled by the viewer, hence\n // the event must bubble.\n if (!bubbles) {\n event.stopPropagation();\n event.preventDefault();\n }\n }\n}\n\nclass ColorManager {\n static _colorsMapping = new Map([\n [\"CanvasText\", [0, 0, 0]],\n [\"Canvas\", [255, 255, 255]],\n ]);\n\n get _colors() {\n if (\n typeof PDFJSDev !== \"undefined\" &&\n PDFJSDev.test(\"LIB\") &&\n typeof document === \"undefined\"\n ) {\n return shadow(this, \"_colors\", ColorManager._colorsMapping);\n }\n\n const colors = new Map([\n [\"CanvasText\", null],\n [\"Canvas\", null],\n ]);\n getColorValues(colors);\n return shadow(this, \"_colors\", colors);\n }\n\n /**\n * In High Contrast Mode, the color on the screen is not always the\n * real color used in the pdf.\n * For example in some cases white can appear to be black but when saving\n * we want to have white.\n * @param {string} color\n * @returns {Array}\n */\n convert(color) {\n const rgb = getRGB(color);\n if (!window.matchMedia(\"(forced-colors: active)\").matches) {\n return rgb;\n }\n\n for (const [name, RGB] of this._colors) {\n if (RGB.every((x, i) => x === rgb[i])) {\n return ColorManager._colorsMapping.get(name);\n }\n }\n return rgb;\n }\n\n /**\n * An input element must have its color value as a hex string\n * and not as color name.\n * So this function converts a name into an hex string.\n * @param {string} name\n * @returns {string}\n */\n getHexCode(name) {\n const rgb = this._colors.get(name);\n if (!rgb) {\n return name;\n }\n return Util.makeHexColor(...rgb);\n }\n}\n\n/**\n * A pdf has several pages and each of them when it will rendered\n * will have an AnnotationEditorLayer which will contain the some\n * new Annotations associated to an editor in order to modify them.\n *\n * This class is used to manage all the different layers, editors and\n * some action like copy/paste, undo/redo, ...\n */\nclass AnnotationEditorUIManager {\n #abortController = new AbortController();\n\n #activeEditor = null;\n\n #allEditors = new Map();\n\n #allLayers = new Map();\n\n #altTextManager = null;\n\n #annotationStorage = null;\n\n #changedExistingAnnotations = null;\n\n #commandManager = new CommandManager();\n\n #copyPasteAC = null;\n\n #currentPageIndex = 0;\n\n #deletedAnnotationsElementIds = new Set();\n\n #draggingEditors = null;\n\n #editorTypes = null;\n\n #editorsToRescale = new Set();\n\n #enableHighlightFloatingButton = false;\n\n #enableUpdatedAddImage = false;\n\n #enableNewAltTextWhenAddingImage = false;\n\n #filterFactory = null;\n\n #focusMainContainerTimeoutId = null;\n\n #focusManagerAC = null;\n\n #highlightColors = null;\n\n #highlightWhenShiftUp = false;\n\n #highlightToolbar = null;\n\n #idManager = new IdManager();\n\n #isEnabled = false;\n\n #isWaiting = false;\n\n #keyboardManagerAC = null;\n\n #lastActiveElement = null;\n\n #mainHighlightColorPicker = null;\n\n #mlManager = null;\n\n #mode = AnnotationEditorType.NONE;\n\n #selectedEditors = new Set();\n\n #selectedTextNode = null;\n\n #pageColors = null;\n\n #showAllStates = null;\n\n #previousStates = {\n isEditing: false,\n isEmpty: true,\n hasSomethingToUndo: false,\n hasSomethingToRedo: false,\n hasSelectedEditor: false,\n hasSelectedText: false,\n };\n\n #translation = [0, 0];\n\n #translationTimeoutId = null;\n\n #container = null;\n\n #viewer = null;\n\n static TRANSLATE_SMALL = 1; // page units.\n\n static TRANSLATE_BIG = 10; // page units.\n\n static get _keyboardManager() {\n const proto = AnnotationEditorUIManager.prototype;\n\n /**\n * If the focused element is an input, we don't want to handle the arrow.\n * For example, sliders can be controlled with the arrow keys.\n */\n const arrowChecker = self =>\n self.#container.contains(document.activeElement) &&\n document.activeElement.tagName !== \"BUTTON\" &&\n self.hasSomethingToControl();\n\n const textInputChecker = (_self, { target: el }) => {\n if (el instanceof HTMLInputElement) {\n const { type } = el;\n return type !== \"text\" && type !== \"number\";\n }\n return true;\n };\n\n const small = this.TRANSLATE_SMALL;\n const big = this.TRANSLATE_BIG;\n\n return shadow(\n this,\n \"_keyboardManager\",\n new KeyboardManager([\n [\n [\"ctrl+a\", \"mac+meta+a\"],\n proto.selectAll,\n { checker: textInputChecker },\n ],\n [[\"ctrl+z\", \"mac+meta+z\"], proto.undo, { checker: textInputChecker }],\n [\n // On mac, depending of the OS version, the event.key is either \"z\" or\n // \"Z\" when the user presses \"meta+shift+z\".\n [\n \"ctrl+y\",\n \"ctrl+shift+z\",\n \"mac+meta+shift+z\",\n \"ctrl+shift+Z\",\n \"mac+meta+shift+Z\",\n ],\n proto.redo,\n { checker: textInputChecker },\n ],\n [\n [\n \"Backspace\",\n \"alt+Backspace\",\n \"ctrl+Backspace\",\n \"shift+Backspace\",\n \"mac+Backspace\",\n \"mac+alt+Backspace\",\n \"mac+ctrl+Backspace\",\n \"Delete\",\n \"ctrl+Delete\",\n \"shift+Delete\",\n \"mac+Delete\",\n ],\n proto.delete,\n { checker: textInputChecker },\n ],\n [\n [\"Enter\", \"mac+Enter\"],\n proto.addNewEditorFromKeyboard,\n {\n // Those shortcuts can be used in the toolbar for some other actions\n // like zooming, hence we need to check if the container has the\n // focus.\n checker: (self, { target: el }) =>\n !(el instanceof HTMLButtonElement) &&\n self.#container.contains(el) &&\n !self.isEnterHandled,\n },\n ],\n [\n [\" \", \"mac+ \"],\n proto.addNewEditorFromKeyboard,\n {\n // Those shortcuts can be used in the toolbar for some other actions\n // like zooming, hence we need to check if the container has the\n // focus.\n checker: (self, { target: el }) =>\n !(el instanceof HTMLButtonElement) &&\n self.#container.contains(document.activeElement),\n },\n ],\n [[\"Escape\", \"mac+Escape\"], proto.unselectAll],\n [\n [\"ArrowLeft\", \"mac+ArrowLeft\"],\n proto.translateSelectedEditors,\n { args: [-small, 0], checker: arrowChecker },\n ],\n [\n [\"ctrl+ArrowLeft\", \"mac+shift+ArrowLeft\"],\n proto.translateSelectedEditors,\n { args: [-big, 0], checker: arrowChecker },\n ],\n [\n [\"ArrowRight\", \"mac+ArrowRight\"],\n proto.translateSelectedEditors,\n { args: [small, 0], checker: arrowChecker },\n ],\n [\n [\"ctrl+ArrowRight\", \"mac+shift+ArrowRight\"],\n proto.translateSelectedEditors,\n { args: [big, 0], checker: arrowChecker },\n ],\n [\n [\"ArrowUp\", \"mac+ArrowUp\"],\n proto.translateSelectedEditors,\n { args: [0, -small], checker: arrowChecker },\n ],\n [\n [\"ctrl+ArrowUp\", \"mac+shift+ArrowUp\"],\n proto.translateSelectedEditors,\n { args: [0, -big], checker: arrowChecker },\n ],\n [\n [\"ArrowDown\", \"mac+ArrowDown\"],\n proto.translateSelectedEditors,\n { args: [0, small], checker: arrowChecker },\n ],\n [\n [\"ctrl+ArrowDown\", \"mac+shift+ArrowDown\"],\n proto.translateSelectedEditors,\n { args: [0, big], checker: arrowChecker },\n ],\n ])\n );\n }\n\n constructor(\n container,\n viewer,\n altTextManager,\n eventBus,\n pdfDocument,\n pageColors,\n highlightColors,\n enableHighlightFloatingButton,\n enableUpdatedAddImage,\n enableNewAltTextWhenAddingImage,\n mlManager\n ) {\n const signal = (this._signal = this.#abortController.signal);\n this.#container = container;\n this.#viewer = viewer;\n this.#altTextManager = altTextManager;\n this._eventBus = eventBus;\n eventBus._on(\"editingaction\", this.onEditingAction.bind(this), { signal });\n eventBus._on(\"pagechanging\", this.onPageChanging.bind(this), { signal });\n eventBus._on(\"scalechanging\", this.onScaleChanging.bind(this), { signal });\n eventBus._on(\"rotationchanging\", this.onRotationChanging.bind(this), {\n signal,\n });\n eventBus._on(\"setpreference\", this.onSetPreference.bind(this), { signal });\n eventBus._on(\n \"switchannotationeditorparams\",\n evt => this.updateParams(evt.type, evt.value),\n { signal }\n );\n this.#addSelectionListener();\n this.#addDragAndDropListeners();\n this.#addKeyboardManager();\n this.#annotationStorage = pdfDocument.annotationStorage;\n this.#filterFactory = pdfDocument.filterFactory;\n this.#pageColors = pageColors;\n this.#highlightColors = highlightColors || null;\n this.#enableHighlightFloatingButton = enableHighlightFloatingButton;\n this.#enableUpdatedAddImage = enableUpdatedAddImage;\n this.#enableNewAltTextWhenAddingImage = enableNewAltTextWhenAddingImage;\n this.#mlManager = mlManager || null;\n this.viewParameters = {\n realScale: PixelsPerInch.PDF_TO_CSS_UNITS,\n rotation: 0,\n };\n this.isShiftKeyDown = false;\n\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"TESTING\")) {\n Object.defineProperty(this, \"reset\", {\n value: () => {\n this.selectAll();\n this.delete();\n this.#idManager.reset();\n },\n });\n }\n }\n\n destroy() {\n this.#abortController?.abort();\n this.#abortController = null;\n this._signal = null;\n\n for (const layer of this.#allLayers.values()) {\n layer.destroy();\n }\n this.#allLayers.clear();\n this.#allEditors.clear();\n this.#editorsToRescale.clear();\n this.#activeEditor = null;\n this.#selectedEditors.clear();\n this.#commandManager.destroy();\n this.#altTextManager?.destroy();\n this.#highlightToolbar?.hide();\n this.#highlightToolbar = null;\n if (this.#focusMainContainerTimeoutId) {\n clearTimeout(this.#focusMainContainerTimeoutId);\n this.#focusMainContainerTimeoutId = null;\n }\n if (this.#translationTimeoutId) {\n clearTimeout(this.#translationTimeoutId);\n this.#translationTimeoutId = null;\n }\n }\n\n combinedSignal(ac) {\n return AbortSignal.any([this._signal, ac.signal]);\n }\n\n get mlManager() {\n return this.#mlManager;\n }\n\n get useNewAltTextFlow() {\n return this.#enableUpdatedAddImage;\n }\n\n get useNewAltTextWhenAddingImage() {\n return this.#enableNewAltTextWhenAddingImage;\n }\n\n get hcmFilter() {\n return shadow(\n this,\n \"hcmFilter\",\n this.#pageColors\n ? this.#filterFactory.addHCMFilter(\n this.#pageColors.foreground,\n this.#pageColors.background\n )\n : \"none\"\n );\n }\n\n get direction() {\n return shadow(\n this,\n \"direction\",\n getComputedStyle(this.#container).direction\n );\n }\n\n get highlightColors() {\n return shadow(\n this,\n \"highlightColors\",\n this.#highlightColors\n ? new Map(\n this.#highlightColors\n .split(\",\")\n .map(pair => pair.split(\"=\").map(x => x.trim()))\n )\n : null\n );\n }\n\n get highlightColorNames() {\n return shadow(\n this,\n \"highlightColorNames\",\n this.highlightColors\n ? new Map(Array.from(this.highlightColors, e => e.reverse()))\n : null\n );\n }\n\n setMainHighlightColorPicker(colorPicker) {\n this.#mainHighlightColorPicker = colorPicker;\n }\n\n editAltText(editor, firstTime = false) {\n this.#altTextManager?.editAltText(this, editor, firstTime);\n }\n\n switchToMode(mode, callback) {\n // Switching to a mode can be asynchronous.\n this._eventBus.on(\"annotationeditormodechanged\", callback, {\n once: true,\n signal: this._signal,\n });\n this._eventBus.dispatch(\"showannotationeditorui\", {\n source: this,\n mode,\n });\n }\n\n setPreference(name, value) {\n this._eventBus.dispatch(\"setpreference\", {\n source: this,\n name,\n value,\n });\n }\n\n onSetPreference({ name, value }) {\n switch (name) {\n case \"enableNewAltTextWhenAddingImage\":\n this.#enableNewAltTextWhenAddingImage = value;\n break;\n }\n }\n\n onPageChanging({ pageNumber }) {\n this.#currentPageIndex = pageNumber - 1;\n }\n\n focusMainContainer() {\n this.#container.focus();\n }\n\n findParent(x, y) {\n for (const layer of this.#allLayers.values()) {\n const {\n x: layerX,\n y: layerY,\n width,\n height,\n } = layer.div.getBoundingClientRect();\n if (\n x >= layerX &&\n x <= layerX + width &&\n y >= layerY &&\n y <= layerY + height\n ) {\n return layer;\n }\n }\n return null;\n }\n\n disableUserSelect(value = false) {\n this.#viewer.classList.toggle(\"noUserSelect\", value);\n }\n\n addShouldRescale(editor) {\n this.#editorsToRescale.add(editor);\n }\n\n removeShouldRescale(editor) {\n this.#editorsToRescale.delete(editor);\n }\n\n onScaleChanging({ scale }) {\n this.commitOrRemove();\n this.viewParameters.realScale = scale * PixelsPerInch.PDF_TO_CSS_UNITS;\n for (const editor of this.#editorsToRescale) {\n editor.onScaleChanging();\n }\n }\n\n onRotationChanging({ pagesRotation }) {\n this.commitOrRemove();\n this.viewParameters.rotation = pagesRotation;\n }\n\n #getAnchorElementForSelection({ anchorNode }) {\n return anchorNode.nodeType === Node.TEXT_NODE\n ? anchorNode.parentElement\n : anchorNode;\n }\n\n #getLayerForTextLayer(textLayer) {\n const { currentLayer } = this;\n if (currentLayer.hasTextLayer(textLayer)) {\n return currentLayer;\n }\n for (const layer of this.#allLayers.values()) {\n if (layer.hasTextLayer(textLayer)) {\n return layer;\n }\n }\n return null;\n }\n\n highlightSelection(methodOfCreation = \"\") {\n const selection = document.getSelection();\n if (!selection || selection.isCollapsed) {\n return;\n }\n const { anchorNode, anchorOffset, focusNode, focusOffset } = selection;\n const text = selection.toString();\n const anchorElement = this.#getAnchorElementForSelection(selection);\n const textLayer = anchorElement.closest(\".textLayer\");\n const boxes = this.getSelectionBoxes(textLayer);\n if (!boxes) {\n return;\n }\n selection.empty();\n\n const layer = this.#getLayerForTextLayer(textLayer);\n const isNoneMode = this.#mode === AnnotationEditorType.NONE;\n const callback = () => {\n layer?.createAndAddNewEditor({ x: 0, y: 0 }, false, {\n methodOfCreation,\n boxes,\n anchorNode,\n anchorOffset,\n focusNode,\n focusOffset,\n text,\n });\n if (isNoneMode) {\n this.showAllEditors(\"highlight\", true, /* updateButton = */ true);\n }\n };\n if (isNoneMode) {\n this.switchToMode(AnnotationEditorType.HIGHLIGHT, callback);\n return;\n }\n callback();\n }\n\n #displayHighlightToolbar() {\n const selection = document.getSelection();\n if (!selection || selection.isCollapsed) {\n return;\n }\n const anchorElement = this.#getAnchorElementForSelection(selection);\n const textLayer = anchorElement.closest(\".textLayer\");\n const boxes = this.getSelectionBoxes(textLayer);\n if (!boxes) {\n return;\n }\n this.#highlightToolbar ||= new HighlightToolbar(this);\n this.#highlightToolbar.show(textLayer, boxes, this.direction === \"ltr\");\n }\n\n /**\n * Add an editor in the annotation storage.\n * @param {AnnotationEditor} editor\n */\n addToAnnotationStorage(editor) {\n if (\n !editor.isEmpty() &&\n this.#annotationStorage &&\n !this.#annotationStorage.has(editor.id)\n ) {\n this.#annotationStorage.setValue(editor.id, editor);\n }\n }\n\n #selectionChange() {\n const selection = document.getSelection();\n if (!selection || selection.isCollapsed) {\n if (this.#selectedTextNode) {\n this.#highlightToolbar?.hide();\n this.#selectedTextNode = null;\n this.#dispatchUpdateStates({\n hasSelectedText: false,\n });\n }\n return;\n }\n const { anchorNode } = selection;\n if (anchorNode === this.#selectedTextNode) {\n return;\n }\n\n const anchorElement = this.#getAnchorElementForSelection(selection);\n const textLayer = anchorElement.closest(\".textLayer\");\n if (!textLayer) {\n if (this.#selectedTextNode) {\n this.#highlightToolbar?.hide();\n this.#selectedTextNode = null;\n this.#dispatchUpdateStates({\n hasSelectedText: false,\n });\n }\n return;\n }\n\n this.#highlightToolbar?.hide();\n this.#selectedTextNode = anchorNode;\n this.#dispatchUpdateStates({\n hasSelectedText: true,\n });\n\n if (\n this.#mode !== AnnotationEditorType.HIGHLIGHT &&\n this.#mode !== AnnotationEditorType.NONE\n ) {\n return;\n }\n\n if (this.#mode === AnnotationEditorType.HIGHLIGHT) {\n this.showAllEditors(\"highlight\", true, /* updateButton = */ true);\n }\n\n this.#highlightWhenShiftUp = this.isShiftKeyDown;\n if (!this.isShiftKeyDown) {\n const activeLayer =\n this.#mode === AnnotationEditorType.HIGHLIGHT\n ? this.#getLayerForTextLayer(textLayer)\n : null;\n activeLayer?.toggleDrawing();\n\n const ac = new AbortController();\n const signal = this.combinedSignal(ac);\n\n const pointerup = e => {\n if (e.type === \"pointerup\" && e.button !== 0) {\n // Do nothing on right click.\n return;\n }\n ac.abort();\n activeLayer?.toggleDrawing(true);\n if (e.type === \"pointerup\") {\n this.#onSelectEnd(\"main_toolbar\");\n }\n };\n window.addEventListener(\"pointerup\", pointerup, { signal });\n window.addEventListener(\"blur\", pointerup, { signal });\n }\n }\n\n #onSelectEnd(methodOfCreation = \"\") {\n if (this.#mode === AnnotationEditorType.HIGHLIGHT) {\n this.highlightSelection(methodOfCreation);\n } else if (this.#enableHighlightFloatingButton) {\n this.#displayHighlightToolbar();\n }\n }\n\n #addSelectionListener() {\n document.addEventListener(\n \"selectionchange\",\n this.#selectionChange.bind(this),\n { signal: this._signal }\n );\n }\n\n #addFocusManager() {\n if (this.#focusManagerAC) {\n return;\n }\n this.#focusManagerAC = new AbortController();\n const signal = this.combinedSignal(this.#focusManagerAC);\n\n window.addEventListener(\"focus\", this.focus.bind(this), { signal });\n window.addEventListener(\"blur\", this.blur.bind(this), { signal });\n }\n\n #removeFocusManager() {\n this.#focusManagerAC?.abort();\n this.#focusManagerAC = null;\n }\n\n blur() {\n this.isShiftKeyDown = false;\n if (this.#highlightWhenShiftUp) {\n this.#highlightWhenShiftUp = false;\n this.#onSelectEnd(\"main_toolbar\");\n }\n if (!this.hasSelection) {\n return;\n }\n // When several editors are selected and the window loses focus, we want to\n // keep the last active element in order to be able to focus it again when\n // the window gets the focus back but we don't want to trigger any focus\n // callbacks else only one editor will be selected.\n const { activeElement } = document;\n for (const editor of this.#selectedEditors) {\n if (editor.div.contains(activeElement)) {\n this.#lastActiveElement = [editor, activeElement];\n editor._focusEventsAllowed = false;\n break;\n }\n }\n }\n\n focus() {\n if (!this.#lastActiveElement) {\n return;\n }\n const [lastEditor, lastActiveElement] = this.#lastActiveElement;\n this.#lastActiveElement = null;\n lastActiveElement.addEventListener(\n \"focusin\",\n () => {\n lastEditor._focusEventsAllowed = true;\n },\n { once: true, signal: this._signal }\n );\n lastActiveElement.focus();\n }\n\n #addKeyboardManager() {\n if (this.#keyboardManagerAC) {\n return;\n }\n this.#keyboardManagerAC = new AbortController();\n const signal = this.combinedSignal(this.#keyboardManagerAC);\n\n // The keyboard events are caught at the container level in order to be able\n // to execute some callbacks even if the current page doesn't have focus.\n window.addEventListener(\"keydown\", this.keydown.bind(this), { signal });\n window.addEventListener(\"keyup\", this.keyup.bind(this), { signal });\n }\n\n #removeKeyboardManager() {\n this.#keyboardManagerAC?.abort();\n this.#keyboardManagerAC = null;\n }\n\n #addCopyPasteListeners() {\n if (this.#copyPasteAC) {\n return;\n }\n this.#copyPasteAC = new AbortController();\n const signal = this.combinedSignal(this.#copyPasteAC);\n\n document.addEventListener(\"copy\", this.copy.bind(this), { signal });\n document.addEventListener(\"cut\", this.cut.bind(this), { signal });\n document.addEventListener(\"paste\", this.paste.bind(this), { signal });\n }\n\n #removeCopyPasteListeners() {\n this.#copyPasteAC?.abort();\n this.#copyPasteAC = null;\n }\n\n #addDragAndDropListeners() {\n const signal = this._signal;\n document.addEventListener(\"dragover\", this.dragOver.bind(this), { signal });\n document.addEventListener(\"drop\", this.drop.bind(this), { signal });\n }\n\n addEditListeners() {\n this.#addKeyboardManager();\n this.#addCopyPasteListeners();\n }\n\n removeEditListeners() {\n this.#removeKeyboardManager();\n this.#removeCopyPasteListeners();\n }\n\n dragOver(event) {\n for (const { type } of event.dataTransfer.items) {\n for (const editorType of this.#editorTypes) {\n if (editorType.isHandlingMimeForPasting(type)) {\n event.dataTransfer.dropEffect = \"copy\";\n event.preventDefault();\n return;\n }\n }\n }\n }\n\n /**\n * Drop callback.\n * @param {DragEvent} event\n */\n drop(event) {\n for (const item of event.dataTransfer.items) {\n for (const editorType of this.#editorTypes) {\n if (editorType.isHandlingMimeForPasting(item.type)) {\n editorType.paste(item, this.currentLayer);\n event.preventDefault();\n return;\n }\n }\n }\n }\n\n /**\n * Copy callback.\n * @param {ClipboardEvent} event\n */\n copy(event) {\n event.preventDefault();\n\n // An editor is being edited so just commit it.\n this.#activeEditor?.commitOrRemove();\n\n if (!this.hasSelection) {\n return;\n }\n\n const editors = [];\n for (const editor of this.#selectedEditors) {\n const serialized = editor.serialize(/* isForCopying = */ true);\n if (serialized) {\n editors.push(serialized);\n }\n }\n if (editors.length === 0) {\n return;\n }\n\n event.clipboardData.setData(\"application/pdfjs\", JSON.stringify(editors));\n }\n\n /**\n * Cut callback.\n * @param {ClipboardEvent} event\n */\n cut(event) {\n this.copy(event);\n this.delete();\n }\n\n /**\n * Paste callback.\n * @param {ClipboardEvent} event\n */\n paste(event) {\n event.preventDefault();\n const { clipboardData } = event;\n for (const item of clipboardData.items) {\n for (const editorType of this.#editorTypes) {\n if (editorType.isHandlingMimeForPasting(item.type)) {\n editorType.paste(item, this.currentLayer);\n return;\n }\n }\n }\n\n let data = clipboardData.getData(\"application/pdfjs\");\n if (!data) {\n return;\n }\n\n try {\n data = JSON.parse(data);\n } catch (ex) {\n warn(`paste: \"${ex.message}\".`);\n return;\n }\n\n if (!Array.isArray(data)) {\n return;\n }\n\n this.unselectAll();\n const layer = this.currentLayer;\n\n try {\n const newEditors = [];\n for (const editor of data) {\n const deserializedEditor = layer.deserialize(editor);\n if (!deserializedEditor) {\n return;\n }\n newEditors.push(deserializedEditor);\n }\n\n const cmd = () => {\n for (const editor of newEditors) {\n this.#addEditorToLayer(editor);\n }\n this.#selectEditors(newEditors);\n };\n const undo = () => {\n for (const editor of newEditors) {\n editor.remove();\n }\n };\n this.addCommands({ cmd, undo, mustExec: true });\n } catch (ex) {\n warn(`paste: \"${ex.message}\".`);\n }\n }\n\n /**\n * Keydown callback.\n * @param {KeyboardEvent} event\n */\n keydown(event) {\n if (!this.isShiftKeyDown && event.key === \"Shift\") {\n this.isShiftKeyDown = true;\n }\n if (\n this.#mode !== AnnotationEditorType.NONE &&\n !this.isEditorHandlingKeyboard\n ) {\n AnnotationEditorUIManager._keyboardManager.exec(this, event);\n }\n }\n\n /**\n * Keyup callback.\n * @param {KeyboardEvent} event\n */\n keyup(event) {\n if (this.isShiftKeyDown && event.key === \"Shift\") {\n this.isShiftKeyDown = false;\n if (this.#highlightWhenShiftUp) {\n this.#highlightWhenShiftUp = false;\n this.#onSelectEnd(\"main_toolbar\");\n }\n }\n }\n\n /**\n * Execute an action for a given name.\n * For example, the user can click on the \"Undo\" entry in the context menu\n * and it'll trigger the undo action.\n */\n onEditingAction({ name }) {\n switch (name) {\n case \"undo\":\n case \"redo\":\n case \"delete\":\n case \"selectAll\":\n this[name]();\n break;\n case \"highlightSelection\":\n this.highlightSelection(\"context_menu\");\n break;\n }\n }\n\n /**\n * Update the different possible states of this manager, e.g. is there\n * something to undo, redo, ...\n * @param {Object} details\n */\n #dispatchUpdateStates(details) {\n const hasChanged = Object.entries(details).some(\n ([key, value]) => this.#previousStates[key] !== value\n );\n\n if (hasChanged) {\n this._eventBus.dispatch(\"annotationeditorstateschanged\", {\n source: this,\n details: Object.assign(this.#previousStates, details),\n });\n // We could listen on our own event but it sounds like a bit weird and\n // it's a way to simpler to handle that stuff here instead of having to\n // add something in every place where an editor can be unselected.\n if (\n this.#mode === AnnotationEditorType.HIGHLIGHT &&\n details.hasSelectedEditor === false\n ) {\n this.#dispatchUpdateUI([\n [AnnotationEditorParamsType.HIGHLIGHT_FREE, true],\n ]);\n }\n }\n }\n\n #dispatchUpdateUI(details) {\n this._eventBus.dispatch(\"annotationeditorparamschanged\", {\n source: this,\n details,\n });\n }\n\n /**\n * Set the editing state.\n * It can be useful to temporarily disable it when the user is editing a\n * FreeText annotation.\n * @param {boolean} isEditing\n */\n setEditingState(isEditing) {\n if (isEditing) {\n this.#addFocusManager();\n this.#addCopyPasteListeners();\n this.#dispatchUpdateStates({\n isEditing: this.#mode !== AnnotationEditorType.NONE,\n isEmpty: this.#isEmpty(),\n hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),\n hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),\n hasSelectedEditor: false,\n });\n } else {\n this.#removeFocusManager();\n this.#removeCopyPasteListeners();\n this.#dispatchUpdateStates({\n isEditing: false,\n });\n this.disableUserSelect(false);\n }\n }\n\n registerEditorTypes(types) {\n if (this.#editorTypes) {\n return;\n }\n this.#editorTypes = types;\n for (const editorType of this.#editorTypes) {\n this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate);\n }\n }\n\n /**\n * Get an id.\n * @returns {string}\n */\n getId() {\n return this.#idManager.id;\n }\n\n get currentLayer() {\n return this.#allLayers.get(this.#currentPageIndex);\n }\n\n getLayer(pageIndex) {\n return this.#allLayers.get(pageIndex);\n }\n\n get currentPageIndex() {\n return this.#currentPageIndex;\n }\n\n /**\n * Add a new layer for a page which will contains the editors.\n * @param {AnnotationEditorLayer} layer\n */\n addLayer(layer) {\n this.#allLayers.set(layer.pageIndex, layer);\n if (this.#isEnabled) {\n layer.enable();\n } else {\n layer.disable();\n }\n }\n\n /**\n * Remove a layer.\n * @param {AnnotationEditorLayer} layer\n */\n removeLayer(layer) {\n this.#allLayers.delete(layer.pageIndex);\n }\n\n /**\n * Change the editor mode (None, FreeText, Ink, ...)\n * @param {number} mode\n * @param {string|null} editId\n * @param {boolean} [isFromKeyboard] - true if the mode change is due to a\n * keyboard action.\n */\n updateMode(mode, editId = null, isFromKeyboard = false) {\n if (this.#mode === mode) {\n return;\n }\n this.#mode = mode;\n if (mode === AnnotationEditorType.NONE) {\n this.setEditingState(false);\n this.#disableAll();\n return;\n }\n this.setEditingState(true);\n this.#enableAll();\n this.unselectAll();\n for (const layer of this.#allLayers.values()) {\n layer.updateMode(mode);\n }\n if (!editId && isFromKeyboard) {\n this.addNewEditorFromKeyboard();\n return;\n }\n\n if (!editId) {\n return;\n }\n for (const editor of this.#allEditors.values()) {\n if (editor.annotationElementId === editId) {\n this.setSelected(editor);\n editor.enterInEditMode();\n break;\n }\n }\n }\n\n addNewEditorFromKeyboard() {\n if (this.currentLayer.canCreateNewEmptyEditor()) {\n this.currentLayer.addNewEditor();\n }\n }\n\n /**\n * Update the toolbar if it's required to reflect the tool currently used.\n * @param {number} mode\n * @returns {undefined}\n */\n updateToolbar(mode) {\n if (mode === this.#mode) {\n return;\n }\n this._eventBus.dispatch(\"switchannotationeditormode\", {\n source: this,\n mode,\n });\n }\n\n /**\n * Update a parameter in the current editor or globally.\n * @param {number} type\n * @param {*} value\n */\n updateParams(type, value) {\n if (!this.#editorTypes) {\n return;\n }\n\n switch (type) {\n case AnnotationEditorParamsType.CREATE:\n this.currentLayer.addNewEditor();\n return;\n case AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR:\n this.#mainHighlightColorPicker?.updateColor(value);\n break;\n case AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL:\n this._eventBus.dispatch(\"reporttelemetry\", {\n source: this,\n details: {\n type: \"editing\",\n data: {\n type: \"highlight\",\n action: \"toggle_visibility\",\n },\n },\n });\n (this.#showAllStates ||= new Map()).set(type, value);\n this.showAllEditors(\"highlight\", value);\n break;\n }\n\n for (const editor of this.#selectedEditors) {\n editor.updateParams(type, value);\n }\n\n for (const editorType of this.#editorTypes) {\n editorType.updateDefaultParams(type, value);\n }\n }\n\n showAllEditors(type, visible, updateButton = false) {\n for (const editor of this.#allEditors.values()) {\n if (editor.editorType === type) {\n editor.show(visible);\n }\n }\n const state =\n this.#showAllStates?.get(AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL) ??\n true;\n if (state !== visible) {\n this.#dispatchUpdateUI([\n [AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL, visible],\n ]);\n }\n }\n\n enableWaiting(mustWait = false) {\n if (this.#isWaiting === mustWait) {\n return;\n }\n this.#isWaiting = mustWait;\n for (const layer of this.#allLayers.values()) {\n if (mustWait) {\n layer.disableClick();\n } else {\n layer.enableClick();\n }\n layer.div.classList.toggle(\"waiting\", mustWait);\n }\n }\n\n /**\n * Enable all the layers.\n */\n #enableAll() {\n if (!this.#isEnabled) {\n this.#isEnabled = true;\n for (const layer of this.#allLayers.values()) {\n layer.enable();\n }\n for (const editor of this.#allEditors.values()) {\n editor.enable();\n }\n }\n }\n\n /**\n * Disable all the layers.\n */\n #disableAll() {\n this.unselectAll();\n if (this.#isEnabled) {\n this.#isEnabled = false;\n for (const layer of this.#allLayers.values()) {\n layer.disable();\n }\n for (const editor of this.#allEditors.values()) {\n editor.disable();\n }\n }\n }\n\n /**\n * Get all the editors belonging to a given page.\n * @param {number} pageIndex\n * @returns {Array}\n */\n getEditors(pageIndex) {\n const editors = [];\n for (const editor of this.#allEditors.values()) {\n if (editor.pageIndex === pageIndex) {\n editors.push(editor);\n }\n }\n return editors;\n }\n\n /**\n * Get an editor with the given id.\n * @param {string} id\n * @returns {AnnotationEditor}\n */\n getEditor(id) {\n return this.#allEditors.get(id);\n }\n\n /**\n * Add a new editor.\n * @param {AnnotationEditor} editor\n */\n addEditor(editor) {\n this.#allEditors.set(editor.id, editor);\n }\n\n /**\n * Remove an editor.\n * @param {AnnotationEditor} editor\n */\n removeEditor(editor) {\n if (editor.div.contains(document.activeElement)) {\n if (this.#focusMainContainerTimeoutId) {\n clearTimeout(this.#focusMainContainerTimeoutId);\n }\n this.#focusMainContainerTimeoutId = setTimeout(() => {\n // When the div is removed from DOM the focus can move on the\n // document.body, so we need to move it back to the main container.\n this.focusMainContainer();\n this.#focusMainContainerTimeoutId = null;\n }, 0);\n }\n this.#allEditors.delete(editor.id);\n this.unselect(editor);\n if (\n !editor.annotationElementId ||\n !this.#deletedAnnotationsElementIds.has(editor.annotationElementId)\n ) {\n this.#annotationStorage?.remove(editor.id);\n }\n }\n\n /**\n * The annotation element with the given id has been deleted.\n * @param {AnnotationEditor} editor\n */\n addDeletedAnnotationElement(editor) {\n this.#deletedAnnotationsElementIds.add(editor.annotationElementId);\n this.addChangedExistingAnnotation(editor);\n editor.deleted = true;\n }\n\n /**\n * Check if the annotation element with the given id has been deleted.\n * @param {string} annotationElementId\n * @returns {boolean}\n */\n isDeletedAnnotationElement(annotationElementId) {\n return this.#deletedAnnotationsElementIds.has(annotationElementId);\n }\n\n /**\n * The annotation element with the given id have been restored.\n * @param {AnnotationEditor} editor\n */\n removeDeletedAnnotationElement(editor) {\n this.#deletedAnnotationsElementIds.delete(editor.annotationElementId);\n this.removeChangedExistingAnnotation(editor);\n editor.deleted = false;\n }\n\n /**\n * Add an editor to the layer it belongs to or add it to the global map.\n * @param {AnnotationEditor} editor\n */\n #addEditorToLayer(editor) {\n const layer = this.#allLayers.get(editor.pageIndex);\n if (layer) {\n layer.addOrRebuild(editor);\n } else {\n this.addEditor(editor);\n this.addToAnnotationStorage(editor);\n }\n }\n\n /**\n * Set the given editor as the active one.\n * @param {AnnotationEditor} editor\n */\n setActiveEditor(editor) {\n if (this.#activeEditor === editor) {\n return;\n }\n\n this.#activeEditor = editor;\n if (editor) {\n this.#dispatchUpdateUI(editor.propertiesToUpdate);\n }\n }\n\n get #lastSelectedEditor() {\n let ed = null;\n for (ed of this.#selectedEditors) {\n // Iterate to get the last element.\n }\n return ed;\n }\n\n /**\n * Update the UI of the active editor.\n * @param {AnnotationEditor} editor\n */\n updateUI(editor) {\n if (this.#lastSelectedEditor === editor) {\n this.#dispatchUpdateUI(editor.propertiesToUpdate);\n }\n }\n\n /**\n * Add or remove an editor the current selection.\n * @param {AnnotationEditor} editor\n */\n toggleSelected(editor) {\n if (this.#selectedEditors.has(editor)) {\n this.#selectedEditors.delete(editor);\n editor.unselect();\n this.#dispatchUpdateStates({\n hasSelectedEditor: this.hasSelection,\n });\n return;\n }\n this.#selectedEditors.add(editor);\n editor.select();\n this.#dispatchUpdateUI(editor.propertiesToUpdate);\n this.#dispatchUpdateStates({\n hasSelectedEditor: true,\n });\n }\n\n /**\n * Set the last selected editor.\n * @param {AnnotationEditor} editor\n */\n setSelected(editor) {\n for (const ed of this.#selectedEditors) {\n if (ed !== editor) {\n ed.unselect();\n }\n }\n this.#selectedEditors.clear();\n\n this.#selectedEditors.add(editor);\n editor.select();\n this.#dispatchUpdateUI(editor.propertiesToUpdate);\n this.#dispatchUpdateStates({\n hasSelectedEditor: true,\n });\n }\n\n /**\n * Check if the editor is selected.\n * @param {AnnotationEditor} editor\n */\n isSelected(editor) {\n return this.#selectedEditors.has(editor);\n }\n\n get firstSelectedEditor() {\n return this.#selectedEditors.values().next().value;\n }\n\n /**\n * Unselect an editor.\n * @param {AnnotationEditor} editor\n */\n unselect(editor) {\n editor.unselect();\n this.#selectedEditors.delete(editor);\n this.#dispatchUpdateStates({\n hasSelectedEditor: this.hasSelection,\n });\n }\n\n get hasSelection() {\n return this.#selectedEditors.size !== 0;\n }\n\n get isEnterHandled() {\n return (\n this.#selectedEditors.size === 1 &&\n this.firstSelectedEditor.isEnterHandled\n );\n }\n\n /**\n * Undo the last command.\n */\n undo() {\n this.#commandManager.undo();\n this.#dispatchUpdateStates({\n hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),\n hasSomethingToRedo: true,\n isEmpty: this.#isEmpty(),\n });\n }\n\n /**\n * Redo the last undoed command.\n */\n redo() {\n this.#commandManager.redo();\n this.#dispatchUpdateStates({\n hasSomethingToUndo: true,\n hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),\n isEmpty: this.#isEmpty(),\n });\n }\n\n /**\n * Add a command to execute (cmd) and another one to undo it.\n * @param {Object} params\n */\n addCommands(params) {\n this.#commandManager.add(params);\n this.#dispatchUpdateStates({\n hasSomethingToUndo: true,\n hasSomethingToRedo: false,\n isEmpty: this.#isEmpty(),\n });\n }\n\n #isEmpty() {\n if (this.#allEditors.size === 0) {\n return true;\n }\n\n if (this.#allEditors.size === 1) {\n for (const editor of this.#allEditors.values()) {\n return editor.isEmpty();\n }\n }\n\n return false;\n }\n\n /**\n * Delete the current editor or all.\n */\n delete() {\n this.commitOrRemove();\n if (!this.hasSelection) {\n return;\n }\n\n const editors = [...this.#selectedEditors];\n const cmd = () => {\n for (const editor of editors) {\n editor.remove();\n }\n };\n const undo = () => {\n for (const editor of editors) {\n this.#addEditorToLayer(editor);\n }\n };\n\n this.addCommands({ cmd, undo, mustExec: true });\n }\n\n commitOrRemove() {\n // An editor is being edited so just commit it.\n this.#activeEditor?.commitOrRemove();\n }\n\n hasSomethingToControl() {\n return this.#activeEditor || this.hasSelection;\n }\n\n /**\n * Select the editors.\n * @param {Array} editors\n */\n #selectEditors(editors) {\n for (const editor of this.#selectedEditors) {\n editor.unselect();\n }\n this.#selectedEditors.clear();\n for (const editor of editors) {\n if (editor.isEmpty()) {\n continue;\n }\n this.#selectedEditors.add(editor);\n editor.select();\n }\n this.#dispatchUpdateStates({ hasSelectedEditor: this.hasSelection });\n }\n\n /**\n * Select all the editors.\n */\n selectAll() {\n for (const editor of this.#selectedEditors) {\n editor.commit();\n }\n this.#selectEditors(this.#allEditors.values());\n }\n\n /**\n * Unselect all the selected editors.\n */\n unselectAll() {\n if (this.#activeEditor) {\n // An editor is being edited so just commit it.\n this.#activeEditor.commitOrRemove();\n if (this.#mode !== AnnotationEditorType.NONE) {\n // If the mode is NONE, we want to really unselect the editor, hence we\n // mustn't return here.\n return;\n }\n }\n\n if (!this.hasSelection) {\n return;\n }\n for (const editor of this.#selectedEditors) {\n editor.unselect();\n }\n this.#selectedEditors.clear();\n this.#dispatchUpdateStates({\n hasSelectedEditor: false,\n });\n }\n\n translateSelectedEditors(x, y, noCommit = false) {\n if (!noCommit) {\n this.commitOrRemove();\n }\n if (!this.hasSelection) {\n return;\n }\n\n this.#translation[0] += x;\n this.#translation[1] += y;\n const [totalX, totalY] = this.#translation;\n const editors = [...this.#selectedEditors];\n\n // We don't want to have an undo/redo for each translation so we wait a bit\n // before adding the command to the command manager.\n const TIME_TO_WAIT = 1000;\n\n if (this.#translationTimeoutId) {\n clearTimeout(this.#translationTimeoutId);\n }\n\n this.#translationTimeoutId = setTimeout(() => {\n this.#translationTimeoutId = null;\n this.#translation[0] = this.#translation[1] = 0;\n\n this.addCommands({\n cmd: () => {\n for (const editor of editors) {\n if (this.#allEditors.has(editor.id)) {\n editor.translateInPage(totalX, totalY);\n }\n }\n },\n undo: () => {\n for (const editor of editors) {\n if (this.#allEditors.has(editor.id)) {\n editor.translateInPage(-totalX, -totalY);\n }\n }\n },\n mustExec: false,\n });\n }, TIME_TO_WAIT);\n\n for (const editor of editors) {\n editor.translateInPage(x, y);\n }\n }\n\n /**\n * Set up the drag session for moving the selected editors.\n */\n setUpDragSession() {\n // Note: don't use any references to the editor's parent which can be null\n // if the editor belongs to a destroyed page.\n if (!this.hasSelection) {\n return;\n }\n // Avoid to have spurious text selection in the text layer when dragging.\n this.disableUserSelect(true);\n this.#draggingEditors = new Map();\n for (const editor of this.#selectedEditors) {\n this.#draggingEditors.set(editor, {\n savedX: editor.x,\n savedY: editor.y,\n savedPageIndex: editor.pageIndex,\n newX: 0,\n newY: 0,\n newPageIndex: -1,\n });\n }\n }\n\n /**\n * Ends the drag session.\n * @returns {boolean} true if at least one editor has been moved.\n */\n endDragSession() {\n if (!this.#draggingEditors) {\n return false;\n }\n this.disableUserSelect(false);\n const map = this.#draggingEditors;\n this.#draggingEditors = null;\n let mustBeAddedInUndoStack = false;\n\n for (const [{ x, y, pageIndex }, value] of map) {\n value.newX = x;\n value.newY = y;\n value.newPageIndex = pageIndex;\n mustBeAddedInUndoStack ||=\n x !== value.savedX ||\n y !== value.savedY ||\n pageIndex !== value.savedPageIndex;\n }\n\n if (!mustBeAddedInUndoStack) {\n return false;\n }\n\n const move = (editor, x, y, pageIndex) => {\n if (this.#allEditors.has(editor.id)) {\n // The editor can be undone/redone on a page which is not visible (and\n // which potentially has no annotation editor layer), hence we need to\n // use the pageIndex instead of the parent.\n const parent = this.#allLayers.get(pageIndex);\n if (parent) {\n editor._setParentAndPosition(parent, x, y);\n } else {\n editor.pageIndex = pageIndex;\n editor.x = x;\n editor.y = y;\n }\n }\n };\n\n this.addCommands({\n cmd: () => {\n for (const [editor, { newX, newY, newPageIndex }] of map) {\n move(editor, newX, newY, newPageIndex);\n }\n },\n undo: () => {\n for (const [editor, { savedX, savedY, savedPageIndex }] of map) {\n move(editor, savedX, savedY, savedPageIndex);\n }\n },\n mustExec: true,\n });\n\n return true;\n }\n\n /**\n * Drag the set of selected editors.\n * @param {number} tx\n * @param {number} ty\n */\n dragSelectedEditors(tx, ty) {\n if (!this.#draggingEditors) {\n return;\n }\n for (const editor of this.#draggingEditors.keys()) {\n editor.drag(tx, ty);\n }\n }\n\n /**\n * Rebuild the editor (usually on undo/redo actions) on a potentially\n * non-rendered page.\n * @param {AnnotationEditor} editor\n */\n rebuild(editor) {\n if (editor.parent === null) {\n const parent = this.getLayer(editor.pageIndex);\n if (parent) {\n parent.changeParent(editor);\n parent.addOrRebuild(editor);\n } else {\n this.addEditor(editor);\n this.addToAnnotationStorage(editor);\n editor.rebuild();\n }\n } else {\n editor.parent.addOrRebuild(editor);\n }\n }\n\n get isEditorHandlingKeyboard() {\n return (\n this.getActive()?.shouldGetKeyboardEvents() ||\n (this.#selectedEditors.size === 1 &&\n this.firstSelectedEditor.shouldGetKeyboardEvents())\n );\n }\n\n /**\n * Is the current editor the one passed as argument?\n * @param {AnnotationEditor} editor\n * @returns\n */\n isActive(editor) {\n return this.#activeEditor === editor;\n }\n\n /**\n * Get the current active editor.\n * @returns {AnnotationEditor|null}\n */\n getActive() {\n return this.#activeEditor;\n }\n\n /**\n * Get the current editor mode.\n * @returns {number}\n */\n getMode() {\n return this.#mode;\n }\n\n get imageManager() {\n return shadow(this, \"imageManager\", new ImageManager());\n }\n\n getSelectionBoxes(textLayer) {\n if (!textLayer) {\n return null;\n }\n const selection = document.getSelection();\n for (let i = 0, ii = selection.rangeCount; i < ii; i++) {\n if (\n !textLayer.contains(selection.getRangeAt(i).commonAncestorContainer)\n ) {\n return null;\n }\n }\n\n const {\n x: layerX,\n y: layerY,\n width: parentWidth,\n height: parentHeight,\n } = textLayer.getBoundingClientRect();\n\n // We must rotate the boxes because we want to have them in the non-rotated\n // page coordinates.\n let rotator;\n switch (textLayer.getAttribute(\"data-main-rotation\")) {\n case \"90\":\n rotator = (x, y, w, h) => ({\n x: (y - layerY) / parentHeight,\n y: 1 - (x + w - layerX) / parentWidth,\n width: h / parentHeight,\n height: w / parentWidth,\n });\n break;\n case \"180\":\n rotator = (x, y, w, h) => ({\n x: 1 - (x + w - layerX) / parentWidth,\n y: 1 - (y + h - layerY) / parentHeight,\n width: w / parentWidth,\n height: h / parentHeight,\n });\n break;\n case \"270\":\n rotator = (x, y, w, h) => ({\n x: 1 - (y + h - layerY) / parentHeight,\n y: (x - layerX) / parentWidth,\n width: h / parentHeight,\n height: w / parentWidth,\n });\n break;\n default:\n rotator = (x, y, w, h) => ({\n x: (x - layerX) / parentWidth,\n y: (y - layerY) / parentHeight,\n width: w / parentWidth,\n height: h / parentHeight,\n });\n break;\n }\n\n const boxes = [];\n for (let i = 0, ii = selection.rangeCount; i < ii; i++) {\n const range = selection.getRangeAt(i);\n if (range.collapsed) {\n continue;\n }\n for (const { x, y, width, height } of range.getClientRects()) {\n if (width === 0 || height === 0) {\n continue;\n }\n boxes.push(rotator(x, y, width, height));\n }\n }\n return boxes.length === 0 ? null : boxes;\n }\n\n addChangedExistingAnnotation({ annotationElementId, id }) {\n (this.#changedExistingAnnotations ||= new Map()).set(\n annotationElementId,\n id\n );\n }\n\n removeChangedExistingAnnotation({ annotationElementId }) {\n this.#changedExistingAnnotations?.delete(annotationElementId);\n }\n\n renderAnnotationElement(annotation) {\n const editorId = this.#changedExistingAnnotations?.get(annotation.data.id);\n if (!editorId) {\n return;\n }\n const editor = this.#annotationStorage.getRawValue(editorId);\n if (!editor) {\n return;\n }\n if (this.#mode === AnnotationEditorType.NONE && !editor.hasBeenModified) {\n return;\n }\n editor.renderAnnotationElement(annotation);\n }\n}\n\nexport {\n AnnotationEditorUIManager,\n bindEvents,\n ColorManager,\n CommandManager,\n KeyboardManager,\n opacityToHex,\n};\n","/* Copyright 2023 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { noContextMenu } from \"../display_utils.js\";\n\nclass AltText {\n #altText = null;\n\n #altTextDecorative = false;\n\n #altTextButton = null;\n\n #altTextTooltip = null;\n\n #altTextTooltipTimeout = null;\n\n #altTextWasFromKeyBoard = false;\n\n #badge = null;\n\n #editor = null;\n\n #guessedText = null;\n\n #textWithDisclaimer = null;\n\n #useNewAltTextFlow = false;\n\n static _l10nPromise = null;\n\n constructor(editor) {\n this.#editor = editor;\n this.#useNewAltTextFlow = editor._uiManager.useNewAltTextFlow;\n }\n\n static initialize(l10nPromise) {\n AltText._l10nPromise ||= l10nPromise;\n }\n\n async render() {\n const altText = (this.#altTextButton = document.createElement(\"button\"));\n altText.className = \"altText\";\n let msg;\n if (this.#useNewAltTextFlow) {\n altText.classList.add(\"new\");\n msg = await AltText._l10nPromise.get(\n \"pdfjs-editor-new-alt-text-missing-button-label\"\n );\n } else {\n msg = await AltText._l10nPromise.get(\n \"pdfjs-editor-alt-text-button-label\"\n );\n }\n altText.textContent = msg;\n altText.setAttribute(\"aria-label\", msg);\n altText.tabIndex = \"0\";\n const signal = this.#editor._uiManager._signal;\n altText.addEventListener(\"contextmenu\", noContextMenu, { signal });\n altText.addEventListener(\"pointerdown\", event => event.stopPropagation(), {\n signal,\n });\n\n const onClick = event => {\n event.preventDefault();\n this.#editor._uiManager.editAltText(this.#editor);\n if (this.#useNewAltTextFlow) {\n this.#editor._reportTelemetry({\n action: \"pdfjs.image.alt_text.image_status_label_clicked\",\n data: { label: this.#label },\n });\n }\n };\n altText.addEventListener(\"click\", onClick, { capture: true, signal });\n altText.addEventListener(\n \"keydown\",\n event => {\n if (event.target === altText && event.key === \"Enter\") {\n this.#altTextWasFromKeyBoard = true;\n onClick(event);\n }\n },\n { signal }\n );\n await this.#setState();\n\n return altText;\n }\n\n get #label() {\n return (\n (this.#altText && \"added\") ||\n (this.#altText === null && this.guessedText && \"review\") ||\n \"missing\"\n );\n }\n\n finish() {\n if (!this.#altTextButton) {\n return;\n }\n this.#altTextButton.focus({ focusVisible: this.#altTextWasFromKeyBoard });\n this.#altTextWasFromKeyBoard = false;\n }\n\n isEmpty() {\n if (this.#useNewAltTextFlow) {\n return this.#altText === null;\n }\n return !this.#altText && !this.#altTextDecorative;\n }\n\n hasData() {\n if (this.#useNewAltTextFlow) {\n return this.#altText !== null || !!this.#guessedText;\n }\n return this.isEmpty();\n }\n\n get guessedText() {\n return this.#guessedText;\n }\n\n async setGuessedText(guessedText) {\n if (this.#altText !== null) {\n // The user provided their own alt text, so we don't want to overwrite it.\n return;\n }\n this.#guessedText = guessedText;\n this.#textWithDisclaimer = await AltText._l10nPromise.get(\n \"pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer\"\n )({ generatedAltText: guessedText });\n this.#setState();\n }\n\n toggleAltTextBadge(visibility = false) {\n if (!this.#useNewAltTextFlow || this.#altText) {\n this.#badge?.remove();\n this.#badge = null;\n return;\n }\n if (!this.#badge) {\n const badge = (this.#badge = document.createElement(\"div\"));\n badge.className = \"noAltTextBadge\";\n this.#editor.div.append(badge);\n }\n this.#badge.classList.toggle(\"hidden\", !visibility);\n }\n\n serialize(isForCopying) {\n let altText = this.#altText;\n if (!isForCopying && this.#guessedText === altText) {\n altText = this.#textWithDisclaimer;\n }\n return {\n altText,\n decorative: this.#altTextDecorative,\n guessedText: this.#guessedText,\n textWithDisclaimer: this.#textWithDisclaimer,\n };\n }\n\n get data() {\n return {\n altText: this.#altText,\n decorative: this.#altTextDecorative,\n };\n }\n\n /**\n * Set the alt text data.\n */\n set data({\n altText,\n decorative,\n guessedText,\n textWithDisclaimer,\n cancel = false,\n }) {\n if (guessedText) {\n this.#guessedText = guessedText;\n this.#textWithDisclaimer = textWithDisclaimer;\n }\n if (this.#altText === altText && this.#altTextDecorative === decorative) {\n return;\n }\n if (!cancel) {\n this.#altText = altText;\n this.#altTextDecorative = decorative;\n }\n this.#setState();\n }\n\n toggle(enabled = false) {\n if (!this.#altTextButton) {\n return;\n }\n if (!enabled && this.#altTextTooltipTimeout) {\n clearTimeout(this.#altTextTooltipTimeout);\n this.#altTextTooltipTimeout = null;\n }\n this.#altTextButton.disabled = !enabled;\n }\n\n shown() {\n this.#editor._reportTelemetry({\n action: \"pdfjs.image.alt_text.image_status_label_displayed\",\n data: { label: this.#label },\n });\n }\n\n destroy() {\n this.#altTextButton?.remove();\n this.#altTextButton = null;\n this.#altTextTooltip = null;\n this.#badge?.remove();\n this.#badge = null;\n }\n\n async #setState() {\n const button = this.#altTextButton;\n if (!button) {\n return;\n }\n\n if (this.#useNewAltTextFlow) {\n // If we've an alt text, we get an \"added\".\n // If we've a guessed text and the alt text has never been set, we get a\n // \"to-review\" been set.\n // Otherwise, we get a \"missing\".\n const label = this.#label;\n // TODO: Update the l10n keys to avoid this.\n const type = label === \"review\" ? \"to-review\" : label;\n button.classList.toggle(\"done\", !!this.#altText);\n AltText._l10nPromise\n .get(`pdfjs-editor-new-alt-text-${type}-button-label`)\n .then(msg => {\n button.setAttribute(\"aria-label\", msg);\n // We can't just use button.textContent here, because it would remove\n // the existing tooltip element.\n for (const child of button.childNodes) {\n if (child.nodeType === Node.TEXT_NODE) {\n child.textContent = msg;\n break;\n }\n }\n });\n if (!this.#altText) {\n this.#altTextTooltip?.remove();\n return;\n }\n } else {\n if (!this.#altText && !this.#altTextDecorative) {\n button.classList.remove(\"done\");\n this.#altTextTooltip?.remove();\n return;\n }\n button.classList.add(\"done\");\n AltText._l10nPromise\n .get(\"pdfjs-editor-alt-text-edit-button-label\")\n .then(msg => {\n button.setAttribute(\"aria-label\", msg);\n });\n }\n\n let tooltip = this.#altTextTooltip;\n if (!tooltip) {\n this.#altTextTooltip = tooltip = document.createElement(\"span\");\n tooltip.className = \"tooltip\";\n tooltip.setAttribute(\"role\", \"tooltip\");\n const id = (tooltip.id = `alt-text-tooltip-${this.#editor.id}`);\n button.setAttribute(\"aria-describedby\", id);\n\n const DELAY_TO_SHOW_TOOLTIP = 100;\n const signal = this.#editor._uiManager._signal;\n signal.addEventListener(\n \"abort\",\n () => {\n clearTimeout(this.#altTextTooltipTimeout);\n this.#altTextTooltipTimeout = null;\n },\n { once: true }\n );\n button.addEventListener(\n \"mouseenter\",\n () => {\n this.#altTextTooltipTimeout = setTimeout(() => {\n this.#altTextTooltipTimeout = null;\n this.#altTextTooltip.classList.add(\"show\");\n this.#editor._reportTelemetry({\n action: \"alt_text_tooltip\",\n });\n }, DELAY_TO_SHOW_TOOLTIP);\n },\n { signal }\n );\n button.addEventListener(\n \"mouseleave\",\n () => {\n if (this.#altTextTooltipTimeout) {\n clearTimeout(this.#altTextTooltipTimeout);\n this.#altTextTooltipTimeout = null;\n }\n this.#altTextTooltip?.classList.remove(\"show\");\n },\n { signal }\n );\n }\n tooltip.innerText = this.#altTextDecorative\n ? await AltText._l10nPromise.get(\n \"pdfjs-editor-alt-text-decorative-tooltip\"\n )\n : this.#altText;\n\n if (!tooltip.parentNode) {\n button.append(tooltip);\n }\n\n const element = this.#editor.getImageForAltText();\n element?.setAttribute(\"aria-describedby\", tooltip.id);\n }\n}\n\nexport { AltText };\n","/* Copyright 2022 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line max-len\n/** @typedef {import(\"./annotation_editor_layer.js\").AnnotationEditorLayer} AnnotationEditorLayer */\n\nimport {\n AnnotationEditorUIManager,\n bindEvents,\n ColorManager,\n KeyboardManager,\n} from \"./tools.js\";\nimport { FeatureTest, shadow, unreachable } from \"../../shared/util.js\";\nimport { AltText } from \"./alt_text.js\";\nimport { EditorToolbar } from \"./toolbar.js\";\nimport { noContextMenu } from \"../display_utils.js\";\n\n/**\n * @typedef {Object} AnnotationEditorParameters\n * @property {AnnotationEditorUIManager} uiManager - the global manager\n * @property {AnnotationEditorLayer} parent - the layer containing this editor\n * @property {string} id - editor id\n * @property {number} x - x-coordinate\n * @property {number} y - y-coordinate\n */\n\n/**\n * Base class for editors.\n */\nclass AnnotationEditor {\n #accessibilityData = null;\n\n #allResizerDivs = null;\n\n #altText = null;\n\n #disabled = false;\n\n #keepAspectRatio = false;\n\n #resizersDiv = null;\n\n #savedDimensions = null;\n\n #focusAC = null;\n\n #focusedResizerName = \"\";\n\n #hasBeenClicked = false;\n\n #initialPosition = null;\n\n #isEditing = false;\n\n #isInEditMode = false;\n\n #isResizerEnabledForKeyboard = false;\n\n #moveInDOMTimeout = null;\n\n #prevDragX = 0;\n\n #prevDragY = 0;\n\n #telemetryTimeouts = null;\n\n _editToolbar = null;\n\n _initialOptions = Object.create(null);\n\n _isVisible = true;\n\n _uiManager = null;\n\n _focusEventsAllowed = true;\n\n static _l10nPromise = null;\n\n static _l10nResizer = null;\n\n #isDraggable = false;\n\n #zIndex = AnnotationEditor._zIndex++;\n\n static _borderLineWidth = -1;\n\n static _colorManager = new ColorManager();\n\n static _zIndex = 1;\n\n // Time to wait (in ms) before sending the telemetry data.\n // We wait a bit to avoid sending too many requests when changing something\n // like the thickness of a line.\n static _telemetryTimeout = 1000;\n\n static get _resizerKeyboardManager() {\n const resize = AnnotationEditor.prototype._resizeWithKeyboard;\n const small = AnnotationEditorUIManager.TRANSLATE_SMALL;\n const big = AnnotationEditorUIManager.TRANSLATE_BIG;\n\n return shadow(\n this,\n \"_resizerKeyboardManager\",\n new KeyboardManager([\n [[\"ArrowLeft\", \"mac+ArrowLeft\"], resize, { args: [-small, 0] }],\n [\n [\"ctrl+ArrowLeft\", \"mac+shift+ArrowLeft\"],\n resize,\n { args: [-big, 0] },\n ],\n [[\"ArrowRight\", \"mac+ArrowRight\"], resize, { args: [small, 0] }],\n [\n [\"ctrl+ArrowRight\", \"mac+shift+ArrowRight\"],\n resize,\n { args: [big, 0] },\n ],\n [[\"ArrowUp\", \"mac+ArrowUp\"], resize, { args: [0, -small] }],\n [[\"ctrl+ArrowUp\", \"mac+shift+ArrowUp\"], resize, { args: [0, -big] }],\n [[\"ArrowDown\", \"mac+ArrowDown\"], resize, { args: [0, small] }],\n [[\"ctrl+ArrowDown\", \"mac+shift+ArrowDown\"], resize, { args: [0, big] }],\n [\n [\"Escape\", \"mac+Escape\"],\n AnnotationEditor.prototype._stopResizingWithKeyboard,\n ],\n ])\n );\n }\n\n /**\n * @param {AnnotationEditorParameters} parameters\n */\n constructor(parameters) {\n if (\n (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) &&\n this.constructor === AnnotationEditor\n ) {\n unreachable(\"Cannot initialize AnnotationEditor.\");\n }\n\n this.parent = parameters.parent;\n this.id = parameters.id;\n this.width = this.height = null;\n this.pageIndex = parameters.parent.pageIndex;\n this.name = parameters.name;\n this.div = null;\n this._uiManager = parameters.uiManager;\n this.annotationElementId = null;\n this._willKeepAspectRatio = false;\n this._initialOptions.isCentered = parameters.isCentered;\n this._structTreeParentId = null;\n\n const {\n rotation,\n rawDims: { pageWidth, pageHeight, pageX, pageY },\n } = this.parent.viewport;\n\n this.rotation = rotation;\n this.pageRotation =\n (360 + rotation - this._uiManager.viewParameters.rotation) % 360;\n this.pageDimensions = [pageWidth, pageHeight];\n this.pageTranslation = [pageX, pageY];\n\n const [width, height] = this.parentDimensions;\n this.x = parameters.x / width;\n this.y = parameters.y / height;\n\n this.isAttachedToDOM = false;\n this.deleted = false;\n }\n\n get editorType() {\n return Object.getPrototypeOf(this).constructor._type;\n }\n\n static get _defaultLineColor() {\n return shadow(\n this,\n \"_defaultLineColor\",\n this._colorManager.getHexCode(\"CanvasText\")\n );\n }\n\n static deleteAnnotationElement(editor) {\n const fakeEditor = new FakeEditor({\n id: editor.parent.getNextId(),\n parent: editor.parent,\n uiManager: editor._uiManager,\n });\n fakeEditor.annotationElementId = editor.annotationElementId;\n fakeEditor.deleted = true;\n fakeEditor._uiManager.addToAnnotationStorage(fakeEditor);\n }\n\n /**\n * Initialize the l10n stuff for this type of editor.\n * @param {Object} l10n\n */\n static initialize(l10n, _uiManager, options) {\n AnnotationEditor._l10nResizer ||= Object.freeze({\n topLeft: \"pdfjs-editor-resizer-top-left\",\n topMiddle: \"pdfjs-editor-resizer-top-middle\",\n topRight: \"pdfjs-editor-resizer-top-right\",\n middleRight: \"pdfjs-editor-resizer-middle-right\",\n bottomRight: \"pdfjs-editor-resizer-bottom-right\",\n bottomMiddle: \"pdfjs-editor-resizer-bottom-middle\",\n bottomLeft: \"pdfjs-editor-resizer-bottom-left\",\n middleLeft: \"pdfjs-editor-resizer-middle-left\",\n });\n\n AnnotationEditor._l10nPromise ||= new Map([\n ...[\n \"pdfjs-editor-alt-text-button-label\",\n \"pdfjs-editor-alt-text-edit-button-label\",\n \"pdfjs-editor-alt-text-decorative-tooltip\",\n \"pdfjs-editor-new-alt-text-added-button-label\",\n \"pdfjs-editor-new-alt-text-missing-button-label\",\n \"pdfjs-editor-new-alt-text-to-review-button-label\",\n ].map(str => [str, l10n.get(str)]),\n ...[\n // Strings that need l10n-arguments.\n \"pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer\",\n ].map(str => [str, l10n.get.bind(l10n, str)]),\n ]);\n\n if (options?.strings) {\n for (const str of options.strings) {\n AnnotationEditor._l10nPromise.set(str, l10n.get(str));\n }\n }\n if (AnnotationEditor._borderLineWidth !== -1) {\n return;\n }\n const style = getComputedStyle(document.documentElement);\n AnnotationEditor._borderLineWidth =\n parseFloat(style.getPropertyValue(\"--outline-width\")) || 0;\n }\n\n /**\n * Update the default parameters for this type of editor.\n * @param {number} _type\n * @param {*} _value\n */\n static updateDefaultParams(_type, _value) {}\n\n /**\n * Get the default properties to set in the UI for this type of editor.\n * @returns {Array}\n */\n static get defaultPropertiesToUpdate() {\n return [];\n }\n\n /**\n * Check if this kind of editor is able to handle the given mime type for\n * pasting.\n * @param {string} mime\n * @returns {boolean}\n */\n static isHandlingMimeForPasting(mime) {\n return false;\n }\n\n /**\n * Extract the data from the clipboard item and delegate the creation of the\n * editor to the parent.\n * @param {DataTransferItem} item\n * @param {AnnotationEditorLayer} parent\n */\n static paste(item, parent) {\n unreachable(\"Not implemented\");\n }\n\n /**\n * Get the properties to update in the UI for this editor.\n * @returns {Array}\n */\n get propertiesToUpdate() {\n return [];\n }\n\n get _isDraggable() {\n return this.#isDraggable;\n }\n\n set _isDraggable(value) {\n this.#isDraggable = value;\n this.div?.classList.toggle(\"draggable\", value);\n }\n\n /**\n * @returns {boolean} true if the editor handles the Enter key itself.\n */\n get isEnterHandled() {\n return true;\n }\n\n center() {\n const [pageWidth, pageHeight] = this.pageDimensions;\n switch (this.parentRotation) {\n case 90:\n this.x -= (this.height * pageHeight) / (pageWidth * 2);\n this.y += (this.width * pageWidth) / (pageHeight * 2);\n break;\n case 180:\n this.x += this.width / 2;\n this.y += this.height / 2;\n break;\n case 270:\n this.x += (this.height * pageHeight) / (pageWidth * 2);\n this.y -= (this.width * pageWidth) / (pageHeight * 2);\n break;\n default:\n this.x -= this.width / 2;\n this.y -= this.height / 2;\n break;\n }\n this.fixAndSetPosition();\n }\n\n /**\n * Add some commands into the CommandManager (undo/redo stuff).\n * @param {Object} params\n */\n addCommands(params) {\n this._uiManager.addCommands(params);\n }\n\n get currentLayer() {\n return this._uiManager.currentLayer;\n }\n\n /**\n * This editor will be behind the others.\n */\n setInBackground() {\n this.div.style.zIndex = 0;\n }\n\n /**\n * This editor will be in the foreground.\n */\n setInForeground() {\n this.div.style.zIndex = this.#zIndex;\n }\n\n setParent(parent) {\n if (parent !== null) {\n this.pageIndex = parent.pageIndex;\n this.pageDimensions = parent.pageDimensions;\n } else {\n // The editor is being removed from the DOM, so we need to stop resizing.\n this.#stopResizing();\n }\n this.parent = parent;\n }\n\n /**\n * onfocus callback.\n */\n focusin(event) {\n if (!this._focusEventsAllowed) {\n return;\n }\n if (!this.#hasBeenClicked) {\n this.parent.setSelected(this);\n } else {\n this.#hasBeenClicked = false;\n }\n }\n\n /**\n * onblur callback.\n * @param {FocusEvent} event\n */\n focusout(event) {\n if (!this._focusEventsAllowed) {\n return;\n }\n\n if (!this.isAttachedToDOM) {\n return;\n }\n\n // In case of focusout, the relatedTarget is the element which\n // is grabbing the focus.\n // So if the related target is an element under the div for this\n // editor, then the editor isn't unactive.\n const target = event.relatedTarget;\n if (target?.closest(`#${this.id}`)) {\n return;\n }\n\n event.preventDefault();\n\n if (!this.parent?.isMultipleSelection) {\n this.commitOrRemove();\n }\n }\n\n commitOrRemove() {\n if (this.isEmpty()) {\n this.remove();\n } else {\n this.commit();\n }\n }\n\n /**\n * Commit the data contained in this editor.\n */\n commit() {\n this.addToAnnotationStorage();\n }\n\n addToAnnotationStorage() {\n this._uiManager.addToAnnotationStorage(this);\n }\n\n /**\n * Set the editor position within its parent.\n * @param {number} x\n * @param {number} y\n * @param {number} tx - x-translation in screen coordinates.\n * @param {number} ty - y-translation in screen coordinates.\n */\n setAt(x, y, tx, ty) {\n const [width, height] = this.parentDimensions;\n [tx, ty] = this.screenToPageTranslation(tx, ty);\n\n this.x = (x + tx) / width;\n this.y = (y + ty) / height;\n\n this.fixAndSetPosition();\n }\n\n #translate([width, height], x, y) {\n [x, y] = this.screenToPageTranslation(x, y);\n\n this.x += x / width;\n this.y += y / height;\n\n this.fixAndSetPosition();\n }\n\n /**\n * Translate the editor position within its parent.\n * @param {number} x - x-translation in screen coordinates.\n * @param {number} y - y-translation in screen coordinates.\n */\n translate(x, y) {\n // We don't change the initial position because the move here hasn't been\n // done by the user.\n this.#translate(this.parentDimensions, x, y);\n }\n\n /**\n * Translate the editor position within its page and adjust the scroll\n * in order to have the editor in the view.\n * @param {number} x - x-translation in page coordinates.\n * @param {number} y - y-translation in page coordinates.\n */\n translateInPage(x, y) {\n this.#initialPosition ||= [this.x, this.y];\n this.#translate(this.pageDimensions, x, y);\n this.div.scrollIntoView({ block: \"nearest\" });\n }\n\n drag(tx, ty) {\n this.#initialPosition ||= [this.x, this.y];\n const [parentWidth, parentHeight] = this.parentDimensions;\n this.x += tx / parentWidth;\n this.y += ty / parentHeight;\n if (this.parent && (this.x < 0 || this.x > 1 || this.y < 0 || this.y > 1)) {\n // It's possible to not have a parent: for example, when the user is\n // dragging all the selected editors but this one on a page which has been\n // destroyed.\n // It's why we need to check for it. In such a situation, it isn't really\n // a problem to not find a new parent: it's something which is related to\n // what the user is seeing, hence it depends on how pages are layed out.\n\n // The element will be outside of its parent so change the parent.\n const { x, y } = this.div.getBoundingClientRect();\n if (this.parent.findNewParent(this, x, y)) {\n this.x -= Math.floor(this.x);\n this.y -= Math.floor(this.y);\n }\n }\n\n // The editor can be moved wherever the user wants, so we don't need to fix\n // the position: it'll be done when the user will release the mouse button.\n\n let { x, y } = this;\n const [bx, by] = this.getBaseTranslation();\n x += bx;\n y += by;\n\n this.div.style.left = `${(100 * x).toFixed(2)}%`;\n this.div.style.top = `${(100 * y).toFixed(2)}%`;\n this.div.scrollIntoView({ block: \"nearest\" });\n }\n\n get _hasBeenMoved() {\n return (\n !!this.#initialPosition &&\n (this.#initialPosition[0] !== this.x ||\n this.#initialPosition[1] !== this.y)\n );\n }\n\n /**\n * Get the translation to take into account the editor border.\n * The CSS engine positions the element by taking the border into account so\n * we must apply the opposite translation to have the editor in the right\n * position.\n * @returns {Array}\n */\n getBaseTranslation() {\n const [parentWidth, parentHeight] = this.parentDimensions;\n const { _borderLineWidth } = AnnotationEditor;\n const x = _borderLineWidth / parentWidth;\n const y = _borderLineWidth / parentHeight;\n switch (this.rotation) {\n case 90:\n return [-x, y];\n case 180:\n return [x, y];\n case 270:\n return [x, -y];\n default:\n return [-x, -y];\n }\n }\n\n /**\n * @returns {boolean} true if position must be fixed (i.e. make the x and y\n * living in the page).\n */\n get _mustFixPosition() {\n return true;\n }\n\n /**\n * Fix the position of the editor in order to keep it inside its parent page.\n * @param {number} [rotation] - the rotation of the page.\n */\n fixAndSetPosition(rotation = this.rotation) {\n const [pageWidth, pageHeight] = this.pageDimensions;\n let { x, y, width, height } = this;\n width *= pageWidth;\n height *= pageHeight;\n x *= pageWidth;\n y *= pageHeight;\n\n if (this._mustFixPosition) {\n switch (rotation) {\n case 0:\n x = Math.max(0, Math.min(pageWidth - width, x));\n y = Math.max(0, Math.min(pageHeight - height, y));\n break;\n case 90:\n x = Math.max(0, Math.min(pageWidth - height, x));\n y = Math.min(pageHeight, Math.max(width, y));\n break;\n case 180:\n x = Math.min(pageWidth, Math.max(width, x));\n y = Math.min(pageHeight, Math.max(height, y));\n break;\n case 270:\n x = Math.min(pageWidth, Math.max(height, x));\n y = Math.max(0, Math.min(pageHeight - width, y));\n break;\n }\n }\n\n this.x = x /= pageWidth;\n this.y = y /= pageHeight;\n\n const [bx, by] = this.getBaseTranslation();\n x += bx;\n y += by;\n\n const { style } = this.div;\n style.left = `${(100 * x).toFixed(2)}%`;\n style.top = `${(100 * y).toFixed(2)}%`;\n\n this.moveInDOM();\n }\n\n static #rotatePoint(x, y, angle) {\n switch (angle) {\n case 90:\n return [y, -x];\n case 180:\n return [-x, -y];\n case 270:\n return [-y, x];\n default:\n return [x, y];\n }\n }\n\n /**\n * Convert a screen translation into a page one.\n * @param {number} x\n * @param {number} y\n */\n screenToPageTranslation(x, y) {\n return AnnotationEditor.#rotatePoint(x, y, this.parentRotation);\n }\n\n /**\n * Convert a page translation into a screen one.\n * @param {number} x\n * @param {number} y\n */\n pageTranslationToScreen(x, y) {\n return AnnotationEditor.#rotatePoint(x, y, 360 - this.parentRotation);\n }\n\n #getRotationMatrix(rotation) {\n switch (rotation) {\n case 90: {\n const [pageWidth, pageHeight] = this.pageDimensions;\n return [0, -pageWidth / pageHeight, pageHeight / pageWidth, 0];\n }\n case 180:\n return [-1, 0, 0, -1];\n case 270: {\n const [pageWidth, pageHeight] = this.pageDimensions;\n return [0, pageWidth / pageHeight, -pageHeight / pageWidth, 0];\n }\n default:\n return [1, 0, 0, 1];\n }\n }\n\n get parentScale() {\n return this._uiManager.viewParameters.realScale;\n }\n\n get parentRotation() {\n return (this._uiManager.viewParameters.rotation + this.pageRotation) % 360;\n }\n\n get parentDimensions() {\n const {\n parentScale,\n pageDimensions: [pageWidth, pageHeight],\n } = this;\n const scaledWidth = pageWidth * parentScale;\n const scaledHeight = pageHeight * parentScale;\n return FeatureTest.isCSSRoundSupported\n ? [Math.round(scaledWidth), Math.round(scaledHeight)]\n : [scaledWidth, scaledHeight];\n }\n\n /**\n * Set the dimensions of this editor.\n * @param {number} width\n * @param {number} height\n */\n setDims(width, height) {\n const [parentWidth, parentHeight] = this.parentDimensions;\n this.div.style.width = `${((100 * width) / parentWidth).toFixed(2)}%`;\n if (!this.#keepAspectRatio) {\n this.div.style.height = `${((100 * height) / parentHeight).toFixed(2)}%`;\n }\n }\n\n fixDims() {\n const { style } = this.div;\n const { height, width } = style;\n const widthPercent = width.endsWith(\"%\");\n const heightPercent = !this.#keepAspectRatio && height.endsWith(\"%\");\n if (widthPercent && heightPercent) {\n return;\n }\n\n const [parentWidth, parentHeight] = this.parentDimensions;\n if (!widthPercent) {\n style.width = `${((100 * parseFloat(width)) / parentWidth).toFixed(2)}%`;\n }\n if (!this.#keepAspectRatio && !heightPercent) {\n style.height = `${((100 * parseFloat(height)) / parentHeight).toFixed(\n 2\n )}%`;\n }\n }\n\n /**\n * Get the translation used to position this editor when it's created.\n * @returns {Array}\n */\n getInitialTranslation() {\n return [0, 0];\n }\n\n #createResizers() {\n if (this.#resizersDiv) {\n return;\n }\n this.#resizersDiv = document.createElement(\"div\");\n this.#resizersDiv.classList.add(\"resizers\");\n // When the resizers are used with the keyboard, they're focusable, hence\n // we want to have them in this order (top left, top middle, top right, ...)\n // in the DOM to have the focus order correct.\n const classes = this._willKeepAspectRatio\n ? [\"topLeft\", \"topRight\", \"bottomRight\", \"bottomLeft\"]\n : [\n \"topLeft\",\n \"topMiddle\",\n \"topRight\",\n \"middleRight\",\n \"bottomRight\",\n \"bottomMiddle\",\n \"bottomLeft\",\n \"middleLeft\",\n ];\n const signal = this._uiManager._signal;\n for (const name of classes) {\n const div = document.createElement(\"div\");\n this.#resizersDiv.append(div);\n div.classList.add(\"resizer\", name);\n div.setAttribute(\"data-resizer-name\", name);\n div.addEventListener(\n \"pointerdown\",\n this.#resizerPointerdown.bind(this, name),\n { signal }\n );\n div.addEventListener(\"contextmenu\", noContextMenu, { signal });\n div.tabIndex = -1;\n }\n this.div.prepend(this.#resizersDiv);\n }\n\n #resizerPointerdown(name, event) {\n event.preventDefault();\n const { isMac } = FeatureTest.platform;\n if (event.button !== 0 || (event.ctrlKey && isMac)) {\n return;\n }\n\n this.#altText?.toggle(false);\n\n const savedDraggable = this._isDraggable;\n this._isDraggable = false;\n\n const ac = new AbortController();\n const signal = this._uiManager.combinedSignal(ac);\n\n this.parent.togglePointerEvents(false);\n window.addEventListener(\n \"pointermove\",\n this.#resizerPointermove.bind(this, name),\n { passive: true, capture: true, signal }\n );\n window.addEventListener(\"contextmenu\", noContextMenu, { signal });\n const savedX = this.x;\n const savedY = this.y;\n const savedWidth = this.width;\n const savedHeight = this.height;\n const savedParentCursor = this.parent.div.style.cursor;\n const savedCursor = this.div.style.cursor;\n this.div.style.cursor = this.parent.div.style.cursor =\n window.getComputedStyle(event.target).cursor;\n\n const pointerUpCallback = () => {\n ac.abort();\n this.parent.togglePointerEvents(true);\n this.#altText?.toggle(true);\n this._isDraggable = savedDraggable;\n this.parent.div.style.cursor = savedParentCursor;\n this.div.style.cursor = savedCursor;\n\n this.#addResizeToUndoStack(savedX, savedY, savedWidth, savedHeight);\n };\n window.addEventListener(\"pointerup\", pointerUpCallback, { signal });\n // If the user switches to another window (with alt+tab), then we end the\n // resize session.\n window.addEventListener(\"blur\", pointerUpCallback, { signal });\n }\n\n #addResizeToUndoStack(savedX, savedY, savedWidth, savedHeight) {\n const newX = this.x;\n const newY = this.y;\n const newWidth = this.width;\n const newHeight = this.height;\n if (\n newX === savedX &&\n newY === savedY &&\n newWidth === savedWidth &&\n newHeight === savedHeight\n ) {\n return;\n }\n\n this.addCommands({\n cmd: () => {\n this.width = newWidth;\n this.height = newHeight;\n this.x = newX;\n this.y = newY;\n const [parentWidth, parentHeight] = this.parentDimensions;\n this.setDims(parentWidth * newWidth, parentHeight * newHeight);\n this.fixAndSetPosition();\n },\n undo: () => {\n this.width = savedWidth;\n this.height = savedHeight;\n this.x = savedX;\n this.y = savedY;\n const [parentWidth, parentHeight] = this.parentDimensions;\n this.setDims(parentWidth * savedWidth, parentHeight * savedHeight);\n this.fixAndSetPosition();\n },\n mustExec: true,\n });\n }\n\n #resizerPointermove(name, event) {\n const [parentWidth, parentHeight] = this.parentDimensions;\n const savedX = this.x;\n const savedY = this.y;\n const savedWidth = this.width;\n const savedHeight = this.height;\n const minWidth = AnnotationEditor.MIN_SIZE / parentWidth;\n const minHeight = AnnotationEditor.MIN_SIZE / parentHeight;\n\n // 10000 because we multiply by 100 and use toFixed(2) in fixAndSetPosition.\n // Without rounding, the positions of the corners other than the top left\n // one can be slightly wrong.\n const round = x => Math.round(x * 10000) / 10000;\n const rotationMatrix = this.#getRotationMatrix(this.rotation);\n const transf = (x, y) => [\n rotationMatrix[0] * x + rotationMatrix[2] * y,\n rotationMatrix[1] * x + rotationMatrix[3] * y,\n ];\n const invRotationMatrix = this.#getRotationMatrix(360 - this.rotation);\n const invTransf = (x, y) => [\n invRotationMatrix[0] * x + invRotationMatrix[2] * y,\n invRotationMatrix[1] * x + invRotationMatrix[3] * y,\n ];\n let getPoint;\n let getOpposite;\n let isDiagonal = false;\n let isHorizontal = false;\n\n switch (name) {\n case \"topLeft\":\n isDiagonal = true;\n getPoint = (w, h) => [0, 0];\n getOpposite = (w, h) => [w, h];\n break;\n case \"topMiddle\":\n getPoint = (w, h) => [w / 2, 0];\n getOpposite = (w, h) => [w / 2, h];\n break;\n case \"topRight\":\n isDiagonal = true;\n getPoint = (w, h) => [w, 0];\n getOpposite = (w, h) => [0, h];\n break;\n case \"middleRight\":\n isHorizontal = true;\n getPoint = (w, h) => [w, h / 2];\n getOpposite = (w, h) => [0, h / 2];\n break;\n case \"bottomRight\":\n isDiagonal = true;\n getPoint = (w, h) => [w, h];\n getOpposite = (w, h) => [0, 0];\n break;\n case \"bottomMiddle\":\n getPoint = (w, h) => [w / 2, h];\n getOpposite = (w, h) => [w / 2, 0];\n break;\n case \"bottomLeft\":\n isDiagonal = true;\n getPoint = (w, h) => [0, h];\n getOpposite = (w, h) => [w, 0];\n break;\n case \"middleLeft\":\n isHorizontal = true;\n getPoint = (w, h) => [0, h / 2];\n getOpposite = (w, h) => [w, h / 2];\n break;\n }\n\n const point = getPoint(savedWidth, savedHeight);\n const oppositePoint = getOpposite(savedWidth, savedHeight);\n let transfOppositePoint = transf(...oppositePoint);\n const oppositeX = round(savedX + transfOppositePoint[0]);\n const oppositeY = round(savedY + transfOppositePoint[1]);\n let ratioX = 1;\n let ratioY = 1;\n\n let [deltaX, deltaY] = this.screenToPageTranslation(\n event.movementX,\n event.movementY\n );\n [deltaX, deltaY] = invTransf(deltaX / parentWidth, deltaY / parentHeight);\n\n if (isDiagonal) {\n const oldDiag = Math.hypot(savedWidth, savedHeight);\n ratioX = ratioY = Math.max(\n Math.min(\n Math.hypot(\n oppositePoint[0] - point[0] - deltaX,\n oppositePoint[1] - point[1] - deltaY\n ) / oldDiag,\n // Avoid the editor to be larger than the page.\n 1 / savedWidth,\n 1 / savedHeight\n ),\n // Avoid the editor to be smaller than the minimum size.\n minWidth / savedWidth,\n minHeight / savedHeight\n );\n } else if (isHorizontal) {\n ratioX =\n Math.max(\n minWidth,\n Math.min(1, Math.abs(oppositePoint[0] - point[0] - deltaX))\n ) / savedWidth;\n } else {\n ratioY =\n Math.max(\n minHeight,\n Math.min(1, Math.abs(oppositePoint[1] - point[1] - deltaY))\n ) / savedHeight;\n }\n\n const newWidth = round(savedWidth * ratioX);\n const newHeight = round(savedHeight * ratioY);\n transfOppositePoint = transf(...getOpposite(newWidth, newHeight));\n const newX = oppositeX - transfOppositePoint[0];\n const newY = oppositeY - transfOppositePoint[1];\n\n this.width = newWidth;\n this.height = newHeight;\n this.x = newX;\n this.y = newY;\n\n this.setDims(parentWidth * newWidth, parentHeight * newHeight);\n this.fixAndSetPosition();\n }\n\n /**\n * Called when the alt text dialog is closed.\n */\n altTextFinish() {\n this.#altText?.finish();\n }\n\n /**\n * Add a toolbar for this editor.\n * @returns {Promise}\n */\n async addEditToolbar() {\n if (this._editToolbar || this.#isInEditMode) {\n return this._editToolbar;\n }\n this._editToolbar = new EditorToolbar(this);\n this.div.append(this._editToolbar.render());\n if (this.#altText) {\n await this._editToolbar.addAltText(this.#altText);\n }\n\n return this._editToolbar;\n }\n\n removeEditToolbar() {\n if (!this._editToolbar) {\n return;\n }\n this._editToolbar.remove();\n this._editToolbar = null;\n\n // We destroy the alt text but we don't null it because we want to be able\n // to restore it in case the user undoes the deletion.\n this.#altText?.destroy();\n }\n\n getClientDimensions() {\n return this.div.getBoundingClientRect();\n }\n\n async addAltTextButton() {\n if (this.#altText) {\n return;\n }\n AltText.initialize(AnnotationEditor._l10nPromise);\n this.#altText = new AltText(this);\n if (this.#accessibilityData) {\n this.#altText.data = this.#accessibilityData;\n this.#accessibilityData = null;\n }\n await this.addEditToolbar();\n }\n\n get altTextData() {\n return this.#altText?.data;\n }\n\n /**\n * Set the alt text data.\n */\n set altTextData(data) {\n if (!this.#altText) {\n return;\n }\n this.#altText.data = data;\n }\n\n get guessedAltText() {\n return this.#altText?.guessedText;\n }\n\n async setGuessedAltText(text) {\n await this.#altText?.setGuessedText(text);\n }\n\n serializeAltText(isForCopying) {\n return this.#altText?.serialize(isForCopying);\n }\n\n hasAltText() {\n return !!this.#altText && !this.#altText.isEmpty();\n }\n\n hasAltTextData() {\n return this.#altText?.hasData() ?? false;\n }\n\n /**\n * Render this editor in a div.\n * @returns {HTMLDivElement | null}\n */\n render() {\n this.div = document.createElement(\"div\");\n this.div.setAttribute(\"data-editor-rotation\", (360 - this.rotation) % 360);\n this.div.className = this.name;\n this.div.setAttribute(\"id\", this.id);\n this.div.tabIndex = this.#disabled ? -1 : 0;\n if (!this._isVisible) {\n this.div.classList.add(\"hidden\");\n }\n\n this.setInForeground();\n this.#addFocusListeners();\n\n const [parentWidth, parentHeight] = this.parentDimensions;\n if (this.parentRotation % 180 !== 0) {\n this.div.style.maxWidth = `${((100 * parentHeight) / parentWidth).toFixed(\n 2\n )}%`;\n this.div.style.maxHeight = `${(\n (100 * parentWidth) /\n parentHeight\n ).toFixed(2)}%`;\n }\n\n const [tx, ty] = this.getInitialTranslation();\n this.translate(tx, ty);\n\n bindEvents(this, this.div, [\"pointerdown\"]);\n\n return this.div;\n }\n\n /**\n * Onpointerdown callback.\n * @param {PointerEvent} event\n */\n pointerdown(event) {\n const { isMac } = FeatureTest.platform;\n if (event.button !== 0 || (event.ctrlKey && isMac)) {\n // Avoid to focus this editor because of a non-left click.\n event.preventDefault();\n return;\n }\n\n this.#hasBeenClicked = true;\n\n if (this._isDraggable) {\n this.#setUpDragSession(event);\n return;\n }\n\n this.#selectOnPointerEvent(event);\n }\n\n #selectOnPointerEvent(event) {\n const { isMac } = FeatureTest.platform;\n if (\n (event.ctrlKey && !isMac) ||\n event.shiftKey ||\n (event.metaKey && isMac)\n ) {\n this.parent.toggleSelected(this);\n } else {\n this.parent.setSelected(this);\n }\n }\n\n #setUpDragSession(event) {\n const isSelected = this._uiManager.isSelected(this);\n this._uiManager.setUpDragSession();\n\n const ac = new AbortController();\n const signal = this._uiManager.combinedSignal(ac);\n\n if (isSelected) {\n this.div.classList.add(\"moving\");\n this.#prevDragX = event.clientX;\n this.#prevDragY = event.clientY;\n const pointerMoveCallback = e => {\n const { clientX: x, clientY: y } = e;\n const [tx, ty] = this.screenToPageTranslation(\n x - this.#prevDragX,\n y - this.#prevDragY\n );\n this.#prevDragX = x;\n this.#prevDragY = y;\n this._uiManager.dragSelectedEditors(tx, ty);\n };\n window.addEventListener(\"pointermove\", pointerMoveCallback, {\n passive: true,\n capture: true,\n signal,\n });\n }\n\n const pointerUpCallback = () => {\n ac.abort();\n if (isSelected) {\n this.div.classList.remove(\"moving\");\n }\n\n this.#hasBeenClicked = false;\n if (!this._uiManager.endDragSession()) {\n this.#selectOnPointerEvent(event);\n }\n };\n window.addEventListener(\"pointerup\", pointerUpCallback, { signal });\n // If the user is using alt+tab during the dragging session, the pointerup\n // event could be not fired, but a blur event is fired so we can use it in\n // order to interrupt the dragging session.\n window.addEventListener(\"blur\", pointerUpCallback, { signal });\n }\n\n moveInDOM() {\n // Moving the editor in the DOM can be expensive, so we wait a bit before.\n // It's important to not block the UI (for example when changing the font\n // size in a FreeText).\n if (this.#moveInDOMTimeout) {\n clearTimeout(this.#moveInDOMTimeout);\n }\n this.#moveInDOMTimeout = setTimeout(() => {\n this.#moveInDOMTimeout = null;\n this.parent?.moveEditorInDOM(this);\n }, 0);\n }\n\n _setParentAndPosition(parent, x, y) {\n parent.changeParent(this);\n this.x = x;\n this.y = y;\n this.fixAndSetPosition();\n }\n\n /**\n * Convert the current rect into a page one.\n * @param {number} tx - x-translation in screen coordinates.\n * @param {number} ty - y-translation in screen coordinates.\n * @param {number} [rotation] - the rotation of the page.\n */\n getRect(tx, ty, rotation = this.rotation) {\n const scale = this.parentScale;\n const [pageWidth, pageHeight] = this.pageDimensions;\n const [pageX, pageY] = this.pageTranslation;\n const shiftX = tx / scale;\n const shiftY = ty / scale;\n const x = this.x * pageWidth;\n const y = this.y * pageHeight;\n const width = this.width * pageWidth;\n const height = this.height * pageHeight;\n\n switch (rotation) {\n case 0:\n return [\n x + shiftX + pageX,\n pageHeight - y - shiftY - height + pageY,\n x + shiftX + width + pageX,\n pageHeight - y - shiftY + pageY,\n ];\n case 90:\n return [\n x + shiftY + pageX,\n pageHeight - y + shiftX + pageY,\n x + shiftY + height + pageX,\n pageHeight - y + shiftX + width + pageY,\n ];\n case 180:\n return [\n x - shiftX - width + pageX,\n pageHeight - y + shiftY + pageY,\n x - shiftX + pageX,\n pageHeight - y + shiftY + height + pageY,\n ];\n case 270:\n return [\n x - shiftY - height + pageX,\n pageHeight - y - shiftX - width + pageY,\n x - shiftY + pageX,\n pageHeight - y - shiftX + pageY,\n ];\n default:\n throw new Error(\"Invalid rotation\");\n }\n }\n\n getRectInCurrentCoords(rect, pageHeight) {\n const [x1, y1, x2, y2] = rect;\n\n const width = x2 - x1;\n const height = y2 - y1;\n\n switch (this.rotation) {\n case 0:\n return [x1, pageHeight - y2, width, height];\n case 90:\n return [x1, pageHeight - y1, height, width];\n case 180:\n return [x2, pageHeight - y1, width, height];\n case 270:\n return [x2, pageHeight - y2, height, width];\n default:\n throw new Error(\"Invalid rotation\");\n }\n }\n\n /**\n * Executed once this editor has been rendered.\n */\n onceAdded() {}\n\n /**\n * Check if the editor contains something.\n * @returns {boolean}\n */\n isEmpty() {\n return false;\n }\n\n /**\n * Enable edit mode.\n */\n enableEditMode() {\n this.#isInEditMode = true;\n }\n\n /**\n * Disable edit mode.\n */\n disableEditMode() {\n this.#isInEditMode = false;\n }\n\n /**\n * Check if the editor is edited.\n * @returns {boolean}\n */\n isInEditMode() {\n return this.#isInEditMode;\n }\n\n /**\n * If it returns true, then this editor handles the keyboard\n * events itself.\n * @returns {boolean}\n */\n shouldGetKeyboardEvents() {\n return this.#isResizerEnabledForKeyboard;\n }\n\n /**\n * Check if this editor needs to be rebuilt or not.\n * @returns {boolean}\n */\n needsToBeRebuilt() {\n return this.div && !this.isAttachedToDOM;\n }\n\n #addFocusListeners() {\n if (this.#focusAC || !this.div) {\n return;\n }\n this.#focusAC = new AbortController();\n const signal = this._uiManager.combinedSignal(this.#focusAC);\n\n this.div.addEventListener(\"focusin\", this.focusin.bind(this), { signal });\n this.div.addEventListener(\"focusout\", this.focusout.bind(this), { signal });\n }\n\n /**\n * Rebuild the editor in case it has been removed on undo.\n *\n * To implement in subclasses.\n */\n rebuild() {\n this.#addFocusListeners();\n }\n\n /**\n * Rotate the editor.\n * @param {number} angle\n */\n rotate(_angle) {}\n\n /**\n * Serialize the editor.\n * The result of the serialization will be used to construct a\n * new annotation to add to the pdf document.\n *\n * To implement in subclasses.\n * @param {boolean} [isForCopying]\n * @param {Object | null} [context]\n * @returns {Object | null}\n */\n serialize(isForCopying = false, context = null) {\n unreachable(\"An editor must be serializable\");\n }\n\n /**\n * Deserialize the editor.\n * The result of the deserialization is a new editor.\n *\n * @param {Object} data\n * @param {AnnotationEditorLayer} parent\n * @param {AnnotationEditorUIManager} uiManager\n * @returns {AnnotationEditor | null}\n */\n static deserialize(data, parent, uiManager) {\n const editor = new this.prototype.constructor({\n parent,\n id: parent.getNextId(),\n uiManager,\n });\n editor.rotation = data.rotation;\n editor.#accessibilityData = data.accessibilityData;\n\n const [pageWidth, pageHeight] = editor.pageDimensions;\n const [x, y, width, height] = editor.getRectInCurrentCoords(\n data.rect,\n pageHeight\n );\n editor.x = x / pageWidth;\n editor.y = y / pageHeight;\n editor.width = width / pageWidth;\n editor.height = height / pageHeight;\n\n return editor;\n }\n\n /**\n * Check if an existing annotation associated with this editor has been\n * modified.\n * @returns {boolean}\n */\n get hasBeenModified() {\n return (\n !!this.annotationElementId && (this.deleted || this.serialize() !== null)\n );\n }\n\n /**\n * Remove this editor.\n * It's used on ctrl+backspace action.\n */\n remove() {\n this.#focusAC?.abort();\n this.#focusAC = null;\n\n if (!this.isEmpty()) {\n // The editor is removed but it can be back at some point thanks to\n // undo/redo so we must commit it before.\n this.commit();\n }\n if (this.parent) {\n this.parent.remove(this);\n } else {\n this._uiManager.removeEditor(this);\n }\n\n if (this.#moveInDOMTimeout) {\n clearTimeout(this.#moveInDOMTimeout);\n this.#moveInDOMTimeout = null;\n }\n this.#stopResizing();\n this.removeEditToolbar();\n if (this.#telemetryTimeouts) {\n for (const timeout of this.#telemetryTimeouts.values()) {\n clearTimeout(timeout);\n }\n this.#telemetryTimeouts = null;\n }\n this.parent = null;\n }\n\n /**\n * @returns {boolean} true if this editor can be resized.\n */\n get isResizable() {\n return false;\n }\n\n /**\n * Add the resizers to this editor.\n */\n makeResizable() {\n if (this.isResizable) {\n this.#createResizers();\n this.#resizersDiv.classList.remove(\"hidden\");\n bindEvents(this, this.div, [\"keydown\"]);\n }\n }\n\n get toolbarPosition() {\n return null;\n }\n\n /**\n * onkeydown callback.\n * @param {KeyboardEvent} event\n */\n keydown(event) {\n if (\n !this.isResizable ||\n event.target !== this.div ||\n event.key !== \"Enter\"\n ) {\n return;\n }\n this._uiManager.setSelected(this);\n this.#savedDimensions = {\n savedX: this.x,\n savedY: this.y,\n savedWidth: this.width,\n savedHeight: this.height,\n };\n const children = this.#resizersDiv.children;\n if (!this.#allResizerDivs) {\n this.#allResizerDivs = Array.from(children);\n const boundResizerKeydown = this.#resizerKeydown.bind(this);\n const boundResizerBlur = this.#resizerBlur.bind(this);\n const signal = this._uiManager._signal;\n for (const div of this.#allResizerDivs) {\n const name = div.getAttribute(\"data-resizer-name\");\n div.setAttribute(\"role\", \"spinbutton\");\n div.addEventListener(\"keydown\", boundResizerKeydown, { signal });\n div.addEventListener(\"blur\", boundResizerBlur, { signal });\n div.addEventListener(\"focus\", this.#resizerFocus.bind(this, name), {\n signal,\n });\n div.setAttribute(\"data-l10n-id\", AnnotationEditor._l10nResizer[name]);\n }\n }\n\n // We want to have the resizers in the visual order, so we move the first\n // (top-left) to the right place.\n const first = this.#allResizerDivs[0];\n let firstPosition = 0;\n for (const div of children) {\n if (div === first) {\n break;\n }\n firstPosition++;\n }\n const nextFirstPosition =\n (((360 - this.rotation + this.parentRotation) % 360) / 90) *\n (this.#allResizerDivs.length / 4);\n\n if (nextFirstPosition !== firstPosition) {\n // We need to reorder the resizers in the DOM in order to have the focus\n // on the top-left one.\n if (nextFirstPosition < firstPosition) {\n for (let i = 0; i < firstPosition - nextFirstPosition; i++) {\n this.#resizersDiv.append(this.#resizersDiv.firstChild);\n }\n } else if (nextFirstPosition > firstPosition) {\n for (let i = 0; i < nextFirstPosition - firstPosition; i++) {\n this.#resizersDiv.firstChild.before(this.#resizersDiv.lastChild);\n }\n }\n\n let i = 0;\n for (const child of children) {\n const div = this.#allResizerDivs[i++];\n const name = div.getAttribute(\"data-resizer-name\");\n child.setAttribute(\"data-l10n-id\", AnnotationEditor._l10nResizer[name]);\n }\n }\n\n this.#setResizerTabIndex(0);\n this.#isResizerEnabledForKeyboard = true;\n this.#resizersDiv.firstChild.focus({ focusVisible: true });\n event.preventDefault();\n event.stopImmediatePropagation();\n }\n\n #resizerKeydown(event) {\n AnnotationEditor._resizerKeyboardManager.exec(this, event);\n }\n\n #resizerBlur(event) {\n if (\n this.#isResizerEnabledForKeyboard &&\n event.relatedTarget?.parentNode !== this.#resizersDiv\n ) {\n this.#stopResizing();\n }\n }\n\n #resizerFocus(name) {\n this.#focusedResizerName = this.#isResizerEnabledForKeyboard ? name : \"\";\n }\n\n #setResizerTabIndex(value) {\n if (!this.#allResizerDivs) {\n return;\n }\n for (const div of this.#allResizerDivs) {\n div.tabIndex = value;\n }\n }\n\n _resizeWithKeyboard(x, y) {\n if (!this.#isResizerEnabledForKeyboard) {\n return;\n }\n this.#resizerPointermove(this.#focusedResizerName, {\n movementX: x,\n movementY: y,\n });\n }\n\n #stopResizing() {\n this.#isResizerEnabledForKeyboard = false;\n this.#setResizerTabIndex(-1);\n if (this.#savedDimensions) {\n const { savedX, savedY, savedWidth, savedHeight } = this.#savedDimensions;\n this.#addResizeToUndoStack(savedX, savedY, savedWidth, savedHeight);\n this.#savedDimensions = null;\n }\n }\n\n _stopResizingWithKeyboard() {\n this.#stopResizing();\n this.div.focus();\n }\n\n /**\n * Select this editor.\n */\n select() {\n this.makeResizable();\n this.div?.classList.add(\"selectedEditor\");\n if (!this._editToolbar) {\n this.addEditToolbar().then(() => {\n if (this.div?.classList.contains(\"selectedEditor\")) {\n // The editor can have been unselected while we were waiting for the\n // edit toolbar to be created, hence we want to be sure that this\n // editor is still selected.\n this._editToolbar?.show();\n }\n });\n return;\n }\n this._editToolbar?.show();\n this.#altText?.toggleAltTextBadge(false);\n }\n\n /**\n * Unselect this editor.\n */\n unselect() {\n this.#resizersDiv?.classList.add(\"hidden\");\n this.div?.classList.remove(\"selectedEditor\");\n if (this.div?.contains(document.activeElement)) {\n // Don't use this.div.blur() because we don't know where the focus will\n // go.\n this._uiManager.currentLayer.div.focus({\n preventScroll: true,\n });\n }\n this._editToolbar?.hide();\n this.#altText?.toggleAltTextBadge(true);\n }\n\n /**\n * Update some parameters which have been changed through the UI.\n * @param {number} type\n * @param {*} value\n */\n updateParams(type, value) {}\n\n /**\n * When the user disables the editing mode some editors can change some of\n * their properties.\n */\n disableEditing() {}\n\n /**\n * When the user enables the editing mode some editors can change some of\n * their properties.\n */\n enableEditing() {}\n\n /**\n * The editor is about to be edited.\n */\n enterInEditMode() {}\n\n /**\n * @returns {HTMLElement | null} the element requiring an alt text.\n */\n getImageForAltText() {\n return null;\n }\n\n /**\n * Get the div which really contains the displayed content.\n * @returns {HTMLDivElement | undefined}\n */\n get contentDiv() {\n return this.div;\n }\n\n /**\n * If true then the editor is currently edited.\n * @type {boolean}\n */\n get isEditing() {\n return this.#isEditing;\n }\n\n /**\n * When set to true, it means that this editor is currently edited.\n * @param {boolean} value\n */\n set isEditing(value) {\n this.#isEditing = value;\n if (!this.parent) {\n return;\n }\n if (value) {\n this.parent.setSelected(this);\n this.parent.setActiveEditor(this);\n } else {\n this.parent.setActiveEditor(null);\n }\n }\n\n /**\n * Set the aspect ratio to use when resizing.\n * @param {number} width\n * @param {number} height\n */\n setAspectRatio(width, height) {\n this.#keepAspectRatio = true;\n const aspectRatio = width / height;\n const { style } = this.div;\n style.aspectRatio = aspectRatio;\n style.height = \"auto\";\n }\n\n static get MIN_SIZE() {\n return 16;\n }\n\n static canCreateNewEmptyEditor() {\n return true;\n }\n\n /**\n * Get the data to report to the telemetry when the editor is added.\n * @returns {Object}\n */\n get telemetryInitialData() {\n return { action: \"added\" };\n }\n\n /**\n * The telemetry data to use when saving/printing.\n * @returns {Object|null}\n */\n get telemetryFinalData() {\n return null;\n }\n\n _reportTelemetry(data, mustWait = false) {\n if (mustWait) {\n this.#telemetryTimeouts ||= new Map();\n const { action } = data;\n let timeout = this.#telemetryTimeouts.get(action);\n if (timeout) {\n clearTimeout(timeout);\n }\n timeout = setTimeout(() => {\n this._reportTelemetry(data);\n this.#telemetryTimeouts.delete(action);\n if (this.#telemetryTimeouts.size === 0) {\n this.#telemetryTimeouts = null;\n }\n }, AnnotationEditor._telemetryTimeout);\n this.#telemetryTimeouts.set(action, timeout);\n return;\n }\n data.type ||= this.editorType;\n this._uiManager._eventBus.dispatch(\"reporttelemetry\", {\n source: this,\n details: {\n type: \"editing\",\n data,\n },\n });\n }\n\n /**\n * Show or hide this editor.\n * @param {boolean|undefined} visible\n */\n show(visible = this._isVisible) {\n this.div.classList.toggle(\"hidden\", !visible);\n this._isVisible = visible;\n }\n\n enable() {\n if (this.div) {\n this.div.tabIndex = 0;\n }\n this.#disabled = false;\n }\n\n disable() {\n if (this.div) {\n this.div.tabIndex = -1;\n }\n this.#disabled = true;\n }\n\n /**\n * Render an annotation in the annotation layer.\n * @param {Object} annotation\n * @returns {HTMLElement}\n */\n renderAnnotationElement(annotation) {\n let content = annotation.container.querySelector(\".annotationContent\");\n if (!content) {\n content = document.createElement(\"div\");\n content.classList.add(\"annotationContent\", this.editorType);\n annotation.container.prepend(content);\n } else if (content.nodeName === \"CANVAS\") {\n const canvas = content;\n content = document.createElement(\"div\");\n content.classList.add(\"annotationContent\", this.editorType);\n canvas.before(content);\n }\n\n return content;\n }\n\n resetAnnotationElement(annotation) {\n const { firstChild } = annotation.container;\n if (\n firstChild.nodeName === \"DIV\" &&\n firstChild.classList.contains(\"annotationContent\")\n ) {\n firstChild.remove();\n }\n }\n}\n\n// This class is used to fake an editor which has been deleted.\nclass FakeEditor extends AnnotationEditor {\n constructor(params) {\n super(params);\n this.annotationElementId = params.annotationElementId;\n this.deleted = true;\n }\n\n serialize() {\n return {\n id: this.annotationElementId,\n deleted: true,\n pageIndex: this.pageIndex,\n };\n }\n}\n\nexport { AnnotationEditor };\n","/* Copyright 2014 Opera Software ASA\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\n * Based on https://code.google.com/p/smhasher/wiki/MurmurHash3.\n * Hashes roughly 100 KB per millisecond on i7 3.4 GHz.\n */\n\nconst SEED = 0xc3d2e1f0;\n// Workaround for missing math precision in JS.\nconst MASK_HIGH = 0xffff0000;\nconst MASK_LOW = 0xffff;\n\nclass MurmurHash3_64 {\n constructor(seed) {\n this.h1 = seed ? seed & 0xffffffff : SEED;\n this.h2 = seed ? seed & 0xffffffff : SEED;\n }\n\n update(input) {\n let data, length;\n if (typeof input === \"string\") {\n data = new Uint8Array(input.length * 2);\n length = 0;\n for (let i = 0, ii = input.length; i < ii; i++) {\n const code = input.charCodeAt(i);\n if (code <= 0xff) {\n data[length++] = code;\n } else {\n data[length++] = code >>> 8;\n data[length++] = code & 0xff;\n }\n }\n } else if (ArrayBuffer.isView(input)) {\n data = input.slice();\n length = data.byteLength;\n } else {\n throw new Error(\"Invalid data format, must be a string or TypedArray.\");\n }\n\n const blockCounts = length >> 2;\n const tailLength = length - blockCounts * 4;\n // We don't care about endianness here.\n const dataUint32 = new Uint32Array(data.buffer, 0, blockCounts);\n let k1 = 0,\n k2 = 0;\n let h1 = this.h1,\n h2 = this.h2;\n const C1 = 0xcc9e2d51,\n C2 = 0x1b873593;\n const C1_LOW = C1 & MASK_LOW,\n C2_LOW = C2 & MASK_LOW;\n\n for (let i = 0; i < blockCounts; i++) {\n if (i & 1) {\n k1 = dataUint32[i];\n k1 = ((k1 * C1) & MASK_HIGH) | ((k1 * C1_LOW) & MASK_LOW);\n k1 = (k1 << 15) | (k1 >>> 17);\n k1 = ((k1 * C2) & MASK_HIGH) | ((k1 * C2_LOW) & MASK_LOW);\n h1 ^= k1;\n h1 = (h1 << 13) | (h1 >>> 19);\n h1 = h1 * 5 + 0xe6546b64;\n } else {\n k2 = dataUint32[i];\n k2 = ((k2 * C1) & MASK_HIGH) | ((k2 * C1_LOW) & MASK_LOW);\n k2 = (k2 << 15) | (k2 >>> 17);\n k2 = ((k2 * C2) & MASK_HIGH) | ((k2 * C2_LOW) & MASK_LOW);\n h2 ^= k2;\n h2 = (h2 << 13) | (h2 >>> 19);\n h2 = h2 * 5 + 0xe6546b64;\n }\n }\n\n k1 = 0;\n\n switch (tailLength) {\n case 3:\n k1 ^= data[blockCounts * 4 + 2] << 16;\n /* falls through */\n case 2:\n k1 ^= data[blockCounts * 4 + 1] << 8;\n /* falls through */\n case 1:\n k1 ^= data[blockCounts * 4];\n /* falls through */\n\n k1 = ((k1 * C1) & MASK_HIGH) | ((k1 * C1_LOW) & MASK_LOW);\n k1 = (k1 << 15) | (k1 >>> 17);\n k1 = ((k1 * C2) & MASK_HIGH) | ((k1 * C2_LOW) & MASK_LOW);\n if (blockCounts & 1) {\n h1 ^= k1;\n } else {\n h2 ^= k1;\n }\n }\n\n this.h1 = h1;\n this.h2 = h2;\n }\n\n hexdigest() {\n let h1 = this.h1,\n h2 = this.h2;\n\n h1 ^= h2 >>> 1;\n h1 = ((h1 * 0xed558ccd) & MASK_HIGH) | ((h1 * 0x8ccd) & MASK_LOW);\n h2 =\n ((h2 * 0xff51afd7) & MASK_HIGH) |\n (((((h2 << 16) | (h1 >>> 16)) * 0xafd7ed55) & MASK_HIGH) >>> 16);\n h1 ^= h2 >>> 1;\n h1 = ((h1 * 0x1a85ec53) & MASK_HIGH) | ((h1 * 0xec53) & MASK_LOW);\n h2 =\n ((h2 * 0xc4ceb9fe) & MASK_HIGH) |\n (((((h2 << 16) | (h1 >>> 16)) * 0xb9fe1a85) & MASK_HIGH) >>> 16);\n h1 ^= h2 >>> 1;\n\n return (\n (h1 >>> 0).toString(16).padStart(8, \"0\") +\n (h2 >>> 0).toString(16).padStart(8, \"0\")\n );\n }\n}\n\nexport { MurmurHash3_64 };\n","/* Copyright 2020 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { objectFromMap, shadow, unreachable } from \"../shared/util.js\";\nimport { AnnotationEditor } from \"./editor/editor.js\";\nimport { MurmurHash3_64 } from \"../shared/murmurhash3.js\";\n\nconst SerializableEmpty = Object.freeze({\n map: null,\n hash: \"\",\n transfer: undefined,\n});\n\n/**\n * Key/value storage for annotation data in forms.\n */\nclass AnnotationStorage {\n #modified = false;\n\n #modifiedIds = null;\n\n #storage = new Map();\n\n constructor() {\n // Callbacks to signal when the modification state is set or reset.\n // This is used by the viewer to only bind on `beforeunload` if forms\n // are actually edited to prevent doing so unconditionally since that\n // can have undesirable effects.\n this.onSetModified = null;\n this.onResetModified = null;\n this.onAnnotationEditor = null;\n }\n\n /**\n * Get the value for a given key if it exists, or return the default value.\n * @param {string} key\n * @param {Object} defaultValue\n * @returns {Object}\n */\n getValue(key, defaultValue) {\n const value = this.#storage.get(key);\n if (value === undefined) {\n return defaultValue;\n }\n\n return Object.assign(defaultValue, value);\n }\n\n /**\n * Get the value for a given key.\n * @param {string} key\n * @returns {Object}\n */\n getRawValue(key) {\n return this.#storage.get(key);\n }\n\n /**\n * Remove a value from the storage.\n * @param {string} key\n */\n remove(key) {\n this.#storage.delete(key);\n\n if (this.#storage.size === 0) {\n this.resetModified();\n }\n\n if (typeof this.onAnnotationEditor === \"function\") {\n for (const value of this.#storage.values()) {\n if (value instanceof AnnotationEditor) {\n return;\n }\n }\n this.onAnnotationEditor(null);\n }\n }\n\n /**\n * Set the value for a given key\n * @param {string} key\n * @param {Object} value\n */\n setValue(key, value) {\n const obj = this.#storage.get(key);\n let modified = false;\n if (obj !== undefined) {\n for (const [entry, val] of Object.entries(value)) {\n if (obj[entry] !== val) {\n modified = true;\n obj[entry] = val;\n }\n }\n } else {\n modified = true;\n this.#storage.set(key, value);\n }\n if (modified) {\n this.#setModified();\n }\n\n if (\n value instanceof AnnotationEditor &&\n typeof this.onAnnotationEditor === \"function\"\n ) {\n this.onAnnotationEditor(value.constructor._type);\n }\n }\n\n /**\n * Check if the storage contains the given key.\n * @param {string} key\n * @returns {boolean}\n */\n has(key) {\n return this.#storage.has(key);\n }\n\n /**\n * @returns {Object | null}\n */\n getAll() {\n return this.#storage.size > 0 ? objectFromMap(this.#storage) : null;\n }\n\n /**\n * @param {Object} obj\n */\n setAll(obj) {\n for (const [key, val] of Object.entries(obj)) {\n this.setValue(key, val);\n }\n }\n\n get size() {\n return this.#storage.size;\n }\n\n #setModified() {\n if (!this.#modified) {\n this.#modified = true;\n if (typeof this.onSetModified === \"function\") {\n this.onSetModified();\n }\n }\n }\n\n resetModified() {\n if (this.#modified) {\n this.#modified = false;\n if (typeof this.onResetModified === \"function\") {\n this.onResetModified();\n }\n }\n }\n\n /**\n * @returns {PrintAnnotationStorage}\n */\n get print() {\n return new PrintAnnotationStorage(this);\n }\n\n /**\n * PLEASE NOTE: Only intended for usage within the API itself.\n * @ignore\n */\n get serializable() {\n if (this.#storage.size === 0) {\n return SerializableEmpty;\n }\n const map = new Map(),\n hash = new MurmurHash3_64(),\n transfer = [];\n const context = Object.create(null);\n let hasBitmap = false;\n\n for (const [key, val] of this.#storage) {\n const serialized =\n val instanceof AnnotationEditor\n ? val.serialize(/* isForCopying = */ false, context)\n : val;\n if (serialized) {\n map.set(key, serialized);\n\n hash.update(`${key}:${JSON.stringify(serialized)}`);\n hasBitmap ||= !!serialized.bitmap;\n }\n }\n\n if (hasBitmap) {\n // We must transfer the bitmap data separately, since it can be changed\n // during serialization with SVG images.\n for (const value of map.values()) {\n if (value.bitmap) {\n transfer.push(value.bitmap);\n }\n }\n }\n\n return map.size > 0\n ? { map, hash: hash.hexdigest(), transfer }\n : SerializableEmpty;\n }\n\n get editorStats() {\n let stats = null;\n const typeToEditor = new Map();\n for (const value of this.#storage.values()) {\n if (!(value instanceof AnnotationEditor)) {\n continue;\n }\n const editorStats = value.telemetryFinalData;\n if (!editorStats) {\n continue;\n }\n const { type } = editorStats;\n if (!typeToEditor.has(type)) {\n typeToEditor.set(type, Object.getPrototypeOf(value).constructor);\n }\n stats ||= Object.create(null);\n const map = (stats[type] ||= new Map());\n for (const [key, val] of Object.entries(editorStats)) {\n if (key === \"type\") {\n continue;\n }\n let counters = map.get(key);\n if (!counters) {\n counters = new Map();\n map.set(key, counters);\n }\n const count = counters.get(val) ?? 0;\n counters.set(val, count + 1);\n }\n }\n for (const [type, editor] of typeToEditor) {\n stats[type] = editor.computeTelemetryFinalData(stats[type]);\n }\n return stats;\n }\n\n resetModifiedIds() {\n this.#modifiedIds = null;\n }\n\n /**\n * @returns {{ids: Set, hash: string}}\n */\n get modifiedIds() {\n if (this.#modifiedIds) {\n return this.#modifiedIds;\n }\n const ids = [];\n for (const value of this.#storage.values()) {\n if (\n !(value instanceof AnnotationEditor) ||\n !value.annotationElementId ||\n !value.serialize()\n ) {\n continue;\n }\n ids.push(value.annotationElementId);\n }\n return (this.#modifiedIds = {\n ids: new Set(ids),\n hash: ids.join(\",\"),\n });\n }\n}\n\n/**\n * A special `AnnotationStorage` for use during printing, where the serializable\n * data is *frozen* upon initialization, to prevent scripting from modifying its\n * contents. (Necessary since printing is triggered synchronously in browsers.)\n */\nclass PrintAnnotationStorage extends AnnotationStorage {\n #serializable;\n\n constructor(parent) {\n super();\n const { map, hash, transfer } = parent.serializable;\n // Create a *copy* of the data, since Objects are passed by reference in JS.\n const clone = structuredClone(map, transfer ? { transfer } : null);\n\n this.#serializable = { map: clone, hash, transfer };\n }\n\n /**\n * @returns {PrintAnnotationStorage}\n */\n // eslint-disable-next-line getter-return\n get print() {\n unreachable(\"Should not call PrintAnnotationStorage.print\");\n }\n\n /**\n * PLEASE NOTE: Only intended for usage within the API itself.\n * @ignore\n */\n get serializable() {\n return this.#serializable;\n }\n\n get modifiedIds() {\n return shadow(this, \"modifiedIds\", {\n ids: new Set(),\n hash: \"\",\n });\n }\n}\n\nexport { AnnotationStorage, PrintAnnotationStorage, SerializableEmpty };\n","/* Copyright 2012 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n assert,\n bytesToString,\n FontRenderOps,\n isNodeJS,\n shadow,\n string32,\n unreachable,\n warn,\n} from \"../shared/util.js\";\n\nclass FontLoader {\n #systemFonts = new Set();\n\n constructor({\n ownerDocument = globalThis.document,\n styleElement = null, // For testing only.\n }) {\n this._document = ownerDocument;\n\n this.nativeFontFaces = new Set();\n this.styleElement =\n typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")\n ? styleElement\n : null;\n\n if (typeof PDFJSDev === \"undefined\" || !PDFJSDev.test(\"MOZCENTRAL\")) {\n this.loadingRequests = [];\n this.loadTestFontId = 0;\n }\n }\n\n addNativeFontFace(nativeFontFace) {\n this.nativeFontFaces.add(nativeFontFace);\n this._document.fonts.add(nativeFontFace);\n }\n\n removeNativeFontFace(nativeFontFace) {\n this.nativeFontFaces.delete(nativeFontFace);\n this._document.fonts.delete(nativeFontFace);\n }\n\n insertRule(rule) {\n if (!this.styleElement) {\n this.styleElement = this._document.createElement(\"style\");\n this._document.documentElement\n .getElementsByTagName(\"head\")[0]\n .append(this.styleElement);\n }\n const styleSheet = this.styleElement.sheet;\n styleSheet.insertRule(rule, styleSheet.cssRules.length);\n }\n\n clear() {\n for (const nativeFontFace of this.nativeFontFaces) {\n this._document.fonts.delete(nativeFontFace);\n }\n this.nativeFontFaces.clear();\n this.#systemFonts.clear();\n\n if (this.styleElement) {\n // Note: ChildNode.remove doesn't throw if the parentNode is undefined.\n this.styleElement.remove();\n this.styleElement = null;\n }\n }\n\n async loadSystemFont({ systemFontInfo: info, _inspectFont }) {\n if (!info || this.#systemFonts.has(info.loadedName)) {\n return;\n }\n assert(\n !this.disableFontFace,\n \"loadSystemFont shouldn't be called when `disableFontFace` is set.\"\n );\n\n if (this.isFontLoadingAPISupported) {\n const { loadedName, src, style } = info;\n const fontFace = new FontFace(loadedName, src, style);\n this.addNativeFontFace(fontFace);\n try {\n await fontFace.load();\n this.#systemFonts.add(loadedName);\n _inspectFont?.(info);\n } catch {\n warn(\n `Cannot load system font: ${info.baseFontName}, installing it could help to improve PDF rendering.`\n );\n\n this.removeNativeFontFace(fontFace);\n }\n return;\n }\n\n unreachable(\n \"Not implemented: loadSystemFont without the Font Loading API.\"\n );\n }\n\n async bind(font) {\n // Add the font to the DOM only once; skip if the font is already loaded.\n if (font.attached || (font.missingFile && !font.systemFontInfo)) {\n return;\n }\n font.attached = true;\n\n if (font.systemFontInfo) {\n await this.loadSystemFont(font);\n return;\n }\n\n if (this.isFontLoadingAPISupported) {\n const nativeFontFace = font.createNativeFontFace();\n if (nativeFontFace) {\n this.addNativeFontFace(nativeFontFace);\n try {\n await nativeFontFace.loaded;\n } catch (ex) {\n warn(`Failed to load font '${nativeFontFace.family}': '${ex}'.`);\n\n // When font loading failed, fall back to the built-in font renderer.\n font.disableFontFace = true;\n throw ex;\n }\n }\n return; // The font was, asynchronously, loaded.\n }\n\n // !this.isFontLoadingAPISupported\n const rule = font.createFontFaceRule();\n if (rule) {\n this.insertRule(rule);\n\n if (this.isSyncFontLoadingSupported) {\n return; // The font was, synchronously, loaded.\n }\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n throw new Error(\"Not implemented: async font loading\");\n }\n await new Promise(resolve => {\n const request = this._queueLoadingCallback(resolve);\n this._prepareFontLoadEvent(font, request);\n });\n // The font was, asynchronously, loaded.\n }\n }\n\n get isFontLoadingAPISupported() {\n const hasFonts = !!this._document?.fonts;\n if (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) {\n return shadow(\n this,\n \"isFontLoadingAPISupported\",\n hasFonts && !this.styleElement\n );\n }\n return shadow(this, \"isFontLoadingAPISupported\", hasFonts);\n }\n\n get isSyncFontLoadingSupported() {\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n return shadow(this, \"isSyncFontLoadingSupported\", true);\n }\n\n let supported = false;\n if (typeof PDFJSDev === \"undefined\" || !PDFJSDev.test(\"CHROME\")) {\n if (isNodeJS) {\n // Node.js - we can pretend that sync font loading is supported.\n supported = true;\n } else if (\n typeof navigator !== \"undefined\" &&\n typeof navigator?.userAgent === \"string\" &&\n // User agent string sniffing is bad, but there is no reliable way to\n // tell if the font is fully loaded and ready to be used with canvas.\n /Mozilla\\/5.0.*?rv:\\d+.*? Gecko/.test(navigator.userAgent)\n ) {\n // Firefox, from version 14, supports synchronous font loading.\n supported = true;\n }\n }\n return shadow(this, \"isSyncFontLoadingSupported\", supported);\n }\n\n _queueLoadingCallback(callback) {\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n throw new Error(\"Not implemented: _queueLoadingCallback\");\n }\n\n function completeRequest() {\n assert(!request.done, \"completeRequest() cannot be called twice.\");\n request.done = true;\n\n // Sending all completed requests in order of how they were queued.\n while (loadingRequests.length > 0 && loadingRequests[0].done) {\n const otherRequest = loadingRequests.shift();\n setTimeout(otherRequest.callback, 0);\n }\n }\n\n const { loadingRequests } = this;\n const request = {\n done: false,\n complete: completeRequest,\n callback,\n };\n loadingRequests.push(request);\n return request;\n }\n\n get _loadTestFont() {\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n throw new Error(\"Not implemented: _loadTestFont\");\n }\n\n // This is a CFF font with 1 glyph for '.' that fills its entire width\n // and height.\n const testFont = atob(\n \"T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQA\" +\n \"FQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAA\" +\n \"ALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgA\" +\n \"AAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1\" +\n \"AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAA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tQXkD5j3CBLnEQAC\" +\n \"AQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3\" +\n \"Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTj\" +\n \"FQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==\"\n );\n return shadow(this, \"_loadTestFont\", testFont);\n }\n\n _prepareFontLoadEvent(font, request) {\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n throw new Error(\"Not implemented: _prepareFontLoadEvent\");\n }\n\n /** Hack begin */\n // There's currently no event when a font has finished downloading so the\n // following code is a dirty hack to 'guess' when a font is ready.\n // It's assumed fonts are loaded in order, so add a known test font after\n // the desired fonts and then test for the loading of that test font.\n\n function int32(data, offset) {\n return (\n (data.charCodeAt(offset) << 24) |\n (data.charCodeAt(offset + 1) << 16) |\n (data.charCodeAt(offset + 2) << 8) |\n (data.charCodeAt(offset + 3) & 0xff)\n );\n }\n function spliceString(s, offset, remove, insert) {\n const chunk1 = s.substring(0, offset);\n const chunk2 = s.substring(offset + remove);\n return chunk1 + insert + chunk2;\n }\n let i, ii;\n\n // The temporary canvas is used to determine if fonts are loaded.\n const canvas = this._document.createElement(\"canvas\");\n canvas.width = 1;\n canvas.height = 1;\n const ctx = canvas.getContext(\"2d\");\n\n let called = 0;\n function isFontReady(name, callback) {\n // With setTimeout clamping this gives the font ~100ms to load.\n if (++called > 30) {\n warn(\"Load test font never loaded.\");\n callback();\n return;\n }\n ctx.font = \"30px \" + name;\n ctx.fillText(\".\", 0, 20);\n const imageData = ctx.getImageData(0, 0, 1, 1);\n if (imageData.data[3] > 0) {\n callback();\n return;\n }\n setTimeout(isFontReady.bind(null, name, callback));\n }\n\n const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`;\n // Chromium seems to cache fonts based on a hash of the actual font data,\n // so the font must be modified for each load test else it will appear to\n // be loaded already.\n // TODO: This could maybe be made faster by avoiding the btoa of the full\n // font by splitting it in chunks before hand and padding the font id.\n let data = this._loadTestFont;\n const COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum)\n data = spliceString(\n data,\n COMMENT_OFFSET,\n loadTestFontId.length,\n loadTestFontId\n );\n // CFF checksum is important for IE, adjusting it\n const CFF_CHECKSUM_OFFSET = 16;\n const XXXX_VALUE = 0x58585858; // the \"comment\" filled with 'X'\n let checksum = int32(data, CFF_CHECKSUM_OFFSET);\n for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {\n checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0;\n }\n if (i < loadTestFontId.length) {\n // align to 4 bytes boundary\n checksum = (checksum - XXXX_VALUE + int32(loadTestFontId + \"XXX\", i)) | 0;\n }\n data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));\n\n const url = `url(data:font/opentype;base64,${btoa(data)});`;\n const rule = `@font-face {font-family:\"${loadTestFontId}\";src:${url}}`;\n this.insertRule(rule);\n\n const div = this._document.createElement(\"div\");\n div.style.visibility = \"hidden\";\n div.style.width = div.style.height = \"10px\";\n div.style.position = \"absolute\";\n div.style.top = div.style.left = \"0px\";\n\n for (const name of [font.loadedName, loadTestFontId]) {\n const span = this._document.createElement(\"span\");\n span.textContent = \"Hi\";\n span.style.fontFamily = name;\n div.append(span);\n }\n this._document.body.append(div);\n\n isFontReady(loadTestFontId, () => {\n div.remove();\n request.complete();\n });\n /** Hack end */\n }\n}\n\nclass FontFaceObject {\n constructor(translatedData, { disableFontFace = false, inspectFont = null }) {\n this.compiledGlyphs = Object.create(null);\n // importing translated data\n for (const i in translatedData) {\n this[i] = translatedData[i];\n }\n this.disableFontFace = disableFontFace === true;\n this._inspectFont = inspectFont;\n }\n\n createNativeFontFace() {\n if (!this.data || this.disableFontFace) {\n return null;\n }\n let nativeFontFace;\n if (!this.cssFontInfo) {\n nativeFontFace = new FontFace(this.loadedName, this.data, {});\n } else {\n const css = {\n weight: this.cssFontInfo.fontWeight,\n };\n if (this.cssFontInfo.italicAngle) {\n css.style = `oblique ${this.cssFontInfo.italicAngle}deg`;\n }\n nativeFontFace = new FontFace(\n this.cssFontInfo.fontFamily,\n this.data,\n css\n );\n }\n\n this._inspectFont?.(this);\n return nativeFontFace;\n }\n\n createFontFaceRule() {\n if (!this.data || this.disableFontFace) {\n return null;\n }\n const data = bytesToString(this.data);\n // Add the @font-face rule to the document.\n const url = `url(data:${this.mimetype};base64,${btoa(data)});`;\n let rule;\n if (!this.cssFontInfo) {\n rule = `@font-face {font-family:\"${this.loadedName}\";src:${url}}`;\n } else {\n let css = `font-weight: ${this.cssFontInfo.fontWeight};`;\n if (this.cssFontInfo.italicAngle) {\n css += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`;\n }\n rule = `@font-face {font-family:\"${this.cssFontInfo.fontFamily}\";${css}src:${url}}`;\n }\n\n this._inspectFont?.(this, url);\n return rule;\n }\n\n getPathGenerator(objs, character) {\n if (this.compiledGlyphs[character] !== undefined) {\n return this.compiledGlyphs[character];\n }\n\n let cmds;\n try {\n cmds = objs.get(this.loadedName + \"_path_\" + character);\n } catch (ex) {\n warn(`getPathGenerator - ignoring character: \"${ex}\".`);\n }\n\n if (!Array.isArray(cmds) || cmds.length === 0) {\n return (this.compiledGlyphs[character] = function (c, size) {\n // No-op function, to allow rendering to continue.\n });\n }\n\n const commands = [];\n for (let i = 0, ii = cmds.length; i < ii; ) {\n switch (cmds[i++]) {\n case FontRenderOps.BEZIER_CURVE_TO:\n {\n const [a, b, c, d, e, f] = cmds.slice(i, i + 6);\n commands.push(ctx => ctx.bezierCurveTo(a, b, c, d, e, f));\n i += 6;\n }\n break;\n case FontRenderOps.MOVE_TO:\n {\n const [a, b] = cmds.slice(i, i + 2);\n commands.push(ctx => ctx.moveTo(a, b));\n i += 2;\n }\n break;\n case FontRenderOps.LINE_TO:\n {\n const [a, b] = cmds.slice(i, i + 2);\n commands.push(ctx => ctx.lineTo(a, b));\n i += 2;\n }\n break;\n case FontRenderOps.QUADRATIC_CURVE_TO:\n {\n const [a, b, c, d] = cmds.slice(i, i + 4);\n commands.push(ctx => ctx.quadraticCurveTo(a, b, c, d));\n i += 4;\n }\n break;\n case FontRenderOps.RESTORE:\n commands.push(ctx => ctx.restore());\n break;\n case FontRenderOps.SAVE:\n commands.push(ctx => ctx.save());\n break;\n case FontRenderOps.SCALE:\n // The scale command must be at the third position, after save and\n // transform (for the font matrix) commands (see also\n // font_renderer.js).\n // The goal is to just scale the canvas and then run the commands loop\n // without the need to pass the size parameter to each command.\n assert(\n commands.length === 2,\n \"Scale command is only valid at the third position.\"\n );\n break;\n case FontRenderOps.TRANSFORM:\n {\n const [a, b, c, d, e, f] = cmds.slice(i, i + 6);\n commands.push(ctx => ctx.transform(a, b, c, d, e, f));\n i += 6;\n }\n break;\n case FontRenderOps.TRANSLATE:\n {\n const [a, b] = cmds.slice(i, i + 2);\n commands.push(ctx => ctx.translate(a, b));\n i += 2;\n }\n break;\n }\n }\n\n return (this.compiledGlyphs[character] = function glyphDrawer(ctx, size) {\n commands[0](ctx);\n commands[1](ctx);\n ctx.scale(size, -size);\n for (let i = 2, ii = commands.length; i < ii; i++) {\n commands[i](ctx);\n }\n });\n }\n}\n\nexport { FontFaceObject, FontLoader };\n","/* Copyright 2020 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n BaseCanvasFactory,\n BaseCMapReaderFactory,\n BaseFilterFactory,\n BaseStandardFontDataFactory,\n} from \"./base_factory.js\";\nimport { isNodeJS, warn } from \"../shared/util.js\";\n\nif (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n throw new Error(\n 'Module \"./node_utils.js\" shall not be used with MOZCENTRAL builds.'\n );\n}\n\nif (isNodeJS) {\n // eslint-disable-next-line no-var\n var packageCapability = Promise.withResolvers();\n // eslint-disable-next-line no-var\n var packageMap = null;\n\n const loadPackages = async () => {\n // Native packages.\n const fs = await __non_webpack_import__(\"fs\"),\n http = await __non_webpack_import__(\"http\"),\n https = await __non_webpack_import__(\"https\"),\n url = await __non_webpack_import__(\"url\");\n\n // Optional, third-party, packages.\n let canvas, path2d;\n if (typeof PDFJSDev !== \"undefined\" && !PDFJSDev.test(\"SKIP_BABEL\")) {\n try {\n canvas = await __non_webpack_import__(\"canvas\");\n } catch {}\n try {\n path2d = await __non_webpack_import__(\"path2d\");\n } catch {}\n }\n\n return new Map(Object.entries({ fs, http, https, url, canvas, path2d }));\n };\n\n loadPackages().then(\n map => {\n packageMap = map;\n packageCapability.resolve();\n\n if (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"SKIP_BABEL\")) {\n return;\n }\n if (!globalThis.DOMMatrix) {\n const DOMMatrix = map.get(\"canvas\")?.DOMMatrix;\n\n if (DOMMatrix) {\n globalThis.DOMMatrix = DOMMatrix;\n } else {\n warn(\"Cannot polyfill `DOMMatrix`, rendering may be broken.\");\n }\n }\n if (!globalThis.Path2D) {\n const CanvasRenderingContext2D =\n map.get(\"canvas\")?.CanvasRenderingContext2D;\n const applyPath2DToCanvasRenderingContext =\n map.get(\"path2d\")?.applyPath2DToCanvasRenderingContext;\n const Path2D = map.get(\"path2d\")?.Path2D;\n\n if (\n CanvasRenderingContext2D &&\n applyPath2DToCanvasRenderingContext &&\n Path2D\n ) {\n applyPath2DToCanvasRenderingContext(CanvasRenderingContext2D);\n globalThis.Path2D = Path2D;\n } else {\n warn(\"Cannot polyfill `Path2D`, rendering may be broken.\");\n }\n }\n },\n reason => {\n warn(`loadPackages: ${reason}`);\n\n packageMap = new Map();\n packageCapability.resolve();\n }\n );\n}\n\nclass NodePackages {\n static get promise() {\n return packageCapability.promise;\n }\n\n static get(name) {\n return packageMap?.get(name);\n }\n}\n\nconst fetchData = function (url) {\n const fs = NodePackages.get(\"fs\");\n return fs.promises.readFile(url).then(data => new Uint8Array(data));\n};\n\nclass NodeFilterFactory extends BaseFilterFactory {}\n\nclass NodeCanvasFactory extends BaseCanvasFactory {\n /**\n * @ignore\n */\n _createCanvas(width, height) {\n const canvas = NodePackages.get(\"canvas\");\n return canvas.createCanvas(width, height);\n }\n}\n\nclass NodeCMapReaderFactory extends BaseCMapReaderFactory {\n /**\n * @ignore\n */\n _fetchData(url, compressionType) {\n return fetchData(url).then(data => ({ cMapData: data, compressionType }));\n }\n}\n\nclass NodeStandardFontDataFactory extends BaseStandardFontDataFactory {\n /**\n * @ignore\n */\n _fetchData(url) {\n return fetchData(url);\n }\n}\n\nexport {\n NodeCanvasFactory,\n NodeCMapReaderFactory,\n NodeFilterFactory,\n NodePackages,\n NodeStandardFontDataFactory,\n};\n","/* Copyright 2014 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FormatError, info, unreachable, Util } from \"../shared/util.js\";\nimport { getCurrentTransform } from \"./display_utils.js\";\n\nconst PathType = {\n FILL: \"Fill\",\n STROKE: \"Stroke\",\n SHADING: \"Shading\",\n};\n\nfunction applyBoundingBox(ctx, bbox) {\n if (!bbox) {\n return;\n }\n const width = bbox[2] - bbox[0];\n const height = bbox[3] - bbox[1];\n const region = new Path2D();\n region.rect(bbox[0], bbox[1], width, height);\n ctx.clip(region);\n}\n\nclass BaseShadingPattern {\n constructor() {\n if (\n (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) &&\n this.constructor === BaseShadingPattern\n ) {\n unreachable(\"Cannot initialize BaseShadingPattern.\");\n }\n }\n\n getPattern() {\n unreachable(\"Abstract method `getPattern` called.\");\n }\n}\n\nclass RadialAxialShadingPattern extends BaseShadingPattern {\n constructor(IR) {\n super();\n this._type = IR[1];\n this._bbox = IR[2];\n this._colorStops = IR[3];\n this._p0 = IR[4];\n this._p1 = IR[5];\n this._r0 = IR[6];\n this._r1 = IR[7];\n this.matrix = null;\n }\n\n _createGradient(ctx) {\n let grad;\n if (this._type === \"axial\") {\n grad = ctx.createLinearGradient(\n this._p0[0],\n this._p0[1],\n this._p1[0],\n this._p1[1]\n );\n } else if (this._type === \"radial\") {\n grad = ctx.createRadialGradient(\n this._p0[0],\n this._p0[1],\n this._r0,\n this._p1[0],\n this._p1[1],\n this._r1\n );\n }\n\n for (const colorStop of this._colorStops) {\n grad.addColorStop(colorStop[0], colorStop[1]);\n }\n return grad;\n }\n\n getPattern(ctx, owner, inverse, pathType) {\n let pattern;\n if (pathType === PathType.STROKE || pathType === PathType.FILL) {\n const ownerBBox = owner.current.getClippedPathBoundingBox(\n pathType,\n getCurrentTransform(ctx)\n ) || [0, 0, 0, 0];\n // Create a canvas that is only as big as the current path. This doesn't\n // allow us to cache the pattern, but it generally creates much smaller\n // canvases and saves memory use. See bug 1722807 for an example.\n const width = Math.ceil(ownerBBox[2] - ownerBBox[0]) || 1;\n const height = Math.ceil(ownerBBox[3] - ownerBBox[1]) || 1;\n\n const tmpCanvas = owner.cachedCanvases.getCanvas(\n \"pattern\",\n width,\n height,\n true\n );\n\n const tmpCtx = tmpCanvas.context;\n tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);\n tmpCtx.beginPath();\n tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);\n // Non shading fill patterns are positioned relative to the base transform\n // (usually the page's initial transform), but we may have created a\n // smaller canvas based on the path, so we must account for the shift.\n tmpCtx.translate(-ownerBBox[0], -ownerBBox[1]);\n inverse = Util.transform(inverse, [\n 1,\n 0,\n 0,\n 1,\n ownerBBox[0],\n ownerBBox[1],\n ]);\n\n tmpCtx.transform(...owner.baseTransform);\n if (this.matrix) {\n tmpCtx.transform(...this.matrix);\n }\n applyBoundingBox(tmpCtx, this._bbox);\n\n tmpCtx.fillStyle = this._createGradient(tmpCtx);\n tmpCtx.fill();\n\n pattern = ctx.createPattern(tmpCanvas.canvas, \"no-repeat\");\n const domMatrix = new DOMMatrix(inverse);\n pattern.setTransform(domMatrix);\n } else {\n // Shading fills are applied relative to the current matrix which is also\n // how canvas gradients work, so there's no need to do anything special\n // here.\n applyBoundingBox(ctx, this._bbox);\n pattern = this._createGradient(ctx);\n }\n return pattern;\n }\n}\n\nfunction drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {\n // Very basic Gouraud-shaded triangle rasterization algorithm.\n const coords = context.coords,\n colors = context.colors;\n const bytes = data.data,\n rowSize = data.width * 4;\n let tmp;\n if (coords[p1 + 1] > coords[p2 + 1]) {\n tmp = p1;\n p1 = p2;\n p2 = tmp;\n tmp = c1;\n c1 = c2;\n c2 = tmp;\n }\n if (coords[p2 + 1] > coords[p3 + 1]) {\n tmp = p2;\n p2 = p3;\n p3 = tmp;\n tmp = c2;\n c2 = c3;\n c3 = tmp;\n }\n if (coords[p1 + 1] > coords[p2 + 1]) {\n tmp = p1;\n p1 = p2;\n p2 = tmp;\n tmp = c1;\n c1 = c2;\n c2 = tmp;\n }\n const x1 = (coords[p1] + context.offsetX) * context.scaleX;\n const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;\n const x2 = (coords[p2] + context.offsetX) * context.scaleX;\n const y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;\n const x3 = (coords[p3] + context.offsetX) * context.scaleX;\n const y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;\n if (y1 >= y3) {\n return;\n }\n const c1r = colors[c1],\n c1g = colors[c1 + 1],\n c1b = colors[c1 + 2];\n const c2r = colors[c2],\n c2g = colors[c2 + 1],\n c2b = colors[c2 + 2];\n const c3r = colors[c3],\n c3g = colors[c3 + 1],\n c3b = colors[c3 + 2];\n\n const minY = Math.round(y1),\n maxY = Math.round(y3);\n let xa, car, cag, cab;\n let xb, cbr, cbg, cbb;\n for (let y = minY; y <= maxY; y++) {\n if (y < y2) {\n const k = y < y1 ? 0 : (y1 - y) / (y1 - y2);\n xa = x1 - (x1 - x2) * k;\n car = c1r - (c1r - c2r) * k;\n cag = c1g - (c1g - c2g) * k;\n cab = c1b - (c1b - c2b) * k;\n } else {\n let k;\n if (y > y3) {\n k = 1;\n } else if (y2 === y3) {\n k = 0;\n } else {\n k = (y2 - y) / (y2 - y3);\n }\n xa = x2 - (x2 - x3) * k;\n car = c2r - (c2r - c3r) * k;\n cag = c2g - (c2g - c3g) * k;\n cab = c2b - (c2b - c3b) * k;\n }\n\n let k;\n if (y < y1) {\n k = 0;\n } else if (y > y3) {\n k = 1;\n } else {\n k = (y1 - y) / (y1 - y3);\n }\n xb = x1 - (x1 - x3) * k;\n cbr = c1r - (c1r - c3r) * k;\n cbg = c1g - (c1g - c3g) * k;\n cbb = c1b - (c1b - c3b) * k;\n const x1_ = Math.round(Math.min(xa, xb));\n const x2_ = Math.round(Math.max(xa, xb));\n let j = rowSize * y + x1_ * 4;\n for (let x = x1_; x <= x2_; x++) {\n k = (xa - x) / (xa - xb);\n if (k < 0) {\n k = 0;\n } else if (k > 1) {\n k = 1;\n }\n bytes[j++] = (car - (car - cbr) * k) | 0;\n bytes[j++] = (cag - (cag - cbg) * k) | 0;\n bytes[j++] = (cab - (cab - cbb) * k) | 0;\n bytes[j++] = 255;\n }\n }\n}\n\nfunction drawFigure(data, figure, context) {\n const ps = figure.coords;\n const cs = figure.colors;\n let i, ii;\n switch (figure.type) {\n case \"lattice\":\n const verticesPerRow = figure.verticesPerRow;\n const rows = Math.floor(ps.length / verticesPerRow) - 1;\n const cols = verticesPerRow - 1;\n for (i = 0; i < rows; i++) {\n let q = i * verticesPerRow;\n for (let j = 0; j < cols; j++, q++) {\n drawTriangle(\n data,\n context,\n ps[q],\n ps[q + 1],\n ps[q + verticesPerRow],\n cs[q],\n cs[q + 1],\n cs[q + verticesPerRow]\n );\n drawTriangle(\n data,\n context,\n ps[q + verticesPerRow + 1],\n ps[q + 1],\n ps[q + verticesPerRow],\n cs[q + verticesPerRow + 1],\n cs[q + 1],\n cs[q + verticesPerRow]\n );\n }\n }\n break;\n case \"triangles\":\n for (i = 0, ii = ps.length; i < ii; i += 3) {\n drawTriangle(\n data,\n context,\n ps[i],\n ps[i + 1],\n ps[i + 2],\n cs[i],\n cs[i + 1],\n cs[i + 2]\n );\n }\n break;\n default:\n throw new Error(\"illegal figure\");\n }\n}\n\nclass MeshShadingPattern extends BaseShadingPattern {\n constructor(IR) {\n super();\n this._coords = IR[2];\n this._colors = IR[3];\n this._figures = IR[4];\n this._bounds = IR[5];\n this._bbox = IR[7];\n this._background = IR[8];\n this.matrix = null;\n }\n\n _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) {\n // we will increase scale on some weird factor to let antialiasing take\n // care of \"rough\" edges\n const EXPECTED_SCALE = 1.1;\n // MAX_PATTERN_SIZE is used to avoid OOM situation.\n const MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough\n // We need to keep transparent border around our pattern for fill():\n // createPattern with 'no-repeat' will bleed edges across entire area.\n const BORDER_SIZE = 2;\n\n const offsetX = Math.floor(this._bounds[0]);\n const offsetY = Math.floor(this._bounds[1]);\n const boundsWidth = Math.ceil(this._bounds[2]) - offsetX;\n const boundsHeight = Math.ceil(this._bounds[3]) - offsetY;\n\n const width = Math.min(\n Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)),\n MAX_PATTERN_SIZE\n );\n const height = Math.min(\n Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)),\n MAX_PATTERN_SIZE\n );\n const scaleX = boundsWidth / width;\n const scaleY = boundsHeight / height;\n\n const context = {\n coords: this._coords,\n colors: this._colors,\n offsetX: -offsetX,\n offsetY: -offsetY,\n scaleX: 1 / scaleX,\n scaleY: 1 / scaleY,\n };\n\n const paddedWidth = width + BORDER_SIZE * 2;\n const paddedHeight = height + BORDER_SIZE * 2;\n\n const tmpCanvas = cachedCanvases.getCanvas(\n \"mesh\",\n paddedWidth,\n paddedHeight,\n false\n );\n const tmpCtx = tmpCanvas.context;\n\n const data = tmpCtx.createImageData(width, height);\n if (backgroundColor) {\n const bytes = data.data;\n for (let i = 0, ii = bytes.length; i < ii; i += 4) {\n bytes[i] = backgroundColor[0];\n bytes[i + 1] = backgroundColor[1];\n bytes[i + 2] = backgroundColor[2];\n bytes[i + 3] = 255;\n }\n }\n for (const figure of this._figures) {\n drawFigure(data, figure, context);\n }\n tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);\n const canvas = tmpCanvas.canvas;\n\n return {\n canvas,\n offsetX: offsetX - BORDER_SIZE * scaleX,\n offsetY: offsetY - BORDER_SIZE * scaleY,\n scaleX,\n scaleY,\n };\n }\n\n getPattern(ctx, owner, inverse, pathType) {\n applyBoundingBox(ctx, this._bbox);\n let scale;\n if (pathType === PathType.SHADING) {\n scale = Util.singularValueDecompose2dScale(getCurrentTransform(ctx));\n } else {\n // Obtain scale from matrix and current transformation matrix.\n scale = Util.singularValueDecompose2dScale(owner.baseTransform);\n if (this.matrix) {\n const matrixScale = Util.singularValueDecompose2dScale(this.matrix);\n scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]];\n }\n }\n\n // Rasterizing on the main thread since sending/queue large canvases\n // might cause OOM.\n const temporaryPatternCanvas = this._createMeshCanvas(\n scale,\n pathType === PathType.SHADING ? null : this._background,\n owner.cachedCanvases\n );\n\n if (pathType !== PathType.SHADING) {\n ctx.setTransform(...owner.baseTransform);\n if (this.matrix) {\n ctx.transform(...this.matrix);\n }\n }\n\n ctx.translate(\n temporaryPatternCanvas.offsetX,\n temporaryPatternCanvas.offsetY\n );\n ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);\n\n return ctx.createPattern(temporaryPatternCanvas.canvas, \"no-repeat\");\n }\n}\n\nclass DummyShadingPattern extends BaseShadingPattern {\n getPattern() {\n return \"hotpink\";\n }\n}\n\nfunction getShadingPattern(IR) {\n switch (IR[0]) {\n case \"RadialAxial\":\n return new RadialAxialShadingPattern(IR);\n case \"Mesh\":\n return new MeshShadingPattern(IR);\n case \"Dummy\":\n return new DummyShadingPattern();\n }\n throw new Error(`Unknown IR type: ${IR[0]}`);\n}\n\nconst PaintType = {\n COLORED: 1,\n UNCOLORED: 2,\n};\n\nclass TilingPattern {\n // 10in @ 300dpi shall be enough.\n static MAX_PATTERN_SIZE = 3000;\n\n constructor(IR, color, ctx, canvasGraphicsFactory, baseTransform) {\n this.operatorList = IR[2];\n this.matrix = IR[3];\n this.bbox = IR[4];\n this.xstep = IR[5];\n this.ystep = IR[6];\n this.paintType = IR[7];\n this.tilingType = IR[8];\n this.color = color;\n this.ctx = ctx;\n this.canvasGraphicsFactory = canvasGraphicsFactory;\n this.baseTransform = baseTransform;\n }\n\n createPatternCanvas(owner) {\n const operatorList = this.operatorList;\n const bbox = this.bbox;\n const xstep = this.xstep;\n const ystep = this.ystep;\n const paintType = this.paintType;\n const tilingType = this.tilingType;\n const color = this.color;\n const canvasGraphicsFactory = this.canvasGraphicsFactory;\n\n info(\"TilingType: \" + tilingType);\n\n // A tiling pattern as defined by PDF spec 8.7.2 is a cell whose size is\n // described by bbox, and may repeat regularly by shifting the cell by\n // xstep and ystep.\n // Because the HTML5 canvas API does not support pattern repetition with\n // gaps in between, we use the xstep/ystep instead of the bbox's size.\n //\n // This has the following consequences (similarly for ystep):\n //\n // - If xstep is the same as bbox, then there is no observable difference.\n //\n // - If xstep is larger than bbox, then the pattern canvas is partially\n // empty: the area bounded by bbox is painted, the outside area is void.\n //\n // - If xstep is smaller than bbox, then the pixels between xstep and the\n // bbox boundary will be missing. This is INCORRECT behavior.\n // \"Figures on adjacent tiles should not overlap\" (PDF spec 8.7.3.1),\n // but overlapping cells without common pixels are still valid.\n // TODO: Fix the implementation, to allow this scenario to be painted\n // correctly.\n\n const x0 = bbox[0],\n y0 = bbox[1],\n x1 = bbox[2],\n y1 = bbox[3];\n\n // Obtain scale from matrix and current transformation matrix.\n const matrixScale = Util.singularValueDecompose2dScale(this.matrix);\n const curMatrixScale = Util.singularValueDecompose2dScale(\n this.baseTransform\n );\n const combinedScale = [\n matrixScale[0] * curMatrixScale[0],\n matrixScale[1] * curMatrixScale[1],\n ];\n\n // Use width and height values that are as close as possible to the end\n // result when the pattern is used. Too low value makes the pattern look\n // blurry. Too large value makes it look too crispy.\n const dimx = this.getSizeAndScale(\n xstep,\n this.ctx.canvas.width,\n combinedScale[0]\n );\n const dimy = this.getSizeAndScale(\n ystep,\n this.ctx.canvas.height,\n combinedScale[1]\n );\n\n const tmpCanvas = owner.cachedCanvases.getCanvas(\n \"pattern\",\n dimx.size,\n dimy.size,\n true\n );\n const tmpCtx = tmpCanvas.context;\n const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);\n graphics.groupLevel = owner.groupLevel;\n\n this.setFillAndStrokeStyleToContext(graphics, paintType, color);\n\n let adjustedX0 = x0;\n let adjustedY0 = y0;\n let adjustedX1 = x1;\n let adjustedY1 = y1;\n // Some bounding boxes have negative x0/y0 coordinates which will cause the\n // some of the drawing to be off of the canvas. To avoid this shift the\n // bounding box over.\n if (x0 < 0) {\n adjustedX0 = 0;\n adjustedX1 += Math.abs(x0);\n }\n if (y0 < 0) {\n adjustedY0 = 0;\n adjustedY1 += Math.abs(y0);\n }\n tmpCtx.translate(-(dimx.scale * adjustedX0), -(dimy.scale * adjustedY0));\n graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0);\n\n // To match CanvasGraphics beginDrawing we must save the context here or\n // else we end up with unbalanced save/restores.\n tmpCtx.save();\n\n this.clipBbox(graphics, adjustedX0, adjustedY0, adjustedX1, adjustedY1);\n\n graphics.baseTransform = getCurrentTransform(graphics.ctx);\n\n graphics.executeOperatorList(operatorList);\n\n graphics.endDrawing();\n\n return {\n canvas: tmpCanvas.canvas,\n scaleX: dimx.scale,\n scaleY: dimy.scale,\n offsetX: adjustedX0,\n offsetY: adjustedY0,\n };\n }\n\n getSizeAndScale(step, realOutputSize, scale) {\n // xstep / ystep may be negative -- normalize.\n step = Math.abs(step);\n // MAX_PATTERN_SIZE is used to avoid OOM situation.\n // Use the destination canvas's size if it is bigger than the hard-coded\n // limit of MAX_PATTERN_SIZE to avoid clipping patterns that cover the\n // whole canvas.\n const maxSize = Math.max(TilingPattern.MAX_PATTERN_SIZE, realOutputSize);\n let size = Math.ceil(step * scale);\n if (size >= maxSize) {\n size = maxSize;\n } else {\n scale = size / step;\n }\n return { scale, size };\n }\n\n clipBbox(graphics, x0, y0, x1, y1) {\n const bboxWidth = x1 - x0;\n const bboxHeight = y1 - y0;\n graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);\n graphics.current.updateRectMinMax(getCurrentTransform(graphics.ctx), [\n x0,\n y0,\n x1,\n y1,\n ]);\n graphics.clip();\n graphics.endPath();\n }\n\n setFillAndStrokeStyleToContext(graphics, paintType, color) {\n const context = graphics.ctx,\n current = graphics.current;\n switch (paintType) {\n case PaintType.COLORED:\n const ctx = this.ctx;\n context.fillStyle = ctx.fillStyle;\n context.strokeStyle = ctx.strokeStyle;\n current.fillColor = ctx.fillStyle;\n current.strokeColor = ctx.strokeStyle;\n break;\n case PaintType.UNCOLORED:\n const cssColor = Util.makeHexColor(color[0], color[1], color[2]);\n context.fillStyle = cssColor;\n context.strokeStyle = cssColor;\n // Set color needed by image masks (fixes issues 3226 and 8741).\n current.fillColor = cssColor;\n current.strokeColor = cssColor;\n break;\n default:\n throw new FormatError(`Unsupported paint type: ${paintType}`);\n }\n }\n\n getPattern(ctx, owner, inverse, pathType) {\n // PDF spec 8.7.2 NOTE 1: pattern's matrix is relative to initial matrix.\n let matrix = inverse;\n if (pathType !== PathType.SHADING) {\n matrix = Util.transform(matrix, owner.baseTransform);\n if (this.matrix) {\n matrix = Util.transform(matrix, this.matrix);\n }\n }\n\n const temporaryPatternCanvas = this.createPatternCanvas(owner);\n\n let domMatrix = new DOMMatrix(matrix);\n // Rescale and so that the ctx.createPattern call generates a pattern with\n // the desired size.\n domMatrix = domMatrix.translate(\n temporaryPatternCanvas.offsetX,\n temporaryPatternCanvas.offsetY\n );\n domMatrix = domMatrix.scale(\n 1 / temporaryPatternCanvas.scaleX,\n 1 / temporaryPatternCanvas.scaleY\n );\n\n const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, \"repeat\");\n pattern.setTransform(domMatrix);\n\n return pattern;\n }\n}\n\nexport { getShadingPattern, PathType, TilingPattern };\n","/* Copyright 2022 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FeatureTest, ImageKind } from \"./util.js\";\n\nfunction convertToRGBA(params) {\n switch (params.kind) {\n case ImageKind.GRAYSCALE_1BPP:\n return convertBlackAndWhiteToRGBA(params);\n case ImageKind.RGB_24BPP:\n return convertRGBToRGBA(params);\n }\n\n return null;\n}\n\nfunction convertBlackAndWhiteToRGBA({\n src,\n srcPos = 0,\n dest,\n width,\n height,\n nonBlackColor = 0xffffffff,\n inverseDecode = false,\n}) {\n const black = FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;\n const [zeroMapping, oneMapping] = inverseDecode\n ? [nonBlackColor, black]\n : [black, nonBlackColor];\n const widthInSource = width >> 3;\n const widthRemainder = width & 7;\n const srcLength = src.length;\n dest = new Uint32Array(dest.buffer);\n let destPos = 0;\n\n for (let i = 0; i < height; i++) {\n for (const max = srcPos + widthInSource; srcPos < max; srcPos++) {\n const elem = srcPos < srcLength ? src[srcPos] : 255;\n dest[destPos++] = elem & 0b10000000 ? oneMapping : zeroMapping;\n dest[destPos++] = elem & 0b1000000 ? oneMapping : zeroMapping;\n dest[destPos++] = elem & 0b100000 ? oneMapping : zeroMapping;\n dest[destPos++] = elem & 0b10000 ? oneMapping : zeroMapping;\n dest[destPos++] = elem & 0b1000 ? oneMapping : zeroMapping;\n dest[destPos++] = elem & 0b100 ? oneMapping : zeroMapping;\n dest[destPos++] = elem & 0b10 ? oneMapping : zeroMapping;\n dest[destPos++] = elem & 0b1 ? oneMapping : zeroMapping;\n }\n if (widthRemainder === 0) {\n continue;\n }\n const elem = srcPos < srcLength ? src[srcPos++] : 255;\n for (let j = 0; j < widthRemainder; j++) {\n dest[destPos++] = elem & (1 << (7 - j)) ? oneMapping : zeroMapping;\n }\n }\n return { srcPos, destPos };\n}\n\nfunction convertRGBToRGBA({\n src,\n srcPos = 0,\n dest,\n destPos = 0,\n width,\n height,\n}) {\n let i = 0;\n const len32 = src.length >> 2;\n const src32 = new Uint32Array(src.buffer, srcPos, len32);\n\n if (FeatureTest.isLittleEndian) {\n // It's a way faster to do the shuffle manually instead of working\n // component by component with some Uint8 arrays.\n for (; i < len32 - 2; i += 3, destPos += 4) {\n const s1 = src32[i]; // R2B1G1R1\n const s2 = src32[i + 1]; // G3R3B2G2\n const s3 = src32[i + 2]; // B4G4R4B3\n\n dest[destPos] = s1 | 0xff000000;\n dest[destPos + 1] = (s1 >>> 24) | (s2 << 8) | 0xff000000;\n dest[destPos + 2] = (s2 >>> 16) | (s3 << 16) | 0xff000000;\n dest[destPos + 3] = (s3 >>> 8) | 0xff000000;\n }\n\n for (let j = i * 4, jj = src.length; j < jj; j += 3) {\n dest[destPos++] =\n src[j] | (src[j + 1] << 8) | (src[j + 2] << 16) | 0xff000000;\n }\n } else {\n for (; i < len32 - 2; i += 3, destPos += 4) {\n const s1 = src32[i]; // R1G1B1R2\n const s2 = src32[i + 1]; // G2B2R3G3\n const s3 = src32[i + 2]; // B3R4G4B4\n\n dest[destPos] = s1 | 0xff;\n dest[destPos + 1] = (s1 << 24) | (s2 >>> 8) | 0xff;\n dest[destPos + 2] = (s2 << 16) | (s3 >>> 16) | 0xff;\n dest[destPos + 3] = (s3 << 8) | 0xff;\n }\n\n for (let j = i * 4, jj = src.length; j < jj; j += 3) {\n dest[destPos++] =\n (src[j] << 24) | (src[j + 1] << 16) | (src[j + 2] << 8) | 0xff;\n }\n }\n\n return { srcPos, destPos };\n}\n\nfunction grayToRGBA(src, dest) {\n if (FeatureTest.isLittleEndian) {\n for (let i = 0, ii = src.length; i < ii; i++) {\n dest[i] = (src[i] * 0x10101) | 0xff000000;\n }\n } else {\n for (let i = 0, ii = src.length; i < ii; i++) {\n dest[i] = (src[i] * 0x1010100) | 0x000000ff;\n }\n }\n}\n\nexport { convertBlackAndWhiteToRGBA, convertToRGBA, grayToRGBA };\n","/* Copyright 2012 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FeatureTest,\n FONT_IDENTITY_MATRIX,\n IDENTITY_MATRIX,\n ImageKind,\n info,\n isNodeJS,\n OPS,\n shadow,\n TextRenderingMode,\n unreachable,\n Util,\n warn,\n} from \"../shared/util.js\";\nimport {\n getCurrentTransform,\n getCurrentTransformInverse,\n PixelsPerInch,\n} from \"./display_utils.js\";\nimport {\n getShadingPattern,\n PathType,\n TilingPattern,\n} from \"./pattern_helper.js\";\nimport { convertBlackAndWhiteToRGBA } from \"../shared/image_utils.js\";\n\n// contexts store most of the state we need natively.\n// However, PDF needs a bit more state, which we store here.\n// Minimal font size that would be used during canvas fillText operations.\nconst MIN_FONT_SIZE = 16;\n// Maximum font size that would be used during canvas fillText operations.\nconst MAX_FONT_SIZE = 100;\n\n// Defines the time the `executeOperatorList`-method is going to be executing\n// before it stops and schedules a continue of execution.\nconst EXECUTION_TIME = 15; // ms\n// Defines the number of steps before checking the execution time.\nconst EXECUTION_STEPS = 10;\n\n// To disable Type3 compilation, set the value to `-1`.\nconst MAX_SIZE_TO_COMPILE = 1000;\n\nconst FULL_CHUNK_HEIGHT = 16;\n\n/**\n * Overrides certain methods on a 2d ctx so that when they are called they\n * will also call the same method on the destCtx. The methods that are\n * overridden are all the transformation state modifiers, path creation, and\n * save/restore. We only forward these specific methods because they are the\n * only state modifiers that we cannot copy over when we switch contexts.\n *\n * To remove mirroring call `ctx._removeMirroring()`.\n *\n * @param {Object} ctx - The 2d canvas context that will duplicate its calls on\n * the destCtx.\n * @param {Object} destCtx - The 2d canvas context that will receive the\n * forwarded calls.\n */\nfunction mirrorContextOperations(ctx, destCtx) {\n if (ctx._removeMirroring) {\n throw new Error(\"Context is already forwarding operations.\");\n }\n ctx.__originalSave = ctx.save;\n ctx.__originalRestore = ctx.restore;\n ctx.__originalRotate = ctx.rotate;\n ctx.__originalScale = ctx.scale;\n ctx.__originalTranslate = ctx.translate;\n ctx.__originalTransform = ctx.transform;\n ctx.__originalSetTransform = ctx.setTransform;\n ctx.__originalResetTransform = ctx.resetTransform;\n ctx.__originalClip = ctx.clip;\n ctx.__originalMoveTo = ctx.moveTo;\n ctx.__originalLineTo = ctx.lineTo;\n ctx.__originalBezierCurveTo = ctx.bezierCurveTo;\n ctx.__originalRect = ctx.rect;\n ctx.__originalClosePath = ctx.closePath;\n ctx.__originalBeginPath = ctx.beginPath;\n\n ctx._removeMirroring = () => {\n ctx.save = ctx.__originalSave;\n ctx.restore = ctx.__originalRestore;\n ctx.rotate = ctx.__originalRotate;\n ctx.scale = ctx.__originalScale;\n ctx.translate = ctx.__originalTranslate;\n ctx.transform = ctx.__originalTransform;\n ctx.setTransform = ctx.__originalSetTransform;\n ctx.resetTransform = ctx.__originalResetTransform;\n\n ctx.clip = ctx.__originalClip;\n ctx.moveTo = ctx.__originalMoveTo;\n ctx.lineTo = ctx.__originalLineTo;\n ctx.bezierCurveTo = ctx.__originalBezierCurveTo;\n ctx.rect = ctx.__originalRect;\n ctx.closePath = ctx.__originalClosePath;\n ctx.beginPath = ctx.__originalBeginPath;\n delete ctx._removeMirroring;\n };\n\n ctx.save = function ctxSave() {\n destCtx.save();\n this.__originalSave();\n };\n\n ctx.restore = function ctxRestore() {\n destCtx.restore();\n this.__originalRestore();\n };\n\n ctx.translate = function ctxTranslate(x, y) {\n destCtx.translate(x, y);\n this.__originalTranslate(x, y);\n };\n\n ctx.scale = function ctxScale(x, y) {\n destCtx.scale(x, y);\n this.__originalScale(x, y);\n };\n\n ctx.transform = function ctxTransform(a, b, c, d, e, f) {\n destCtx.transform(a, b, c, d, e, f);\n this.__originalTransform(a, b, c, d, e, f);\n };\n\n ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {\n destCtx.setTransform(a, b, c, d, e, f);\n this.__originalSetTransform(a, b, c, d, e, f);\n };\n\n ctx.resetTransform = function ctxResetTransform() {\n destCtx.resetTransform();\n this.__originalResetTransform();\n };\n\n ctx.rotate = function ctxRotate(angle) {\n destCtx.rotate(angle);\n this.__originalRotate(angle);\n };\n\n ctx.clip = function ctxRotate(rule) {\n destCtx.clip(rule);\n this.__originalClip(rule);\n };\n\n ctx.moveTo = function (x, y) {\n destCtx.moveTo(x, y);\n this.__originalMoveTo(x, y);\n };\n\n ctx.lineTo = function (x, y) {\n destCtx.lineTo(x, y);\n this.__originalLineTo(x, y);\n };\n\n ctx.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) {\n destCtx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);\n this.__originalBezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);\n };\n\n ctx.rect = function (x, y, width, height) {\n destCtx.rect(x, y, width, height);\n this.__originalRect(x, y, width, height);\n };\n\n ctx.closePath = function () {\n destCtx.closePath();\n this.__originalClosePath();\n };\n\n ctx.beginPath = function () {\n destCtx.beginPath();\n this.__originalBeginPath();\n };\n}\n\nclass CachedCanvases {\n constructor(canvasFactory) {\n this.canvasFactory = canvasFactory;\n this.cache = Object.create(null);\n }\n\n getCanvas(id, width, height) {\n let canvasEntry;\n if (this.cache[id] !== undefined) {\n canvasEntry = this.cache[id];\n this.canvasFactory.reset(canvasEntry, width, height);\n } else {\n canvasEntry = this.canvasFactory.create(width, height);\n this.cache[id] = canvasEntry;\n }\n return canvasEntry;\n }\n\n delete(id) {\n delete this.cache[id];\n }\n\n clear() {\n for (const id in this.cache) {\n const canvasEntry = this.cache[id];\n this.canvasFactory.destroy(canvasEntry);\n delete this.cache[id];\n }\n }\n}\n\nfunction drawImageAtIntegerCoords(\n ctx,\n srcImg,\n srcX,\n srcY,\n srcW,\n srcH,\n destX,\n destY,\n destW,\n destH\n) {\n const [a, b, c, d, tx, ty] = getCurrentTransform(ctx);\n if (b === 0 && c === 0) {\n // top-left corner is at (X, Y) and\n // bottom-right one is at (X + width, Y + height).\n\n // If leftX is 4.321 then it's rounded to 4.\n // If width is 10.432 then it's rounded to 11 because\n // rightX = leftX + width = 14.753 which is rounded to 15\n // so after rounding the total width is 11 (15 - 4).\n // It's why we can't just floor/ceil uniformly, it just depends\n // on the values we've.\n\n const tlX = destX * a + tx;\n const rTlX = Math.round(tlX);\n const tlY = destY * d + ty;\n const rTlY = Math.round(tlY);\n const brX = (destX + destW) * a + tx;\n\n // Some pdf contains images with 1x1 images so in case of 0-width after\n // scaling we must fallback on 1 to be sure there is something.\n const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;\n const brY = (destY + destH) * d + ty;\n const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;\n\n // We must apply a transformation in order to apply it on the image itself.\n // For example if a == 1 && d == -1, it means that the image itself is\n // mirrored w.r.t. the x-axis.\n ctx.setTransform(Math.sign(a), 0, 0, Math.sign(d), rTlX, rTlY);\n ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rWidth, rHeight);\n ctx.setTransform(a, b, c, d, tx, ty);\n\n return [rWidth, rHeight];\n }\n\n if (a === 0 && d === 0) {\n // This path is taken in issue9462.pdf (page 3).\n const tlX = destY * c + tx;\n const rTlX = Math.round(tlX);\n const tlY = destX * b + ty;\n const rTlY = Math.round(tlY);\n const brX = (destY + destH) * c + tx;\n const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;\n const brY = (destX + destW) * b + ty;\n const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;\n\n ctx.setTransform(0, Math.sign(b), Math.sign(c), 0, rTlX, rTlY);\n ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rHeight, rWidth);\n ctx.setTransform(a, b, c, d, tx, ty);\n\n return [rHeight, rWidth];\n }\n\n // Not a scale matrix so let the render handle the case without rounding.\n ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH);\n\n const scaleX = Math.hypot(a, b);\n const scaleY = Math.hypot(c, d);\n return [scaleX * destW, scaleY * destH];\n}\n\nfunction compileType3Glyph(imgData) {\n const { width, height } = imgData;\n if (width > MAX_SIZE_TO_COMPILE || height > MAX_SIZE_TO_COMPILE) {\n return null;\n }\n\n const POINT_TO_PROCESS_LIMIT = 1000;\n const POINT_TYPES = new Uint8Array([\n 0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0,\n ]);\n\n const width1 = width + 1;\n let points = new Uint8Array(width1 * (height + 1));\n let i, j, j0;\n\n // decodes bit-packed mask data\n const lineSize = (width + 7) & ~7;\n let data = new Uint8Array(lineSize * height),\n pos = 0;\n for (const elem of imgData.data) {\n let mask = 128;\n while (mask > 0) {\n data[pos++] = elem & mask ? 0 : 255;\n mask >>= 1;\n }\n }\n\n // finding interesting points: every point is located between mask pixels,\n // so there will be points of the (width + 1)x(height + 1) grid. Every point\n // will have flags assigned based on neighboring mask pixels:\n // 4 | 8\n // --P--\n // 2 | 1\n // We are interested only in points with the flags:\n // - outside corners: 1, 2, 4, 8;\n // - inside corners: 7, 11, 13, 14;\n // - and, intersections: 5, 10.\n let count = 0;\n pos = 0;\n if (data[pos] !== 0) {\n points[0] = 1;\n ++count;\n }\n for (j = 1; j < width; j++) {\n if (data[pos] !== data[pos + 1]) {\n points[j] = data[pos] ? 2 : 1;\n ++count;\n }\n pos++;\n }\n if (data[pos] !== 0) {\n points[j] = 2;\n ++count;\n }\n for (i = 1; i < height; i++) {\n pos = i * lineSize;\n j0 = i * width1;\n if (data[pos - lineSize] !== data[pos]) {\n points[j0] = data[pos] ? 1 : 8;\n ++count;\n }\n // 'sum' is the position of the current pixel configuration in the 'TYPES'\n // array (in order 8-1-2-4, so we can use '>>2' to shift the column).\n let sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);\n for (j = 1; j < width; j++) {\n sum =\n (sum >> 2) +\n (data[pos + 1] ? 4 : 0) +\n (data[pos - lineSize + 1] ? 8 : 0);\n if (POINT_TYPES[sum]) {\n points[j0 + j] = POINT_TYPES[sum];\n ++count;\n }\n pos++;\n }\n if (data[pos - lineSize] !== data[pos]) {\n points[j0 + j] = data[pos] ? 2 : 4;\n ++count;\n }\n\n if (count > POINT_TO_PROCESS_LIMIT) {\n return null;\n }\n }\n\n pos = lineSize * (height - 1);\n j0 = i * width1;\n if (data[pos] !== 0) {\n points[j0] = 8;\n ++count;\n }\n for (j = 1; j < width; j++) {\n if (data[pos] !== data[pos + 1]) {\n points[j0 + j] = data[pos] ? 4 : 8;\n ++count;\n }\n pos++;\n }\n if (data[pos] !== 0) {\n points[j0 + j] = 4;\n ++count;\n }\n if (count > POINT_TO_PROCESS_LIMIT) {\n return null;\n }\n\n // building outlines\n const steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);\n const path = new Path2D();\n\n for (i = 0; count && i <= height; i++) {\n let p = i * width1;\n const end = p + width;\n while (p < end && !points[p]) {\n p++;\n }\n if (p === end) {\n continue;\n }\n path.moveTo(p % width1, i);\n\n const p0 = p;\n let type = points[p];\n do {\n const step = steps[type];\n do {\n p += step;\n } while (!points[p]);\n\n const pp = points[p];\n if (pp !== 5 && pp !== 10) {\n // set new direction\n type = pp;\n // delete mark\n points[p] = 0;\n } else {\n // type is 5 or 10, ie, a crossing\n // set new direction\n type = pp & ((0x33 * type) >> 4);\n // set new type for \"future hit\"\n points[p] &= (type >> 2) | (type << 2);\n }\n path.lineTo(p % width1, (p / width1) | 0);\n\n if (!points[p]) {\n --count;\n }\n } while (p0 !== p);\n --i;\n }\n\n // Immediately release the, potentially large, `Uint8Array`s after parsing.\n data = null;\n points = null;\n\n const drawOutline = function (c) {\n c.save();\n // the path shall be painted in [0..1]x[0..1] space\n c.scale(1 / width, -1 / height);\n c.translate(0, -height);\n c.fill(path);\n c.beginPath();\n c.restore();\n };\n\n return drawOutline;\n}\n\nclass CanvasExtraState {\n constructor(width, height) {\n // Are soft masks and alpha values shapes or opacities?\n this.alphaIsShape = false;\n this.fontSize = 0;\n this.fontSizeScale = 1;\n this.textMatrix = IDENTITY_MATRIX;\n this.textMatrixScale = 1;\n this.fontMatrix = FONT_IDENTITY_MATRIX;\n this.leading = 0;\n // Current point (in user coordinates)\n this.x = 0;\n this.y = 0;\n // Start of text line (in text coordinates)\n this.lineX = 0;\n this.lineY = 0;\n // Character and word spacing\n this.charSpacing = 0;\n this.wordSpacing = 0;\n this.textHScale = 1;\n this.textRenderingMode = TextRenderingMode.FILL;\n this.textRise = 0;\n // Default fore and background colors\n this.fillColor = \"#000000\";\n this.strokeColor = \"#000000\";\n this.patternFill = false;\n // Note: fill alpha applies to all non-stroking operations\n this.fillAlpha = 1;\n this.strokeAlpha = 1;\n this.lineWidth = 1;\n this.activeSMask = null;\n this.transferMaps = \"none\";\n\n this.startNewPathAndClipBox([0, 0, width, height]);\n }\n\n clone() {\n const clone = Object.create(this);\n clone.clipBox = this.clipBox.slice();\n return clone;\n }\n\n setCurrentPoint(x, y) {\n this.x = x;\n this.y = y;\n }\n\n updatePathMinMax(transform, x, y) {\n [x, y] = Util.applyTransform([x, y], transform);\n this.minX = Math.min(this.minX, x);\n this.minY = Math.min(this.minY, y);\n this.maxX = Math.max(this.maxX, x);\n this.maxY = Math.max(this.maxY, y);\n }\n\n updateRectMinMax(transform, rect) {\n const p1 = Util.applyTransform(rect, transform);\n const p2 = Util.applyTransform(rect.slice(2), transform);\n const p3 = Util.applyTransform([rect[0], rect[3]], transform);\n const p4 = Util.applyTransform([rect[2], rect[1]], transform);\n\n this.minX = Math.min(this.minX, p1[0], p2[0], p3[0], p4[0]);\n this.minY = Math.min(this.minY, p1[1], p2[1], p3[1], p4[1]);\n this.maxX = Math.max(this.maxX, p1[0], p2[0], p3[0], p4[0]);\n this.maxY = Math.max(this.maxY, p1[1], p2[1], p3[1], p4[1]);\n }\n\n updateScalingPathMinMax(transform, minMax) {\n Util.scaleMinMax(transform, minMax);\n this.minX = Math.min(this.minX, minMax[0]);\n this.minY = Math.min(this.minY, minMax[1]);\n this.maxX = Math.max(this.maxX, minMax[2]);\n this.maxY = Math.max(this.maxY, minMax[3]);\n }\n\n updateCurvePathMinMax(transform, x0, y0, x1, y1, x2, y2, x3, y3, minMax) {\n const box = Util.bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3, minMax);\n if (minMax) {\n return;\n }\n this.updateRectMinMax(transform, box);\n }\n\n getPathBoundingBox(pathType = PathType.FILL, transform = null) {\n const box = [this.minX, this.minY, this.maxX, this.maxY];\n if (pathType === PathType.STROKE) {\n if (!transform) {\n unreachable(\"Stroke bounding box must include transform.\");\n }\n // Stroked paths can be outside of the path bounding box by 1/2 the line\n // width.\n const scale = Util.singularValueDecompose2dScale(transform);\n const xStrokePad = (scale[0] * this.lineWidth) / 2;\n const yStrokePad = (scale[1] * this.lineWidth) / 2;\n box[0] -= xStrokePad;\n box[1] -= yStrokePad;\n box[2] += xStrokePad;\n box[3] += yStrokePad;\n }\n return box;\n }\n\n updateClipFromPath() {\n const intersect = Util.intersect(this.clipBox, this.getPathBoundingBox());\n this.startNewPathAndClipBox(intersect || [0, 0, 0, 0]);\n }\n\n isEmptyClip() {\n return this.minX === Infinity;\n }\n\n startNewPathAndClipBox(box) {\n this.clipBox = box;\n this.minX = Infinity;\n this.minY = Infinity;\n this.maxX = 0;\n this.maxY = 0;\n }\n\n getClippedPathBoundingBox(pathType = PathType.FILL, transform = null) {\n return Util.intersect(\n this.clipBox,\n this.getPathBoundingBox(pathType, transform)\n );\n }\n}\n\nfunction putBinaryImageData(ctx, imgData) {\n if (typeof ImageData !== \"undefined\" && imgData instanceof ImageData) {\n ctx.putImageData(imgData, 0, 0);\n return;\n }\n\n // Put the image data to the canvas in chunks, rather than putting the\n // whole image at once. This saves JS memory, because the ImageData object\n // is smaller. It also possibly saves C++ memory within the implementation\n // of putImageData(). (E.g. in Firefox we make two short-lived copies of\n // the data passed to putImageData()). |n| shouldn't be too small, however,\n // because too many putImageData() calls will slow things down.\n //\n // Note: as written, if the last chunk is partial, the putImageData() call\n // will (conceptually) put pixels past the bounds of the canvas. But\n // that's ok; any such pixels are ignored.\n\n const height = imgData.height,\n width = imgData.width;\n const partialChunkHeight = height % FULL_CHUNK_HEIGHT;\n const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;\n const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;\n\n const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);\n let srcPos = 0,\n destPos;\n const src = imgData.data;\n const dest = chunkImgData.data;\n let i, j, thisChunkHeight, elemsInThisChunk;\n\n // There are multiple forms in which the pixel data can be passed, and\n // imgData.kind tells us which one this is.\n if (imgData.kind === ImageKind.GRAYSCALE_1BPP) {\n // Grayscale, 1 bit per pixel (i.e. black-and-white).\n const srcLength = src.byteLength;\n const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2);\n const dest32DataLength = dest32.length;\n const fullSrcDiff = (width + 7) >> 3;\n const white = 0xffffffff;\n const black = FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;\n\n for (i = 0; i < totalChunks; i++) {\n thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;\n destPos = 0;\n for (j = 0; j < thisChunkHeight; j++) {\n const srcDiff = srcLength - srcPos;\n let k = 0;\n const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;\n const kEndUnrolled = kEnd & ~7;\n let mask = 0;\n let srcByte = 0;\n for (; k < kEndUnrolled; k += 8) {\n srcByte = src[srcPos++];\n dest32[destPos++] = srcByte & 128 ? white : black;\n dest32[destPos++] = srcByte & 64 ? white : black;\n dest32[destPos++] = srcByte & 32 ? white : black;\n dest32[destPos++] = srcByte & 16 ? white : black;\n dest32[destPos++] = srcByte & 8 ? white : black;\n dest32[destPos++] = srcByte & 4 ? white : black;\n dest32[destPos++] = srcByte & 2 ? white : black;\n dest32[destPos++] = srcByte & 1 ? white : black;\n }\n for (; k < kEnd; k++) {\n if (mask === 0) {\n srcByte = src[srcPos++];\n mask = 128;\n }\n\n dest32[destPos++] = srcByte & mask ? white : black;\n mask >>= 1;\n }\n }\n // We ran out of input. Make all remaining pixels transparent.\n while (destPos < dest32DataLength) {\n dest32[destPos++] = 0;\n }\n\n ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);\n }\n } else if (imgData.kind === ImageKind.RGBA_32BPP) {\n // RGBA, 32-bits per pixel.\n j = 0;\n elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;\n for (i = 0; i < fullChunks; i++) {\n dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));\n srcPos += elemsInThisChunk;\n\n ctx.putImageData(chunkImgData, 0, j);\n j += FULL_CHUNK_HEIGHT;\n }\n if (i < totalChunks) {\n elemsInThisChunk = width * partialChunkHeight * 4;\n dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));\n\n ctx.putImageData(chunkImgData, 0, j);\n }\n } else if (imgData.kind === ImageKind.RGB_24BPP) {\n // RGB, 24-bits per pixel.\n thisChunkHeight = FULL_CHUNK_HEIGHT;\n elemsInThisChunk = width * thisChunkHeight;\n for (i = 0; i < totalChunks; i++) {\n if (i >= fullChunks) {\n thisChunkHeight = partialChunkHeight;\n elemsInThisChunk = width * thisChunkHeight;\n }\n\n destPos = 0;\n for (j = elemsInThisChunk; j--; ) {\n dest[destPos++] = src[srcPos++];\n dest[destPos++] = src[srcPos++];\n dest[destPos++] = src[srcPos++];\n dest[destPos++] = 255;\n }\n\n ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);\n }\n } else {\n throw new Error(`bad image kind: ${imgData.kind}`);\n }\n}\n\nfunction putBinaryImageMask(ctx, imgData) {\n if (imgData.bitmap) {\n // The bitmap has been created in the worker.\n ctx.drawImage(imgData.bitmap, 0, 0);\n return;\n }\n\n // Slow path: OffscreenCanvas isn't available in the worker.\n const height = imgData.height,\n width = imgData.width;\n const partialChunkHeight = height % FULL_CHUNK_HEIGHT;\n const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;\n const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;\n\n const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);\n let srcPos = 0;\n const src = imgData.data;\n const dest = chunkImgData.data;\n\n for (let i = 0; i < totalChunks; i++) {\n const thisChunkHeight =\n i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;\n\n // Expand the mask so it can be used by the canvas. Any required\n // inversion has already been handled.\n\n ({ srcPos } = convertBlackAndWhiteToRGBA({\n src,\n srcPos,\n dest,\n width,\n height: thisChunkHeight,\n nonBlackColor: 0,\n }));\n\n ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);\n }\n}\n\nfunction copyCtxState(sourceCtx, destCtx) {\n const properties = [\n \"strokeStyle\",\n \"fillStyle\",\n \"fillRule\",\n \"globalAlpha\",\n \"lineWidth\",\n \"lineCap\",\n \"lineJoin\",\n \"miterLimit\",\n \"globalCompositeOperation\",\n \"font\",\n \"filter\",\n ];\n for (const property of properties) {\n if (sourceCtx[property] !== undefined) {\n destCtx[property] = sourceCtx[property];\n }\n }\n if (sourceCtx.setLineDash !== undefined) {\n destCtx.setLineDash(sourceCtx.getLineDash());\n destCtx.lineDashOffset = sourceCtx.lineDashOffset;\n }\n}\n\nfunction resetCtxToDefault(ctx) {\n ctx.strokeStyle = ctx.fillStyle = \"#000000\";\n ctx.fillRule = \"nonzero\";\n ctx.globalAlpha = 1;\n ctx.lineWidth = 1;\n ctx.lineCap = \"butt\";\n ctx.lineJoin = \"miter\";\n ctx.miterLimit = 10;\n ctx.globalCompositeOperation = \"source-over\";\n ctx.font = \"10px sans-serif\";\n if (ctx.setLineDash !== undefined) {\n ctx.setLineDash([]);\n ctx.lineDashOffset = 0;\n }\n if (\n (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) ||\n !isNodeJS\n ) {\n const { filter } = ctx;\n if (filter !== \"none\" && filter !== \"\") {\n ctx.filter = \"none\";\n }\n }\n}\n\nfunction getImageSmoothingEnabled(transform, interpolate) {\n // In section 8.9.5.3 of the PDF spec, it's mentioned that the interpolate\n // flag should be used when the image is upscaled.\n // In Firefox, smoothing is always used when downscaling images (bug 1360415).\n\n if (interpolate) {\n return true;\n }\n\n const scale = Util.singularValueDecompose2dScale(transform);\n // Round to a 32bit float so that `<=` check below will pass for numbers that\n // are very close, but not exactly the same 64bit floats.\n scale[0] = Math.fround(scale[0]);\n scale[1] = Math.fround(scale[1]);\n const actualScale = Math.fround(\n (globalThis.devicePixelRatio || 1) * PixelsPerInch.PDF_TO_CSS_UNITS\n );\n return scale[0] <= actualScale && scale[1] <= actualScale;\n}\n\nconst LINE_CAP_STYLES = [\"butt\", \"round\", \"square\"];\nconst LINE_JOIN_STYLES = [\"miter\", \"round\", \"bevel\"];\nconst NORMAL_CLIP = {};\nconst EO_CLIP = {};\n\nclass CanvasGraphics {\n constructor(\n canvasCtx,\n commonObjs,\n objs,\n canvasFactory,\n filterFactory,\n { optionalContentConfig, markedContentStack = null },\n annotationCanvasMap,\n pageColors\n ) {\n this.ctx = canvasCtx;\n this.current = new CanvasExtraState(\n this.ctx.canvas.width,\n this.ctx.canvas.height\n );\n this.stateStack = [];\n this.pendingClip = null;\n this.pendingEOFill = false;\n this.res = null;\n this.xobjs = null;\n this.commonObjs = commonObjs;\n this.objs = objs;\n this.canvasFactory = canvasFactory;\n this.filterFactory = filterFactory;\n this.groupStack = [];\n this.processingType3 = null;\n // Patterns are painted relative to the initial page/form transform, see\n // PDF spec 8.7.2 NOTE 1.\n this.baseTransform = null;\n this.baseTransformStack = [];\n this.groupLevel = 0;\n this.smaskStack = [];\n this.smaskCounter = 0;\n this.tempSMask = null;\n this.suspendedCtx = null;\n this.contentVisible = true;\n this.markedContentStack = markedContentStack || [];\n this.optionalContentConfig = optionalContentConfig;\n this.cachedCanvases = new CachedCanvases(this.canvasFactory);\n this.cachedPatterns = new Map();\n this.annotationCanvasMap = annotationCanvasMap;\n this.viewportScale = 1;\n this.outputScaleX = 1;\n this.outputScaleY = 1;\n this.pageColors = pageColors;\n\n this._cachedScaleForStroking = [-1, 0];\n this._cachedGetSinglePixelWidth = null;\n this._cachedBitmapsMap = new Map();\n }\n\n getObject(data, fallback = null) {\n if (typeof data === \"string\") {\n return data.startsWith(\"g_\")\n ? this.commonObjs.get(data)\n : this.objs.get(data);\n }\n return fallback;\n }\n\n beginDrawing({\n transform,\n viewport,\n transparency = false,\n background = null,\n }) {\n // For pdfs that use blend modes we have to clear the canvas else certain\n // blend modes can look wrong since we'd be blending with a white\n // backdrop. The problem with a transparent backdrop though is we then\n // don't get sub pixel anti aliasing on text, creating temporary\n // transparent canvas when we have blend modes.\n const width = this.ctx.canvas.width;\n const height = this.ctx.canvas.height;\n\n const savedFillStyle = this.ctx.fillStyle;\n this.ctx.fillStyle = background || \"#ffffff\";\n this.ctx.fillRect(0, 0, width, height);\n this.ctx.fillStyle = savedFillStyle;\n\n if (transparency) {\n const transparentCanvas = this.cachedCanvases.getCanvas(\n \"transparent\",\n width,\n height\n );\n this.compositeCtx = this.ctx;\n this.transparentCanvas = transparentCanvas.canvas;\n this.ctx = transparentCanvas.context;\n this.ctx.save();\n // The transform can be applied before rendering, transferring it to\n // the new canvas.\n this.ctx.transform(...getCurrentTransform(this.compositeCtx));\n }\n\n this.ctx.save();\n resetCtxToDefault(this.ctx);\n if (transform) {\n this.ctx.transform(...transform);\n this.outputScaleX = transform[0];\n this.outputScaleY = transform[0];\n }\n this.ctx.transform(...viewport.transform);\n this.viewportScale = viewport.scale;\n\n this.baseTransform = getCurrentTransform(this.ctx);\n }\n\n executeOperatorList(\n operatorList,\n executionStartIdx,\n continueCallback,\n stepper\n ) {\n const argsArray = operatorList.argsArray;\n const fnArray = operatorList.fnArray;\n let i = executionStartIdx || 0;\n const argsArrayLen = argsArray.length;\n\n // Sometimes the OperatorList to execute is empty.\n if (argsArrayLen === i) {\n return i;\n }\n\n const chunkOperations =\n argsArrayLen - i > EXECUTION_STEPS &&\n typeof continueCallback === \"function\";\n const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;\n let steps = 0;\n\n const commonObjs = this.commonObjs;\n const objs = this.objs;\n let fnId;\n\n while (true) {\n if (stepper !== undefined && i === stepper.nextBreakPoint) {\n stepper.breakIt(i, continueCallback);\n return i;\n }\n\n fnId = fnArray[i];\n\n if (fnId !== OPS.dependency) {\n // eslint-disable-next-line prefer-spread\n this[fnId].apply(this, argsArray[i]);\n } else {\n for (const depObjId of argsArray[i]) {\n const objsPool = depObjId.startsWith(\"g_\") ? commonObjs : objs;\n\n // If the promise isn't resolved yet, add the continueCallback\n // to the promise and bail out.\n if (!objsPool.has(depObjId)) {\n objsPool.get(depObjId, continueCallback);\n return i;\n }\n }\n }\n\n i++;\n\n // If the entire operatorList was executed, stop as were done.\n if (i === argsArrayLen) {\n return i;\n }\n\n // If the execution took longer then a certain amount of time and\n // `continueCallback` is specified, interrupt the execution.\n if (chunkOperations && ++steps > EXECUTION_STEPS) {\n if (Date.now() > endTime) {\n continueCallback();\n return i;\n }\n steps = 0;\n }\n\n // If the operatorList isn't executed completely yet OR the execution\n // time was short enough, do another execution round.\n }\n }\n\n #restoreInitialState() {\n // Finishing all opened operations such as SMask group painting.\n while (this.stateStack.length || this.inSMaskMode) {\n this.restore();\n }\n\n this.current.activeSMask = null;\n this.ctx.restore();\n\n if (this.transparentCanvas) {\n this.ctx = this.compositeCtx;\n this.ctx.save();\n this.ctx.setTransform(1, 0, 0, 1, 0, 0); // Avoid apply transform twice\n this.ctx.drawImage(this.transparentCanvas, 0, 0);\n this.ctx.restore();\n this.transparentCanvas = null;\n }\n }\n\n endDrawing() {\n this.#restoreInitialState();\n\n this.cachedCanvases.clear();\n this.cachedPatterns.clear();\n\n for (const cache of this._cachedBitmapsMap.values()) {\n for (const canvas of cache.values()) {\n if (\n typeof HTMLCanvasElement !== \"undefined\" &&\n canvas instanceof HTMLCanvasElement\n ) {\n canvas.width = canvas.height = 0;\n }\n }\n cache.clear();\n }\n this._cachedBitmapsMap.clear();\n this.#drawFilter();\n }\n\n #drawFilter() {\n if (this.pageColors) {\n const hcmFilterId = this.filterFactory.addHCMFilter(\n this.pageColors.foreground,\n this.pageColors.background\n );\n if (hcmFilterId !== \"none\") {\n const savedFilter = this.ctx.filter;\n this.ctx.filter = hcmFilterId;\n this.ctx.drawImage(this.ctx.canvas, 0, 0);\n this.ctx.filter = savedFilter;\n }\n }\n }\n\n _scaleImage(img, inverseTransform) {\n // Vertical or horizontal scaling shall not be more than 2 to not lose the\n // pixels during drawImage operation, painting on the temporary canvas(es)\n // that are twice smaller in size.\n const width = img.width;\n const height = img.height;\n let widthScale = Math.max(\n Math.hypot(inverseTransform[0], inverseTransform[1]),\n 1\n );\n let heightScale = Math.max(\n Math.hypot(inverseTransform[2], inverseTransform[3]),\n 1\n );\n\n let paintWidth = width,\n paintHeight = height;\n let tmpCanvasId = \"prescale1\";\n let tmpCanvas, tmpCtx;\n while (\n (widthScale > 2 && paintWidth > 1) ||\n (heightScale > 2 && paintHeight > 1)\n ) {\n let newWidth = paintWidth,\n newHeight = paintHeight;\n if (widthScale > 2 && paintWidth > 1) {\n // See bug 1820511 (Windows specific bug).\n // TODO: once the above bug is fixed we could revert to:\n // newWidth = Math.ceil(paintWidth / 2);\n newWidth =\n paintWidth >= 16384\n ? Math.floor(paintWidth / 2) - 1 || 1\n : Math.ceil(paintWidth / 2);\n widthScale /= paintWidth / newWidth;\n }\n if (heightScale > 2 && paintHeight > 1) {\n // TODO: see the comment above.\n newHeight =\n paintHeight >= 16384\n ? Math.floor(paintHeight / 2) - 1 || 1\n : Math.ceil(paintHeight) / 2;\n heightScale /= paintHeight / newHeight;\n }\n tmpCanvas = this.cachedCanvases.getCanvas(\n tmpCanvasId,\n newWidth,\n newHeight\n );\n tmpCtx = tmpCanvas.context;\n tmpCtx.clearRect(0, 0, newWidth, newHeight);\n tmpCtx.drawImage(\n img,\n 0,\n 0,\n paintWidth,\n paintHeight,\n 0,\n 0,\n newWidth,\n newHeight\n );\n img = tmpCanvas.canvas;\n paintWidth = newWidth;\n paintHeight = newHeight;\n tmpCanvasId = tmpCanvasId === \"prescale1\" ? \"prescale2\" : \"prescale1\";\n }\n return {\n img,\n paintWidth,\n paintHeight,\n };\n }\n\n _createMaskCanvas(img) {\n const ctx = this.ctx;\n const { width, height } = img;\n const fillColor = this.current.fillColor;\n const isPatternFill = this.current.patternFill;\n const currentTransform = getCurrentTransform(ctx);\n\n let cache, cacheKey, scaled, maskCanvas;\n if ((img.bitmap || img.data) && img.count > 1) {\n const mainKey = img.bitmap || img.data.buffer;\n // We're reusing the same image several times, so we can cache it.\n // In case we've a pattern fill we just keep the scaled version of\n // the image.\n // Only the scaling part matters, the translation part is just used\n // to compute offsets (but not when filling patterns see #15573).\n // TODO: handle the case of a pattern fill if it's possible.\n cacheKey = JSON.stringify(\n isPatternFill\n ? currentTransform\n : [currentTransform.slice(0, 4), fillColor]\n );\n\n cache = this._cachedBitmapsMap.get(mainKey);\n if (!cache) {\n cache = new Map();\n this._cachedBitmapsMap.set(mainKey, cache);\n }\n const cachedImage = cache.get(cacheKey);\n if (cachedImage && !isPatternFill) {\n const offsetX = Math.round(\n Math.min(currentTransform[0], currentTransform[2]) +\n currentTransform[4]\n );\n const offsetY = Math.round(\n Math.min(currentTransform[1], currentTransform[3]) +\n currentTransform[5]\n );\n return {\n canvas: cachedImage,\n offsetX,\n offsetY,\n };\n }\n scaled = cachedImage;\n }\n\n if (!scaled) {\n maskCanvas = this.cachedCanvases.getCanvas(\"maskCanvas\", width, height);\n putBinaryImageMask(maskCanvas.context, img);\n }\n\n // Create the mask canvas at the size it will be drawn at and also set\n // its transform to match the current transform so if there are any\n // patterns applied they will be applied relative to the correct\n // transform.\n\n let maskToCanvas = Util.transform(currentTransform, [\n 1 / width,\n 0,\n 0,\n -1 / height,\n 0,\n 0,\n ]);\n maskToCanvas = Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]);\n const [minX, minY, maxX, maxY] = Util.getAxialAlignedBoundingBox(\n [0, 0, width, height],\n maskToCanvas\n );\n const drawnWidth = Math.round(maxX - minX) || 1;\n const drawnHeight = Math.round(maxY - minY) || 1;\n const fillCanvas = this.cachedCanvases.getCanvas(\n \"fillCanvas\",\n drawnWidth,\n drawnHeight\n );\n const fillCtx = fillCanvas.context;\n\n // The offset will be the top-left cordinate mask.\n // If objToCanvas is [a,b,c,d,e,f] then:\n // - offsetX = min(a, c) + e\n // - offsetY = min(b, d) + f\n const offsetX = minX;\n const offsetY = minY;\n fillCtx.translate(-offsetX, -offsetY);\n fillCtx.transform(...maskToCanvas);\n\n if (!scaled) {\n // Pre-scale if needed to improve image smoothing.\n scaled = this._scaleImage(\n maskCanvas.canvas,\n getCurrentTransformInverse(fillCtx)\n );\n scaled = scaled.img;\n if (cache && isPatternFill) {\n cache.set(cacheKey, scaled);\n }\n }\n\n fillCtx.imageSmoothingEnabled = getImageSmoothingEnabled(\n getCurrentTransform(fillCtx),\n img.interpolate\n );\n\n drawImageAtIntegerCoords(\n fillCtx,\n scaled,\n 0,\n 0,\n scaled.width,\n scaled.height,\n 0,\n 0,\n width,\n height\n );\n fillCtx.globalCompositeOperation = \"source-in\";\n\n const inverse = Util.transform(getCurrentTransformInverse(fillCtx), [\n 1,\n 0,\n 0,\n 1,\n -offsetX,\n -offsetY,\n ]);\n fillCtx.fillStyle = isPatternFill\n ? fillColor.getPattern(ctx, this, inverse, PathType.FILL)\n : fillColor;\n\n fillCtx.fillRect(0, 0, width, height);\n\n if (cache && !isPatternFill) {\n // The fill canvas is put in the cache associated to the mask image\n // so we must remove from the cached canvas: it mustn't be used again.\n this.cachedCanvases.delete(\"fillCanvas\");\n cache.set(cacheKey, fillCanvas.canvas);\n }\n\n // Round the offsets to avoid drawing fractional pixels.\n return {\n canvas: fillCanvas.canvas,\n offsetX: Math.round(offsetX),\n offsetY: Math.round(offsetY),\n };\n }\n\n // Graphics state\n setLineWidth(width) {\n if (width !== this.current.lineWidth) {\n this._cachedScaleForStroking[0] = -1;\n }\n this.current.lineWidth = width;\n this.ctx.lineWidth = width;\n }\n\n setLineCap(style) {\n this.ctx.lineCap = LINE_CAP_STYLES[style];\n }\n\n setLineJoin(style) {\n this.ctx.lineJoin = LINE_JOIN_STYLES[style];\n }\n\n setMiterLimit(limit) {\n this.ctx.miterLimit = limit;\n }\n\n setDash(dashArray, dashPhase) {\n const ctx = this.ctx;\n if (ctx.setLineDash !== undefined) {\n ctx.setLineDash(dashArray);\n ctx.lineDashOffset = dashPhase;\n }\n }\n\n setRenderingIntent(intent) {\n // This operation is ignored since we haven't found a use case for it yet.\n }\n\n setFlatness(flatness) {\n // This operation is ignored since we haven't found a use case for it yet.\n }\n\n setGState(states) {\n for (const [key, value] of states) {\n switch (key) {\n case \"LW\":\n this.setLineWidth(value);\n break;\n case \"LC\":\n this.setLineCap(value);\n break;\n case \"LJ\":\n this.setLineJoin(value);\n break;\n case \"ML\":\n this.setMiterLimit(value);\n break;\n case \"D\":\n this.setDash(value[0], value[1]);\n break;\n case \"RI\":\n this.setRenderingIntent(value);\n break;\n case \"FL\":\n this.setFlatness(value);\n break;\n case \"Font\":\n this.setFont(value[0], value[1]);\n break;\n case \"CA\":\n this.current.strokeAlpha = value;\n break;\n case \"ca\":\n this.current.fillAlpha = value;\n this.ctx.globalAlpha = value;\n break;\n case \"BM\":\n this.ctx.globalCompositeOperation = value;\n break;\n case \"SMask\":\n this.current.activeSMask = value ? this.tempSMask : null;\n this.tempSMask = null;\n this.checkSMaskState();\n break;\n case \"TR\":\n this.ctx.filter = this.current.transferMaps =\n this.filterFactory.addFilter(value);\n break;\n }\n }\n }\n\n get inSMaskMode() {\n return !!this.suspendedCtx;\n }\n\n checkSMaskState() {\n const inSMaskMode = this.inSMaskMode;\n if (this.current.activeSMask && !inSMaskMode) {\n this.beginSMaskMode();\n } else if (!this.current.activeSMask && inSMaskMode) {\n this.endSMaskMode();\n }\n // Else, the state is okay and nothing needs to be done.\n }\n\n /**\n * Soft mask mode takes the current main drawing canvas and replaces it with\n * a temporary canvas. Any drawing operations that happen on the temporary\n * canvas need to be composed with the main canvas that was suspended (see\n * `compose()`). The temporary canvas also duplicates many of its operations\n * on the suspended canvas to keep them in sync, so that when the soft mask\n * mode ends any clipping paths or transformations will still be active and in\n * the right order on the canvas' graphics state stack.\n */\n beginSMaskMode() {\n if (this.inSMaskMode) {\n throw new Error(\"beginSMaskMode called while already in smask mode\");\n }\n const drawnWidth = this.ctx.canvas.width;\n const drawnHeight = this.ctx.canvas.height;\n const cacheId = \"smaskGroupAt\" + this.groupLevel;\n const scratchCanvas = this.cachedCanvases.getCanvas(\n cacheId,\n drawnWidth,\n drawnHeight\n );\n this.suspendedCtx = this.ctx;\n this.ctx = scratchCanvas.context;\n const ctx = this.ctx;\n ctx.setTransform(...getCurrentTransform(this.suspendedCtx));\n copyCtxState(this.suspendedCtx, ctx);\n mirrorContextOperations(ctx, this.suspendedCtx);\n\n this.setGState([\n [\"BM\", \"source-over\"],\n [\"ca\", 1],\n [\"CA\", 1],\n ]);\n }\n\n endSMaskMode() {\n if (!this.inSMaskMode) {\n throw new Error(\"endSMaskMode called while not in smask mode\");\n }\n // The soft mask is done, now restore the suspended canvas as the main\n // drawing canvas.\n this.ctx._removeMirroring();\n copyCtxState(this.ctx, this.suspendedCtx);\n this.ctx = this.suspendedCtx;\n\n this.suspendedCtx = null;\n }\n\n compose(dirtyBox) {\n if (!this.current.activeSMask) {\n return;\n }\n\n if (!dirtyBox) {\n dirtyBox = [0, 0, this.ctx.canvas.width, this.ctx.canvas.height];\n } else {\n dirtyBox[0] = Math.floor(dirtyBox[0]);\n dirtyBox[1] = Math.floor(dirtyBox[1]);\n dirtyBox[2] = Math.ceil(dirtyBox[2]);\n dirtyBox[3] = Math.ceil(dirtyBox[3]);\n }\n const smask = this.current.activeSMask;\n const suspendedCtx = this.suspendedCtx;\n\n this.composeSMask(suspendedCtx, smask, this.ctx, dirtyBox);\n // Whatever was drawn has been moved to the suspended canvas, now clear it\n // out of the current canvas.\n this.ctx.save();\n this.ctx.setTransform(1, 0, 0, 1, 0, 0);\n this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);\n this.ctx.restore();\n }\n\n composeSMask(ctx, smask, layerCtx, layerBox) {\n const layerOffsetX = layerBox[0];\n const layerOffsetY = layerBox[1];\n const layerWidth = layerBox[2] - layerOffsetX;\n const layerHeight = layerBox[3] - layerOffsetY;\n if (layerWidth === 0 || layerHeight === 0) {\n return;\n }\n this.genericComposeSMask(\n smask.context,\n layerCtx,\n layerWidth,\n layerHeight,\n smask.subtype,\n smask.backdrop,\n smask.transferMap,\n layerOffsetX,\n layerOffsetY,\n smask.offsetX,\n smask.offsetY\n );\n ctx.save();\n ctx.globalAlpha = 1;\n ctx.globalCompositeOperation = \"source-over\";\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.drawImage(layerCtx.canvas, 0, 0);\n ctx.restore();\n }\n\n genericComposeSMask(\n maskCtx,\n layerCtx,\n width,\n height,\n subtype,\n backdrop,\n transferMap,\n layerOffsetX,\n layerOffsetY,\n maskOffsetX,\n maskOffsetY\n ) {\n let maskCanvas = maskCtx.canvas;\n let maskX = layerOffsetX - maskOffsetX;\n let maskY = layerOffsetY - maskOffsetY;\n\n if (backdrop) {\n if (\n maskX < 0 ||\n maskY < 0 ||\n maskX + width > maskCanvas.width ||\n maskY + height > maskCanvas.height\n ) {\n const canvas = this.cachedCanvases.getCanvas(\n \"maskExtension\",\n width,\n height\n );\n const ctx = canvas.context;\n ctx.drawImage(maskCanvas, -maskX, -maskY);\n if (backdrop.some(c => c !== 0)) {\n ctx.globalCompositeOperation = \"destination-atop\";\n ctx.fillStyle = Util.makeHexColor(...backdrop);\n ctx.fillRect(0, 0, width, height);\n ctx.globalCompositeOperation = \"source-over\";\n }\n\n maskCanvas = canvas.canvas;\n maskX = maskY = 0;\n } else if (backdrop.some(c => c !== 0)) {\n maskCtx.save();\n maskCtx.globalAlpha = 1;\n maskCtx.setTransform(1, 0, 0, 1, 0, 0);\n const clip = new Path2D();\n clip.rect(maskX, maskY, width, height);\n maskCtx.clip(clip);\n maskCtx.globalCompositeOperation = \"destination-atop\";\n maskCtx.fillStyle = Util.makeHexColor(...backdrop);\n maskCtx.fillRect(maskX, maskY, width, height);\n maskCtx.restore();\n }\n }\n\n layerCtx.save();\n layerCtx.globalAlpha = 1;\n layerCtx.setTransform(1, 0, 0, 1, 0, 0);\n\n if (subtype === \"Alpha\" && transferMap) {\n layerCtx.filter = this.filterFactory.addAlphaFilter(transferMap);\n } else if (subtype === \"Luminosity\") {\n layerCtx.filter = this.filterFactory.addLuminosityFilter(transferMap);\n }\n\n const clip = new Path2D();\n clip.rect(layerOffsetX, layerOffsetY, width, height);\n layerCtx.clip(clip);\n layerCtx.globalCompositeOperation = \"destination-in\";\n layerCtx.drawImage(\n maskCanvas,\n maskX,\n maskY,\n width,\n height,\n layerOffsetX,\n layerOffsetY,\n width,\n height\n );\n layerCtx.restore();\n }\n\n save() {\n if (this.inSMaskMode) {\n // SMask mode may be turned on/off causing us to lose graphics state.\n // Copy the temporary canvas state to the main(suspended) canvas to keep\n // it in sync.\n copyCtxState(this.ctx, this.suspendedCtx);\n // Don't bother calling save on the temporary canvas since state is not\n // saved there.\n this.suspendedCtx.save();\n } else {\n this.ctx.save();\n }\n const old = this.current;\n this.stateStack.push(old);\n this.current = old.clone();\n }\n\n restore() {\n if (this.stateStack.length === 0 && this.inSMaskMode) {\n this.endSMaskMode();\n }\n if (this.stateStack.length !== 0) {\n this.current = this.stateStack.pop();\n if (this.inSMaskMode) {\n // Graphics state is stored on the main(suspended) canvas. Restore its\n // state then copy it over to the temporary canvas.\n this.suspendedCtx.restore();\n copyCtxState(this.suspendedCtx, this.ctx);\n } else {\n this.ctx.restore();\n }\n this.checkSMaskState();\n\n // Ensure that the clipping path is reset (fixes issue6413.pdf).\n this.pendingClip = null;\n\n this._cachedScaleForStroking[0] = -1;\n this._cachedGetSinglePixelWidth = null;\n }\n }\n\n transform(a, b, c, d, e, f) {\n this.ctx.transform(a, b, c, d, e, f);\n\n this._cachedScaleForStroking[0] = -1;\n this._cachedGetSinglePixelWidth = null;\n }\n\n // Path\n constructPath(ops, args, minMax) {\n const ctx = this.ctx;\n const current = this.current;\n let x = current.x,\n y = current.y;\n let startX, startY;\n const currentTransform = getCurrentTransform(ctx);\n\n // Most of the time the current transform is a scaling matrix\n // so we don't need to transform points before computing min/max:\n // we can compute min/max first and then smartly \"apply\" the\n // transform (see Util.scaleMinMax).\n // For rectangle, moveTo and lineTo, min/max are computed in the\n // worker (see evaluator.js).\n const isScalingMatrix =\n (currentTransform[0] === 0 && currentTransform[3] === 0) ||\n (currentTransform[1] === 0 && currentTransform[2] === 0);\n const minMaxForBezier = isScalingMatrix ? minMax.slice(0) : null;\n\n for (let i = 0, j = 0, ii = ops.length; i < ii; i++) {\n switch (ops[i] | 0) {\n case OPS.rectangle:\n x = args[j++];\n y = args[j++];\n const width = args[j++];\n const height = args[j++];\n\n const xw = x + width;\n const yh = y + height;\n ctx.moveTo(x, y);\n if (width === 0 || height === 0) {\n ctx.lineTo(xw, yh);\n } else {\n ctx.lineTo(xw, y);\n ctx.lineTo(xw, yh);\n ctx.lineTo(x, yh);\n }\n if (!isScalingMatrix) {\n current.updateRectMinMax(currentTransform, [x, y, xw, yh]);\n }\n ctx.closePath();\n break;\n case OPS.moveTo:\n x = args[j++];\n y = args[j++];\n ctx.moveTo(x, y);\n if (!isScalingMatrix) {\n current.updatePathMinMax(currentTransform, x, y);\n }\n break;\n case OPS.lineTo:\n x = args[j++];\n y = args[j++];\n ctx.lineTo(x, y);\n if (!isScalingMatrix) {\n current.updatePathMinMax(currentTransform, x, y);\n }\n break;\n case OPS.curveTo:\n startX = x;\n startY = y;\n x = args[j + 4];\n y = args[j + 5];\n ctx.bezierCurveTo(\n args[j],\n args[j + 1],\n args[j + 2],\n args[j + 3],\n x,\n y\n );\n current.updateCurvePathMinMax(\n currentTransform,\n startX,\n startY,\n args[j],\n args[j + 1],\n args[j + 2],\n args[j + 3],\n x,\n y,\n minMaxForBezier\n );\n j += 6;\n break;\n case OPS.curveTo2:\n startX = x;\n startY = y;\n ctx.bezierCurveTo(\n x,\n y,\n args[j],\n args[j + 1],\n args[j + 2],\n args[j + 3]\n );\n current.updateCurvePathMinMax(\n currentTransform,\n startX,\n startY,\n x,\n y,\n args[j],\n args[j + 1],\n args[j + 2],\n args[j + 3],\n minMaxForBezier\n );\n x = args[j + 2];\n y = args[j + 3];\n j += 4;\n break;\n case OPS.curveTo3:\n startX = x;\n startY = y;\n x = args[j + 2];\n y = args[j + 3];\n ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);\n current.updateCurvePathMinMax(\n currentTransform,\n startX,\n startY,\n args[j],\n args[j + 1],\n x,\n y,\n x,\n y,\n minMaxForBezier\n );\n j += 4;\n break;\n case OPS.closePath:\n ctx.closePath();\n break;\n }\n }\n\n if (isScalingMatrix) {\n current.updateScalingPathMinMax(currentTransform, minMaxForBezier);\n }\n\n current.setCurrentPoint(x, y);\n }\n\n closePath() {\n this.ctx.closePath();\n }\n\n stroke(consumePath = true) {\n const ctx = this.ctx;\n const strokeColor = this.current.strokeColor;\n // For stroke we want to temporarily change the global alpha to the\n // stroking alpha.\n ctx.globalAlpha = this.current.strokeAlpha;\n if (this.contentVisible) {\n if (typeof strokeColor === \"object\" && strokeColor?.getPattern) {\n ctx.save();\n ctx.strokeStyle = strokeColor.getPattern(\n ctx,\n this,\n getCurrentTransformInverse(ctx),\n PathType.STROKE\n );\n this.rescaleAndStroke(/* saveRestore */ false);\n ctx.restore();\n } else {\n this.rescaleAndStroke(/* saveRestore */ true);\n }\n }\n if (consumePath) {\n this.consumePath(this.current.getClippedPathBoundingBox());\n }\n // Restore the global alpha to the fill alpha\n ctx.globalAlpha = this.current.fillAlpha;\n }\n\n closeStroke() {\n this.closePath();\n this.stroke();\n }\n\n fill(consumePath = true) {\n const ctx = this.ctx;\n const fillColor = this.current.fillColor;\n const isPatternFill = this.current.patternFill;\n let needRestore = false;\n\n if (isPatternFill) {\n ctx.save();\n ctx.fillStyle = fillColor.getPattern(\n ctx,\n this,\n getCurrentTransformInverse(ctx),\n PathType.FILL\n );\n needRestore = true;\n }\n\n const intersect = this.current.getClippedPathBoundingBox();\n if (this.contentVisible && intersect !== null) {\n if (this.pendingEOFill) {\n ctx.fill(\"evenodd\");\n this.pendingEOFill = false;\n } else {\n ctx.fill();\n }\n }\n\n if (needRestore) {\n ctx.restore();\n }\n if (consumePath) {\n this.consumePath(intersect);\n }\n }\n\n eoFill() {\n this.pendingEOFill = true;\n this.fill();\n }\n\n fillStroke() {\n this.fill(false);\n this.stroke(false);\n\n this.consumePath();\n }\n\n eoFillStroke() {\n this.pendingEOFill = true;\n this.fillStroke();\n }\n\n closeFillStroke() {\n this.closePath();\n this.fillStroke();\n }\n\n closeEOFillStroke() {\n this.pendingEOFill = true;\n this.closePath();\n this.fillStroke();\n }\n\n endPath() {\n this.consumePath();\n }\n\n // Clipping\n clip() {\n this.pendingClip = NORMAL_CLIP;\n }\n\n eoClip() {\n this.pendingClip = EO_CLIP;\n }\n\n // Text\n beginText() {\n this.current.textMatrix = IDENTITY_MATRIX;\n this.current.textMatrixScale = 1;\n this.current.x = this.current.lineX = 0;\n this.current.y = this.current.lineY = 0;\n }\n\n endText() {\n const paths = this.pendingTextPaths;\n const ctx = this.ctx;\n if (paths === undefined) {\n ctx.beginPath();\n return;\n }\n\n ctx.save();\n ctx.beginPath();\n for (const path of paths) {\n ctx.setTransform(...path.transform);\n ctx.translate(path.x, path.y);\n path.addToPath(ctx, path.fontSize);\n }\n ctx.restore();\n ctx.clip();\n ctx.beginPath();\n delete this.pendingTextPaths;\n }\n\n setCharSpacing(spacing) {\n this.current.charSpacing = spacing;\n }\n\n setWordSpacing(spacing) {\n this.current.wordSpacing = spacing;\n }\n\n setHScale(scale) {\n this.current.textHScale = scale / 100;\n }\n\n setLeading(leading) {\n this.current.leading = -leading;\n }\n\n setFont(fontRefName, size) {\n const fontObj = this.commonObjs.get(fontRefName);\n const current = this.current;\n\n if (!fontObj) {\n throw new Error(`Can't find font for ${fontRefName}`);\n }\n current.fontMatrix = fontObj.fontMatrix || FONT_IDENTITY_MATRIX;\n\n // A valid matrix needs all main diagonal elements to be non-zero\n // This also ensures we bypass FF bugzilla bug #719844.\n if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {\n warn(\"Invalid font matrix for font \" + fontRefName);\n }\n\n // The spec for Tf (setFont) says that 'size' specifies the font 'scale',\n // and in some docs this can be negative (inverted x-y axes).\n if (size < 0) {\n size = -size;\n current.fontDirection = -1;\n } else {\n current.fontDirection = 1;\n }\n\n this.current.font = fontObj;\n this.current.fontSize = size;\n\n if (fontObj.isType3Font) {\n return; // we don't need ctx.font for Type3 fonts\n }\n\n const name = fontObj.loadedName || \"sans-serif\";\n const typeface =\n fontObj.systemFontInfo?.css || `\"${name}\", ${fontObj.fallbackName}`;\n\n let bold = \"normal\";\n if (fontObj.black) {\n bold = \"900\";\n } else if (fontObj.bold) {\n bold = \"bold\";\n }\n const italic = fontObj.italic ? \"italic\" : \"normal\";\n\n // Some font backends cannot handle fonts below certain size.\n // Keeping the font at minimal size and using the fontSizeScale to change\n // the current transformation matrix before the fillText/strokeText.\n // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227\n let browserFontSize = size;\n if (size < MIN_FONT_SIZE) {\n browserFontSize = MIN_FONT_SIZE;\n } else if (size > MAX_FONT_SIZE) {\n browserFontSize = MAX_FONT_SIZE;\n }\n this.current.fontSizeScale = size / browserFontSize;\n\n this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`;\n }\n\n setTextRenderingMode(mode) {\n this.current.textRenderingMode = mode;\n }\n\n setTextRise(rise) {\n this.current.textRise = rise;\n }\n\n moveText(x, y) {\n this.current.x = this.current.lineX += x;\n this.current.y = this.current.lineY += y;\n }\n\n setLeadingMoveText(x, y) {\n this.setLeading(-y);\n this.moveText(x, y);\n }\n\n setTextMatrix(a, b, c, d, e, f) {\n this.current.textMatrix = [a, b, c, d, e, f];\n this.current.textMatrixScale = Math.hypot(a, b);\n\n this.current.x = this.current.lineX = 0;\n this.current.y = this.current.lineY = 0;\n }\n\n nextLine() {\n this.moveText(0, this.current.leading);\n }\n\n paintChar(character, x, y, patternTransform) {\n const ctx = this.ctx;\n const current = this.current;\n const font = current.font;\n const textRenderingMode = current.textRenderingMode;\n const fontSize = current.fontSize / current.fontSizeScale;\n const fillStrokeMode =\n textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;\n const isAddToPathSet = !!(\n textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG\n );\n const patternFill = current.patternFill && !font.missingFile;\n\n let addToPath;\n if (font.disableFontFace || isAddToPathSet || patternFill) {\n addToPath = font.getPathGenerator(this.commonObjs, character);\n }\n\n if (font.disableFontFace || patternFill) {\n ctx.save();\n ctx.translate(x, y);\n ctx.beginPath();\n addToPath(ctx, fontSize);\n if (patternTransform) {\n ctx.setTransform(...patternTransform);\n }\n if (\n fillStrokeMode === TextRenderingMode.FILL ||\n fillStrokeMode === TextRenderingMode.FILL_STROKE\n ) {\n ctx.fill();\n }\n if (\n fillStrokeMode === TextRenderingMode.STROKE ||\n fillStrokeMode === TextRenderingMode.FILL_STROKE\n ) {\n ctx.stroke();\n }\n ctx.restore();\n } else {\n if (\n fillStrokeMode === TextRenderingMode.FILL ||\n fillStrokeMode === TextRenderingMode.FILL_STROKE\n ) {\n ctx.fillText(character, x, y);\n }\n if (\n fillStrokeMode === TextRenderingMode.STROKE ||\n fillStrokeMode === TextRenderingMode.FILL_STROKE\n ) {\n ctx.strokeText(character, x, y);\n }\n }\n\n if (isAddToPathSet) {\n const paths = (this.pendingTextPaths ||= []);\n paths.push({\n transform: getCurrentTransform(ctx),\n x,\n y,\n fontSize,\n addToPath,\n });\n }\n }\n\n get isFontSubpixelAAEnabled() {\n // Checks if anti-aliasing is enabled when scaled text is painted.\n // On Windows GDI scaled fonts looks bad.\n const { context: ctx } = this.cachedCanvases.getCanvas(\n \"isFontSubpixelAAEnabled\",\n 10,\n 10\n );\n ctx.scale(1.5, 1);\n ctx.fillText(\"I\", 0, 10);\n const data = ctx.getImageData(0, 0, 10, 10).data;\n let enabled = false;\n for (let i = 3; i < data.length; i += 4) {\n if (data[i] > 0 && data[i] < 255) {\n enabled = true;\n break;\n }\n }\n return shadow(this, \"isFontSubpixelAAEnabled\", enabled);\n }\n\n showText(glyphs) {\n const current = this.current;\n const font = current.font;\n if (font.isType3Font) {\n return this.showType3Text(glyphs);\n }\n\n const fontSize = current.fontSize;\n if (fontSize === 0) {\n return undefined;\n }\n\n const ctx = this.ctx;\n const fontSizeScale = current.fontSizeScale;\n const charSpacing = current.charSpacing;\n const wordSpacing = current.wordSpacing;\n const fontDirection = current.fontDirection;\n const textHScale = current.textHScale * fontDirection;\n const glyphsLength = glyphs.length;\n const vertical = font.vertical;\n const spacingDir = vertical ? 1 : -1;\n const defaultVMetrics = font.defaultVMetrics;\n const widthAdvanceScale = fontSize * current.fontMatrix[0];\n\n const simpleFillText =\n current.textRenderingMode === TextRenderingMode.FILL &&\n !font.disableFontFace &&\n !current.patternFill;\n\n ctx.save();\n ctx.transform(...current.textMatrix);\n ctx.translate(current.x, current.y + current.textRise);\n\n if (fontDirection > 0) {\n ctx.scale(textHScale, -1);\n } else {\n ctx.scale(textHScale, 1);\n }\n\n let patternTransform;\n if (current.patternFill) {\n ctx.save();\n const pattern = current.fillColor.getPattern(\n ctx,\n this,\n getCurrentTransformInverse(ctx),\n PathType.FILL\n );\n patternTransform = getCurrentTransform(ctx);\n ctx.restore();\n ctx.fillStyle = pattern;\n }\n\n let lineWidth = current.lineWidth;\n const scale = current.textMatrixScale;\n if (scale === 0 || lineWidth === 0) {\n const fillStrokeMode =\n current.textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;\n if (\n fillStrokeMode === TextRenderingMode.STROKE ||\n fillStrokeMode === TextRenderingMode.FILL_STROKE\n ) {\n lineWidth = this.getSinglePixelWidth();\n }\n } else {\n lineWidth /= scale;\n }\n\n if (fontSizeScale !== 1.0) {\n ctx.scale(fontSizeScale, fontSizeScale);\n lineWidth /= fontSizeScale;\n }\n\n ctx.lineWidth = lineWidth;\n\n if (font.isInvalidPDFjsFont) {\n const chars = [];\n let width = 0;\n for (const glyph of glyphs) {\n chars.push(glyph.unicode);\n width += glyph.width;\n }\n ctx.fillText(chars.join(\"\"), 0, 0);\n current.x += width * widthAdvanceScale * textHScale;\n ctx.restore();\n this.compose();\n\n return undefined;\n }\n\n let x = 0,\n i;\n for (i = 0; i < glyphsLength; ++i) {\n const glyph = glyphs[i];\n if (typeof glyph === \"number\") {\n x += (spacingDir * glyph * fontSize) / 1000;\n continue;\n }\n\n let restoreNeeded = false;\n const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;\n const character = glyph.fontChar;\n const accent = glyph.accent;\n let scaledX, scaledY;\n let width = glyph.width;\n if (vertical) {\n const vmetric = glyph.vmetric || defaultVMetrics;\n const vx =\n -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale;\n const vy = vmetric[2] * widthAdvanceScale;\n\n width = vmetric ? -vmetric[0] : width;\n scaledX = vx / fontSizeScale;\n scaledY = (x + vy) / fontSizeScale;\n } else {\n scaledX = x / fontSizeScale;\n scaledY = 0;\n }\n\n if (font.remeasure && width > 0) {\n // Some standard fonts may not have the exact width: rescale per\n // character if measured width is greater than expected glyph width\n // and subpixel-aa is enabled, otherwise just center the glyph.\n const measuredWidth =\n ((ctx.measureText(character).width * 1000) / fontSize) *\n fontSizeScale;\n if (width < measuredWidth && this.isFontSubpixelAAEnabled) {\n const characterScaleX = width / measuredWidth;\n restoreNeeded = true;\n ctx.save();\n ctx.scale(characterScaleX, 1);\n scaledX /= characterScaleX;\n } else if (width !== measuredWidth) {\n scaledX +=\n (((width - measuredWidth) / 2000) * fontSize) / fontSizeScale;\n }\n }\n\n // Only attempt to draw the glyph if it is actually in the embedded font\n // file or if there isn't a font file so the fallback font is shown.\n if (this.contentVisible && (glyph.isInFont || font.missingFile)) {\n if (simpleFillText && !accent) {\n // common case\n ctx.fillText(character, scaledX, scaledY);\n } else {\n this.paintChar(character, scaledX, scaledY, patternTransform);\n if (accent) {\n const scaledAccentX =\n scaledX + (fontSize * accent.offset.x) / fontSizeScale;\n const scaledAccentY =\n scaledY - (fontSize * accent.offset.y) / fontSizeScale;\n this.paintChar(\n accent.fontChar,\n scaledAccentX,\n scaledAccentY,\n patternTransform\n );\n }\n }\n }\n\n const charWidth = vertical\n ? width * widthAdvanceScale - spacing * fontDirection\n : width * widthAdvanceScale + spacing * fontDirection;\n x += charWidth;\n\n if (restoreNeeded) {\n ctx.restore();\n }\n }\n if (vertical) {\n current.y -= x;\n } else {\n current.x += x * textHScale;\n }\n ctx.restore();\n this.compose();\n\n return undefined;\n }\n\n showType3Text(glyphs) {\n // Type3 fonts - each glyph is a \"mini-PDF\"\n const ctx = this.ctx;\n const current = this.current;\n const font = current.font;\n const fontSize = current.fontSize;\n const fontDirection = current.fontDirection;\n const spacingDir = font.vertical ? 1 : -1;\n const charSpacing = current.charSpacing;\n const wordSpacing = current.wordSpacing;\n const textHScale = current.textHScale * fontDirection;\n const fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;\n const glyphsLength = glyphs.length;\n const isTextInvisible =\n current.textRenderingMode === TextRenderingMode.INVISIBLE;\n let i, glyph, width, spacingLength;\n\n if (isTextInvisible || fontSize === 0) {\n return;\n }\n this._cachedScaleForStroking[0] = -1;\n this._cachedGetSinglePixelWidth = null;\n\n ctx.save();\n ctx.transform(...current.textMatrix);\n ctx.translate(current.x, current.y);\n\n ctx.scale(textHScale, fontDirection);\n\n for (i = 0; i < glyphsLength; ++i) {\n glyph = glyphs[i];\n if (typeof glyph === \"number\") {\n spacingLength = (spacingDir * glyph * fontSize) / 1000;\n this.ctx.translate(spacingLength, 0);\n current.x += spacingLength * textHScale;\n continue;\n }\n\n const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;\n const operatorList = font.charProcOperatorList[glyph.operatorListId];\n if (!operatorList) {\n warn(`Type3 character \"${glyph.operatorListId}\" is not available.`);\n continue;\n }\n if (this.contentVisible) {\n this.processingType3 = glyph;\n this.save();\n ctx.scale(fontSize, fontSize);\n ctx.transform(...fontMatrix);\n this.executeOperatorList(operatorList);\n this.restore();\n }\n\n const transformed = Util.applyTransform([glyph.width, 0], fontMatrix);\n width = transformed[0] * fontSize + spacing;\n\n ctx.translate(width, 0);\n current.x += width * textHScale;\n }\n ctx.restore();\n this.processingType3 = null;\n }\n\n // Type3 fonts\n setCharWidth(xWidth, yWidth) {\n // We can safely ignore this since the width should be the same\n // as the width in the Widths array.\n }\n\n setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {\n this.ctx.rect(llx, lly, urx - llx, ury - lly);\n this.ctx.clip();\n this.endPath();\n }\n\n // Color\n getColorN_Pattern(IR) {\n let pattern;\n if (IR[0] === \"TilingPattern\") {\n const color = IR[1];\n const baseTransform = this.baseTransform || getCurrentTransform(this.ctx);\n const canvasGraphicsFactory = {\n createCanvasGraphics: ctx =>\n new CanvasGraphics(\n ctx,\n this.commonObjs,\n this.objs,\n this.canvasFactory,\n this.filterFactory,\n {\n optionalContentConfig: this.optionalContentConfig,\n markedContentStack: this.markedContentStack,\n }\n ),\n };\n pattern = new TilingPattern(\n IR,\n color,\n this.ctx,\n canvasGraphicsFactory,\n baseTransform\n );\n } else {\n pattern = this._getPattern(IR[1], IR[2]);\n }\n return pattern;\n }\n\n setStrokeColorN() {\n this.current.strokeColor = this.getColorN_Pattern(arguments);\n }\n\n setFillColorN() {\n this.current.fillColor = this.getColorN_Pattern(arguments);\n this.current.patternFill = true;\n }\n\n setStrokeRGBColor(r, g, b) {\n this.ctx.strokeStyle = this.current.strokeColor = Util.makeHexColor(\n r,\n g,\n b\n );\n }\n\n setStrokeTransparent() {\n this.ctx.strokeStyle = this.current.strokeColor = \"transparent\";\n }\n\n setFillRGBColor(r, g, b) {\n this.ctx.fillStyle = this.current.fillColor = Util.makeHexColor(r, g, b);\n this.current.patternFill = false;\n }\n\n setFillTransparent() {\n this.ctx.fillStyle = this.current.fillColor = \"transparent\";\n this.current.patternFill = false;\n }\n\n _getPattern(objId, matrix = null) {\n let pattern;\n if (this.cachedPatterns.has(objId)) {\n pattern = this.cachedPatterns.get(objId);\n } else {\n pattern = getShadingPattern(this.getObject(objId));\n this.cachedPatterns.set(objId, pattern);\n }\n if (matrix) {\n pattern.matrix = matrix;\n }\n return pattern;\n }\n\n shadingFill(objId) {\n if (!this.contentVisible) {\n return;\n }\n const ctx = this.ctx;\n\n this.save();\n const pattern = this._getPattern(objId);\n ctx.fillStyle = pattern.getPattern(\n ctx,\n this,\n getCurrentTransformInverse(ctx),\n PathType.SHADING\n );\n\n const inv = getCurrentTransformInverse(ctx);\n if (inv) {\n const { width, height } = ctx.canvas;\n const [x0, y0, x1, y1] = Util.getAxialAlignedBoundingBox(\n [0, 0, width, height],\n inv\n );\n\n this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);\n } else {\n // HACK to draw the gradient onto an infinite rectangle.\n // PDF gradients are drawn across the entire image while\n // Canvas only allows gradients to be drawn in a rectangle\n // The following bug should allow us to remove this.\n // https://bugzilla.mozilla.org/show_bug.cgi?id=664884\n\n this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);\n }\n\n this.compose(this.current.getClippedPathBoundingBox());\n this.restore();\n }\n\n // Images\n beginInlineImage() {\n unreachable(\"Should not call beginInlineImage\");\n }\n\n beginImageData() {\n unreachable(\"Should not call beginImageData\");\n }\n\n paintFormXObjectBegin(matrix, bbox) {\n if (!this.contentVisible) {\n return;\n }\n this.save();\n this.baseTransformStack.push(this.baseTransform);\n\n if (matrix) {\n this.transform(...matrix);\n }\n this.baseTransform = getCurrentTransform(this.ctx);\n\n if (bbox) {\n const width = bbox[2] - bbox[0];\n const height = bbox[3] - bbox[1];\n this.ctx.rect(bbox[0], bbox[1], width, height);\n this.current.updateRectMinMax(getCurrentTransform(this.ctx), bbox);\n this.clip();\n this.endPath();\n }\n }\n\n paintFormXObjectEnd() {\n if (!this.contentVisible) {\n return;\n }\n this.restore();\n this.baseTransform = this.baseTransformStack.pop();\n }\n\n beginGroup(group) {\n if (!this.contentVisible) {\n return;\n }\n\n this.save();\n // If there's an active soft mask we don't want it enabled for the group, so\n // clear it out. The mask and suspended canvas will be restored in endGroup.\n if (this.inSMaskMode) {\n this.endSMaskMode();\n this.current.activeSMask = null;\n }\n\n const currentCtx = this.ctx;\n // TODO non-isolated groups - according to Rik at adobe non-isolated\n // group results aren't usually that different and they even have tools\n // that ignore this setting. Notes from Rik on implementing:\n // - When you encounter an transparency group, create a new canvas with\n // the dimensions of the bbox\n // - copy the content from the previous canvas to the new canvas\n // - draw as usual\n // - remove the backdrop alpha:\n // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha\n // value of your transparency group and 'alphaBackdrop' the alpha of the\n // backdrop\n // - remove background color:\n // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)\n if (!group.isolated) {\n info(\"TODO: Support non-isolated groups.\");\n }\n\n // TODO knockout - supposedly possible with the clever use of compositing\n // modes.\n if (group.knockout) {\n warn(\"Knockout groups not supported.\");\n }\n\n const currentTransform = getCurrentTransform(currentCtx);\n if (group.matrix) {\n currentCtx.transform(...group.matrix);\n }\n if (!group.bbox) {\n throw new Error(\"Bounding box is required.\");\n }\n\n // Based on the current transform figure out how big the bounding box\n // will actually be.\n let bounds = Util.getAxialAlignedBoundingBox(\n group.bbox,\n getCurrentTransform(currentCtx)\n );\n // Clip the bounding box to the current canvas.\n const canvasBounds = [\n 0,\n 0,\n currentCtx.canvas.width,\n currentCtx.canvas.height,\n ];\n bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];\n // Use ceil in case we're between sizes so we don't create canvas that is\n // too small and make the canvas at least 1x1 pixels.\n const offsetX = Math.floor(bounds[0]);\n const offsetY = Math.floor(bounds[1]);\n const drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);\n const drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);\n\n this.current.startNewPathAndClipBox([0, 0, drawnWidth, drawnHeight]);\n\n let cacheId = \"groupAt\" + this.groupLevel;\n if (group.smask) {\n // Using two cache entries is case if masks are used one after another.\n cacheId += \"_smask_\" + (this.smaskCounter++ % 2);\n }\n const scratchCanvas = this.cachedCanvases.getCanvas(\n cacheId,\n drawnWidth,\n drawnHeight\n );\n const groupCtx = scratchCanvas.context;\n\n // Since we created a new canvas that is just the size of the bounding box\n // we have to translate the group ctx.\n groupCtx.translate(-offsetX, -offsetY);\n groupCtx.transform(...currentTransform);\n\n if (group.smask) {\n // Saving state and cached mask to be used in setGState.\n this.smaskStack.push({\n canvas: scratchCanvas.canvas,\n context: groupCtx,\n offsetX,\n offsetY,\n subtype: group.smask.subtype,\n backdrop: group.smask.backdrop,\n transferMap: group.smask.transferMap || null,\n startTransformInverse: null, // used during suspend operation\n });\n } else {\n // Setup the current ctx so when the group is popped we draw it at the\n // right location.\n currentCtx.setTransform(1, 0, 0, 1, 0, 0);\n currentCtx.translate(offsetX, offsetY);\n currentCtx.save();\n }\n // The transparency group inherits all off the current graphics state\n // except the blend mode, soft mask, and alpha constants.\n copyCtxState(currentCtx, groupCtx);\n this.ctx = groupCtx;\n this.setGState([\n [\"BM\", \"source-over\"],\n [\"ca\", 1],\n [\"CA\", 1],\n ]);\n this.groupStack.push(currentCtx);\n this.groupLevel++;\n }\n\n endGroup(group) {\n if (!this.contentVisible) {\n return;\n }\n this.groupLevel--;\n const groupCtx = this.ctx;\n const ctx = this.groupStack.pop();\n this.ctx = ctx;\n // Turn off image smoothing to avoid sub pixel interpolation which can\n // look kind of blurry for some pdfs.\n this.ctx.imageSmoothingEnabled = false;\n\n if (group.smask) {\n this.tempSMask = this.smaskStack.pop();\n this.restore();\n } else {\n this.ctx.restore();\n const currentMtx = getCurrentTransform(this.ctx);\n this.restore();\n this.ctx.save();\n this.ctx.setTransform(...currentMtx);\n const dirtyBox = Util.getAxialAlignedBoundingBox(\n [0, 0, groupCtx.canvas.width, groupCtx.canvas.height],\n currentMtx\n );\n this.ctx.drawImage(groupCtx.canvas, 0, 0);\n this.ctx.restore();\n this.compose(dirtyBox);\n }\n }\n\n beginAnnotation(id, rect, transform, matrix, hasOwnCanvas) {\n // The annotations are drawn just after the page content.\n // The page content drawing can potentially have set a transform,\n // a clipping path, whatever...\n // So in order to have something clean, we restore the initial state.\n this.#restoreInitialState();\n resetCtxToDefault(this.ctx);\n\n this.ctx.save();\n this.save();\n\n if (this.baseTransform) {\n this.ctx.setTransform(...this.baseTransform);\n }\n\n if (rect) {\n const width = rect[2] - rect[0];\n const height = rect[3] - rect[1];\n\n if (hasOwnCanvas && this.annotationCanvasMap) {\n transform = transform.slice();\n transform[4] -= rect[0];\n transform[5] -= rect[1];\n\n rect = rect.slice();\n rect[0] = rect[1] = 0;\n rect[2] = width;\n rect[3] = height;\n\n const [scaleX, scaleY] = Util.singularValueDecompose2dScale(\n getCurrentTransform(this.ctx)\n );\n const { viewportScale } = this;\n const canvasWidth = Math.ceil(\n width * this.outputScaleX * viewportScale\n );\n const canvasHeight = Math.ceil(\n height * this.outputScaleY * viewportScale\n );\n\n this.annotationCanvas = this.canvasFactory.create(\n canvasWidth,\n canvasHeight\n );\n const { canvas, context } = this.annotationCanvas;\n this.annotationCanvasMap.set(id, canvas);\n this.annotationCanvas.savedCtx = this.ctx;\n this.ctx = context;\n this.ctx.save();\n this.ctx.setTransform(scaleX, 0, 0, -scaleY, 0, height * scaleY);\n\n resetCtxToDefault(this.ctx);\n } else {\n resetCtxToDefault(this.ctx);\n\n this.ctx.rect(rect[0], rect[1], width, height);\n this.ctx.clip();\n this.endPath();\n }\n }\n\n this.current = new CanvasExtraState(\n this.ctx.canvas.width,\n this.ctx.canvas.height\n );\n\n this.transform(...transform);\n this.transform(...matrix);\n }\n\n endAnnotation() {\n if (this.annotationCanvas) {\n this.ctx.restore();\n this.#drawFilter();\n\n this.ctx = this.annotationCanvas.savedCtx;\n delete this.annotationCanvas.savedCtx;\n delete this.annotationCanvas;\n }\n }\n\n paintImageMaskXObject(img) {\n if (!this.contentVisible) {\n return;\n }\n const count = img.count;\n img = this.getObject(img.data, img);\n img.count = count;\n\n const ctx = this.ctx;\n const glyph = this.processingType3;\n\n if (glyph) {\n if (glyph.compiled === undefined) {\n glyph.compiled = compileType3Glyph(img);\n }\n\n if (glyph.compiled) {\n glyph.compiled(ctx);\n return;\n }\n }\n const mask = this._createMaskCanvas(img);\n const maskCanvas = mask.canvas;\n\n ctx.save();\n // The mask is drawn with the transform applied. Reset the current\n // transform to draw to the identity.\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY);\n ctx.restore();\n this.compose();\n }\n\n paintImageMaskXObjectRepeat(\n img,\n scaleX,\n skewX = 0,\n skewY = 0,\n scaleY,\n positions\n ) {\n if (!this.contentVisible) {\n return;\n }\n\n img = this.getObject(img.data, img);\n\n const ctx = this.ctx;\n ctx.save();\n const currentTransform = getCurrentTransform(ctx);\n ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0);\n const mask = this._createMaskCanvas(img);\n\n ctx.setTransform(\n 1,\n 0,\n 0,\n 1,\n mask.offsetX - currentTransform[4],\n mask.offsetY - currentTransform[5]\n );\n for (let i = 0, ii = positions.length; i < ii; i += 2) {\n const trans = Util.transform(currentTransform, [\n scaleX,\n skewX,\n skewY,\n scaleY,\n positions[i],\n positions[i + 1],\n ]);\n\n const [x, y] = Util.applyTransform([0, 0], trans);\n ctx.drawImage(mask.canvas, x, y);\n }\n ctx.restore();\n this.compose();\n }\n\n paintImageMaskXObjectGroup(images) {\n if (!this.contentVisible) {\n return;\n }\n const ctx = this.ctx;\n\n const fillColor = this.current.fillColor;\n const isPatternFill = this.current.patternFill;\n\n for (const image of images) {\n const { data, width, height, transform } = image;\n\n const maskCanvas = this.cachedCanvases.getCanvas(\n \"maskCanvas\",\n width,\n height\n );\n const maskCtx = maskCanvas.context;\n maskCtx.save();\n\n const img = this.getObject(data, image);\n putBinaryImageMask(maskCtx, img);\n\n maskCtx.globalCompositeOperation = \"source-in\";\n\n maskCtx.fillStyle = isPatternFill\n ? fillColor.getPattern(\n maskCtx,\n this,\n getCurrentTransformInverse(ctx),\n PathType.FILL\n )\n : fillColor;\n maskCtx.fillRect(0, 0, width, height);\n\n maskCtx.restore();\n\n ctx.save();\n ctx.transform(...transform);\n ctx.scale(1, -1);\n drawImageAtIntegerCoords(\n ctx,\n maskCanvas.canvas,\n 0,\n 0,\n width,\n height,\n 0,\n -1,\n 1,\n 1\n );\n ctx.restore();\n }\n this.compose();\n }\n\n paintImageXObject(objId) {\n if (!this.contentVisible) {\n return;\n }\n const imgData = this.getObject(objId);\n if (!imgData) {\n warn(\"Dependent image isn't ready yet\");\n return;\n }\n\n this.paintInlineImageXObject(imgData);\n }\n\n paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {\n if (!this.contentVisible) {\n return;\n }\n const imgData = this.getObject(objId);\n if (!imgData) {\n warn(\"Dependent image isn't ready yet\");\n return;\n }\n\n const width = imgData.width;\n const height = imgData.height;\n const map = [];\n for (let i = 0, ii = positions.length; i < ii; i += 2) {\n map.push({\n transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]],\n x: 0,\n y: 0,\n w: width,\n h: height,\n });\n }\n this.paintInlineImageXObjectGroup(imgData, map);\n }\n\n applyTransferMapsToCanvas(ctx) {\n if (this.current.transferMaps !== \"none\") {\n ctx.filter = this.current.transferMaps;\n ctx.drawImage(ctx.canvas, 0, 0);\n ctx.filter = \"none\";\n }\n return ctx.canvas;\n }\n\n applyTransferMapsToBitmap(imgData) {\n if (this.current.transferMaps === \"none\") {\n return imgData.bitmap;\n }\n const { bitmap, width, height } = imgData;\n const tmpCanvas = this.cachedCanvases.getCanvas(\n \"inlineImage\",\n width,\n height\n );\n const tmpCtx = tmpCanvas.context;\n tmpCtx.filter = this.current.transferMaps;\n tmpCtx.drawImage(bitmap, 0, 0);\n tmpCtx.filter = \"none\";\n\n return tmpCanvas.canvas;\n }\n\n paintInlineImageXObject(imgData) {\n if (!this.contentVisible) {\n return;\n }\n const width = imgData.width;\n const height = imgData.height;\n const ctx = this.ctx;\n\n this.save();\n\n if (\n (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) ||\n !isNodeJS\n ) {\n // The filter, if any, will be applied in applyTransferMapsToBitmap.\n // It must be applied to the image before rescaling else some artifacts\n // could appear.\n // The final restore will reset it to its value.\n const { filter } = ctx;\n if (filter !== \"none\" && filter !== \"\") {\n ctx.filter = \"none\";\n }\n }\n\n // scale the image to the unit square\n ctx.scale(1 / width, -1 / height);\n\n let imgToPaint;\n if (imgData.bitmap) {\n imgToPaint = this.applyTransferMapsToBitmap(imgData);\n } else if (\n (typeof HTMLElement === \"function\" && imgData instanceof HTMLElement) ||\n !imgData.data\n ) {\n // typeof check is needed due to node.js support, see issue #8489\n imgToPaint = imgData;\n } else {\n const tmpCanvas = this.cachedCanvases.getCanvas(\n \"inlineImage\",\n width,\n height\n );\n const tmpCtx = tmpCanvas.context;\n putBinaryImageData(tmpCtx, imgData);\n imgToPaint = this.applyTransferMapsToCanvas(tmpCtx);\n }\n\n const scaled = this._scaleImage(\n imgToPaint,\n getCurrentTransformInverse(ctx)\n );\n ctx.imageSmoothingEnabled = getImageSmoothingEnabled(\n getCurrentTransform(ctx),\n imgData.interpolate\n );\n\n drawImageAtIntegerCoords(\n ctx,\n scaled.img,\n 0,\n 0,\n scaled.paintWidth,\n scaled.paintHeight,\n 0,\n -height,\n width,\n height\n );\n this.compose();\n this.restore();\n }\n\n paintInlineImageXObjectGroup(imgData, map) {\n if (!this.contentVisible) {\n return;\n }\n const ctx = this.ctx;\n let imgToPaint;\n if (imgData.bitmap) {\n imgToPaint = imgData.bitmap;\n } else {\n const w = imgData.width;\n const h = imgData.height;\n\n const tmpCanvas = this.cachedCanvases.getCanvas(\"inlineImage\", w, h);\n const tmpCtx = tmpCanvas.context;\n putBinaryImageData(tmpCtx, imgData);\n imgToPaint = this.applyTransferMapsToCanvas(tmpCtx);\n }\n\n for (const entry of map) {\n ctx.save();\n ctx.transform(...entry.transform);\n ctx.scale(1, -1);\n drawImageAtIntegerCoords(\n ctx,\n imgToPaint,\n entry.x,\n entry.y,\n entry.w,\n entry.h,\n 0,\n -1,\n 1,\n 1\n );\n ctx.restore();\n }\n this.compose();\n }\n\n paintSolidColorImageMask() {\n if (!this.contentVisible) {\n return;\n }\n this.ctx.fillRect(0, 0, 1, 1);\n this.compose();\n }\n\n // Marked content\n\n markPoint(tag) {\n // TODO Marked content.\n }\n\n markPointProps(tag, properties) {\n // TODO Marked content.\n }\n\n beginMarkedContent(tag) {\n this.markedContentStack.push({\n visible: true,\n });\n }\n\n beginMarkedContentProps(tag, properties) {\n if (tag === \"OC\") {\n this.markedContentStack.push({\n visible: this.optionalContentConfig.isVisible(properties),\n });\n } else {\n this.markedContentStack.push({\n visible: true,\n });\n }\n this.contentVisible = this.isContentVisible();\n }\n\n endMarkedContent() {\n this.markedContentStack.pop();\n this.contentVisible = this.isContentVisible();\n }\n\n // Compatibility\n\n beginCompat() {\n // TODO ignore undefined operators (should we do that anyway?)\n }\n\n endCompat() {\n // TODO stop ignoring undefined operators\n }\n\n // Helper functions\n\n consumePath(clipBox) {\n const isEmpty = this.current.isEmptyClip();\n if (this.pendingClip) {\n this.current.updateClipFromPath();\n }\n if (!this.pendingClip) {\n this.compose(clipBox);\n }\n const ctx = this.ctx;\n if (this.pendingClip) {\n if (!isEmpty) {\n if (this.pendingClip === EO_CLIP) {\n ctx.clip(\"evenodd\");\n } else {\n ctx.clip();\n }\n }\n this.pendingClip = null;\n }\n this.current.startNewPathAndClipBox(this.current.clipBox);\n ctx.beginPath();\n }\n\n getSinglePixelWidth() {\n if (!this._cachedGetSinglePixelWidth) {\n const m = getCurrentTransform(this.ctx);\n if (m[1] === 0 && m[2] === 0) {\n // Fast path\n this._cachedGetSinglePixelWidth =\n 1 / Math.min(Math.abs(m[0]), Math.abs(m[3]));\n } else {\n const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);\n const normX = Math.hypot(m[0], m[2]);\n const normY = Math.hypot(m[1], m[3]);\n this._cachedGetSinglePixelWidth = Math.max(normX, normY) / absDet;\n }\n }\n return this._cachedGetSinglePixelWidth;\n }\n\n getScaleForStroking() {\n // A pixel has thicknessX = thicknessY = 1;\n // A transformed pixel is a parallelogram and the thicknesses\n // corresponds to the heights.\n // The goal of this function is to rescale before setting the\n // lineWidth in order to have both thicknesses greater or equal\n // to 1 after transform.\n if (this._cachedScaleForStroking[0] === -1) {\n const { lineWidth } = this.current;\n const { a, b, c, d } = this.ctx.getTransform();\n let scaleX, scaleY;\n\n if (b === 0 && c === 0) {\n // Fast path\n const normX = Math.abs(a);\n const normY = Math.abs(d);\n if (normX === normY) {\n if (lineWidth === 0) {\n scaleX = scaleY = 1 / normX;\n } else {\n const scaledLineWidth = normX * lineWidth;\n scaleX = scaleY = scaledLineWidth < 1 ? 1 / scaledLineWidth : 1;\n }\n } else if (lineWidth === 0) {\n scaleX = 1 / normX;\n scaleY = 1 / normY;\n } else {\n const scaledXLineWidth = normX * lineWidth;\n const scaledYLineWidth = normY * lineWidth;\n scaleX = scaledXLineWidth < 1 ? 1 / scaledXLineWidth : 1;\n scaleY = scaledYLineWidth < 1 ? 1 / scaledYLineWidth : 1;\n }\n } else {\n // A pixel (base (x, y)) is transformed by M into a parallelogram:\n // - its area is |det(M)|;\n // - heightY (orthogonal to Mx) has a length: |det(M)| / norm(Mx);\n // - heightX (orthogonal to My) has a length: |det(M)| / norm(My).\n // heightX and heightY are the thicknesses of the transformed pixel\n // and they must be both greater or equal to 1.\n const absDet = Math.abs(a * d - b * c);\n const normX = Math.hypot(a, b);\n const normY = Math.hypot(c, d);\n if (lineWidth === 0) {\n scaleX = normY / absDet;\n scaleY = normX / absDet;\n } else {\n const baseArea = lineWidth * absDet;\n scaleX = normY > baseArea ? normY / baseArea : 1;\n scaleY = normX > baseArea ? normX / baseArea : 1;\n }\n }\n this._cachedScaleForStroking[0] = scaleX;\n this._cachedScaleForStroking[1] = scaleY;\n }\n return this._cachedScaleForStroking;\n }\n\n // Rescale before stroking in order to have a final lineWidth\n // with both thicknesses greater or equal to 1.\n rescaleAndStroke(saveRestore) {\n const { ctx } = this;\n const { lineWidth } = this.current;\n const [scaleX, scaleY] = this.getScaleForStroking();\n\n ctx.lineWidth = lineWidth || 1;\n\n if (scaleX === 1 && scaleY === 1) {\n ctx.stroke();\n return;\n }\n\n const dashes = ctx.getLineDash();\n if (saveRestore) {\n ctx.save();\n }\n\n ctx.scale(scaleX, scaleY);\n\n // How the dashed line is rendered depends on the current transform...\n // so we added a rescale to handle too thin lines and consequently\n // the way the line is dashed will be modified.\n // If scaleX === scaleY, the dashed lines will be rendered correctly\n // else we'll have some bugs (but only with too thin lines).\n // Here we take the max... why not taking the min... or something else.\n // Anyway, as said it's buggy when scaleX !== scaleY.\n if (dashes.length > 0) {\n const scale = Math.max(scaleX, scaleY);\n ctx.setLineDash(dashes.map(x => x / scale));\n ctx.lineDashOffset /= scale;\n }\n\n ctx.stroke();\n\n if (saveRestore) {\n ctx.restore();\n }\n }\n\n isContentVisible() {\n for (let i = this.markedContentStack.length - 1; i >= 0; i--) {\n if (!this.markedContentStack[i].visible) {\n return false;\n }\n }\n return true;\n }\n}\n\nfor (const op in OPS) {\n if (CanvasGraphics.prototype[op] !== undefined) {\n CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];\n }\n}\n\nexport { CanvasGraphics };\n","/* Copyright 2018 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nclass GlobalWorkerOptions {\n static #port = null;\n\n static #src = \"\";\n\n /**\n * @type {Worker | null}\n */\n static get workerPort() {\n return this.#port;\n }\n\n /**\n * @param {Worker | null} workerPort - Defines global port for worker process.\n * Overrides the `workerSrc` option.\n */\n static set workerPort(val) {\n if (\n !(typeof Worker !== \"undefined\" && val instanceof Worker) &&\n val !== null\n ) {\n throw new Error(\"Invalid `workerPort` type.\");\n }\n this.#port = val;\n }\n\n /**\n * @type {string}\n */\n static get workerSrc() {\n return this.#src;\n }\n\n /**\n * @param {string} workerSrc - A string containing the path and filename of\n * the worker file.\n *\n * NOTE: The `workerSrc` option should always be set, in order to prevent\n * any issues when using the PDF.js library.\n */\n static set workerSrc(val) {\n if (typeof val !== \"string\") {\n throw new Error(\"Invalid `workerSrc` type.\");\n }\n this.#src = val;\n }\n}\n\nexport { GlobalWorkerOptions };\n","/* Copyright 2018 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AbortException,\n assert,\n MissingPDFException,\n PasswordException,\n UnexpectedResponseException,\n UnknownErrorException,\n unreachable,\n} from \"./util.js\";\n\nconst CallbackKind = {\n UNKNOWN: 0,\n DATA: 1,\n ERROR: 2,\n};\n\nconst StreamKind = {\n UNKNOWN: 0,\n CANCEL: 1,\n CANCEL_COMPLETE: 2,\n CLOSE: 3,\n ENQUEUE: 4,\n ERROR: 5,\n PULL: 6,\n PULL_COMPLETE: 7,\n START_COMPLETE: 8,\n};\n\nfunction wrapReason(reason) {\n if (\n !(\n reason instanceof Error ||\n (typeof reason === \"object\" && reason !== null)\n )\n ) {\n unreachable(\n 'wrapReason: Expected \"reason\" to be a (possibly cloned) Error.'\n );\n }\n switch (reason.name) {\n case \"AbortException\":\n return new AbortException(reason.message);\n case \"MissingPDFException\":\n return new MissingPDFException(reason.message);\n case \"PasswordException\":\n return new PasswordException(reason.message, reason.code);\n case \"UnexpectedResponseException\":\n return new UnexpectedResponseException(reason.message, reason.status);\n case \"UnknownErrorException\":\n return new UnknownErrorException(reason.message, reason.details);\n default:\n return new UnknownErrorException(reason.message, reason.toString());\n }\n}\n\nclass MessageHandler {\n constructor(sourceName, targetName, comObj) {\n this.sourceName = sourceName;\n this.targetName = targetName;\n this.comObj = comObj;\n this.callbackId = 1;\n this.streamId = 1;\n this.streamSinks = Object.create(null);\n this.streamControllers = Object.create(null);\n this.callbackCapabilities = Object.create(null);\n this.actionHandler = Object.create(null);\n\n this._onComObjOnMessage = event => {\n const data = event.data;\n if (data.targetName !== this.sourceName) {\n return;\n }\n if (data.stream) {\n this.#processStreamMessage(data);\n return;\n }\n if (data.callback) {\n const callbackId = data.callbackId;\n const capability = this.callbackCapabilities[callbackId];\n if (!capability) {\n throw new Error(`Cannot resolve callback ${callbackId}`);\n }\n delete this.callbackCapabilities[callbackId];\n\n if (data.callback === CallbackKind.DATA) {\n capability.resolve(data.data);\n } else if (data.callback === CallbackKind.ERROR) {\n capability.reject(wrapReason(data.reason));\n } else {\n throw new Error(\"Unexpected callback case\");\n }\n return;\n }\n const action = this.actionHandler[data.action];\n if (!action) {\n throw new Error(`Unknown action from worker: ${data.action}`);\n }\n if (data.callbackId) {\n const cbSourceName = this.sourceName;\n const cbTargetName = data.sourceName;\n\n new Promise(function (resolve) {\n resolve(action(data.data));\n }).then(\n function (result) {\n comObj.postMessage({\n sourceName: cbSourceName,\n targetName: cbTargetName,\n callback: CallbackKind.DATA,\n callbackId: data.callbackId,\n data: result,\n });\n },\n function (reason) {\n comObj.postMessage({\n sourceName: cbSourceName,\n targetName: cbTargetName,\n callback: CallbackKind.ERROR,\n callbackId: data.callbackId,\n reason: wrapReason(reason),\n });\n }\n );\n return;\n }\n if (data.streamId) {\n this.#createStreamSink(data);\n return;\n }\n action(data.data);\n };\n comObj.addEventListener(\"message\", this._onComObjOnMessage);\n }\n\n on(actionName, handler) {\n if (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) {\n assert(\n typeof handler === \"function\",\n 'MessageHandler.on: Expected \"handler\" to be a function.'\n );\n }\n const ah = this.actionHandler;\n if (ah[actionName]) {\n throw new Error(`There is already an actionName called \"${actionName}\"`);\n }\n ah[actionName] = handler;\n }\n\n /**\n * Sends a message to the comObj to invoke the action with the supplied data.\n * @param {string} actionName - Action to call.\n * @param {JSON} data - JSON data to send.\n * @param {Array} [transfers] - List of transfers/ArrayBuffers.\n */\n send(actionName, data, transfers) {\n this.comObj.postMessage(\n {\n sourceName: this.sourceName,\n targetName: this.targetName,\n action: actionName,\n data,\n },\n transfers\n );\n }\n\n /**\n * Sends a message to the comObj to invoke the action with the supplied data.\n * Expects that the other side will callback with the response.\n * @param {string} actionName - Action to call.\n * @param {JSON} data - JSON data to send.\n * @param {Array} [transfers] - List of transfers/ArrayBuffers.\n * @returns {Promise} Promise to be resolved with response data.\n */\n sendWithPromise(actionName, data, transfers) {\n const callbackId = this.callbackId++;\n const capability = Promise.withResolvers();\n this.callbackCapabilities[callbackId] = capability;\n try {\n this.comObj.postMessage(\n {\n sourceName: this.sourceName,\n targetName: this.targetName,\n action: actionName,\n callbackId,\n data,\n },\n transfers\n );\n } catch (ex) {\n capability.reject(ex);\n }\n return capability.promise;\n }\n\n /**\n * Sends a message to the comObj to invoke the action with the supplied data.\n * Expect that the other side will callback to signal 'start_complete'.\n * @param {string} actionName - Action to call.\n * @param {JSON} data - JSON data to send.\n * @param {Object} queueingStrategy - Strategy to signal backpressure based on\n * internal queue.\n * @param {Array} [transfers] - List of transfers/ArrayBuffers.\n * @returns {ReadableStream} ReadableStream to read data in chunks.\n */\n sendWithStream(actionName, data, queueingStrategy, transfers) {\n const streamId = this.streamId++,\n sourceName = this.sourceName,\n targetName = this.targetName,\n comObj = this.comObj;\n\n return new ReadableStream(\n {\n start: controller => {\n const startCapability = Promise.withResolvers();\n this.streamControllers[streamId] = {\n controller,\n startCall: startCapability,\n pullCall: null,\n cancelCall: null,\n isClosed: false,\n };\n comObj.postMessage(\n {\n sourceName,\n targetName,\n action: actionName,\n streamId,\n data,\n desiredSize: controller.desiredSize,\n },\n transfers\n );\n // Return Promise for Async process, to signal success/failure.\n return startCapability.promise;\n },\n\n pull: controller => {\n const pullCapability = Promise.withResolvers();\n this.streamControllers[streamId].pullCall = pullCapability;\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.PULL,\n streamId,\n desiredSize: controller.desiredSize,\n });\n // Returning Promise will not call \"pull\"\n // again until current pull is resolved.\n return pullCapability.promise;\n },\n\n cancel: reason => {\n assert(reason instanceof Error, \"cancel must have a valid reason\");\n const cancelCapability = Promise.withResolvers();\n this.streamControllers[streamId].cancelCall = cancelCapability;\n this.streamControllers[streamId].isClosed = true;\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.CANCEL,\n streamId,\n reason: wrapReason(reason),\n });\n // Return Promise to signal success or failure.\n return cancelCapability.promise;\n },\n },\n queueingStrategy\n );\n }\n\n #createStreamSink(data) {\n const streamId = data.streamId,\n sourceName = this.sourceName,\n targetName = data.sourceName,\n comObj = this.comObj;\n const self = this,\n action = this.actionHandler[data.action];\n\n const streamSink = {\n enqueue(chunk, size = 1, transfers) {\n if (this.isCancelled) {\n return;\n }\n const lastDesiredSize = this.desiredSize;\n this.desiredSize -= size;\n // Enqueue decreases the desiredSize property of sink,\n // so when it changes from positive to negative,\n // set ready as unresolved promise.\n if (lastDesiredSize > 0 && this.desiredSize <= 0) {\n this.sinkCapability = Promise.withResolvers();\n this.ready = this.sinkCapability.promise;\n }\n comObj.postMessage(\n {\n sourceName,\n targetName,\n stream: StreamKind.ENQUEUE,\n streamId,\n chunk,\n },\n transfers\n );\n },\n\n close() {\n if (this.isCancelled) {\n return;\n }\n this.isCancelled = true;\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.CLOSE,\n streamId,\n });\n delete self.streamSinks[streamId];\n },\n\n error(reason) {\n assert(reason instanceof Error, \"error must have a valid reason\");\n if (this.isCancelled) {\n return;\n }\n this.isCancelled = true;\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.ERROR,\n streamId,\n reason: wrapReason(reason),\n });\n },\n\n sinkCapability: Promise.withResolvers(),\n onPull: null,\n onCancel: null,\n isCancelled: false,\n desiredSize: data.desiredSize,\n ready: null,\n };\n\n streamSink.sinkCapability.resolve();\n streamSink.ready = streamSink.sinkCapability.promise;\n this.streamSinks[streamId] = streamSink;\n\n new Promise(function (resolve) {\n resolve(action(data.data, streamSink));\n }).then(\n function () {\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.START_COMPLETE,\n streamId,\n success: true,\n });\n },\n function (reason) {\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.START_COMPLETE,\n streamId,\n reason: wrapReason(reason),\n });\n }\n );\n }\n\n #processStreamMessage(data) {\n const streamId = data.streamId,\n sourceName = this.sourceName,\n targetName = data.sourceName,\n comObj = this.comObj;\n const streamController = this.streamControllers[streamId],\n streamSink = this.streamSinks[streamId];\n\n switch (data.stream) {\n case StreamKind.START_COMPLETE:\n if (data.success) {\n streamController.startCall.resolve();\n } else {\n streamController.startCall.reject(wrapReason(data.reason));\n }\n break;\n case StreamKind.PULL_COMPLETE:\n if (data.success) {\n streamController.pullCall.resolve();\n } else {\n streamController.pullCall.reject(wrapReason(data.reason));\n }\n break;\n case StreamKind.PULL:\n // Ignore any pull after close is called.\n if (!streamSink) {\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.PULL_COMPLETE,\n streamId,\n success: true,\n });\n break;\n }\n // Pull increases the desiredSize property of sink, so when it changes\n // from negative to positive, set ready property as resolved promise.\n if (streamSink.desiredSize <= 0 && data.desiredSize > 0) {\n streamSink.sinkCapability.resolve();\n }\n // Reset desiredSize property of sink on every pull.\n streamSink.desiredSize = data.desiredSize;\n\n new Promise(function (resolve) {\n resolve(streamSink.onPull?.());\n }).then(\n function () {\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.PULL_COMPLETE,\n streamId,\n success: true,\n });\n },\n function (reason) {\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.PULL_COMPLETE,\n streamId,\n reason: wrapReason(reason),\n });\n }\n );\n break;\n case StreamKind.ENQUEUE:\n assert(streamController, \"enqueue should have stream controller\");\n if (streamController.isClosed) {\n break;\n }\n streamController.controller.enqueue(data.chunk);\n break;\n case StreamKind.CLOSE:\n assert(streamController, \"close should have stream controller\");\n if (streamController.isClosed) {\n break;\n }\n streamController.isClosed = true;\n streamController.controller.close();\n this.#deleteStreamController(streamController, streamId);\n break;\n case StreamKind.ERROR:\n assert(streamController, \"error should have stream controller\");\n streamController.controller.error(wrapReason(data.reason));\n this.#deleteStreamController(streamController, streamId);\n break;\n case StreamKind.CANCEL_COMPLETE:\n if (data.success) {\n streamController.cancelCall.resolve();\n } else {\n streamController.cancelCall.reject(wrapReason(data.reason));\n }\n this.#deleteStreamController(streamController, streamId);\n break;\n case StreamKind.CANCEL:\n if (!streamSink) {\n break;\n }\n\n new Promise(function (resolve) {\n resolve(streamSink.onCancel?.(wrapReason(data.reason)));\n }).then(\n function () {\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.CANCEL_COMPLETE,\n streamId,\n success: true,\n });\n },\n function (reason) {\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.CANCEL_COMPLETE,\n streamId,\n reason: wrapReason(reason),\n });\n }\n );\n streamSink.sinkCapability.reject(wrapReason(data.reason));\n streamSink.isCancelled = true;\n delete this.streamSinks[streamId];\n break;\n default:\n throw new Error(\"Unexpected stream case\");\n }\n }\n\n async #deleteStreamController(streamController, streamId) {\n // Delete the `streamController` only when the start, pull, and cancel\n // capabilities have settled, to prevent `TypeError`s.\n await Promise.allSettled([\n streamController.startCall?.promise,\n streamController.pullCall?.promise,\n streamController.cancelCall?.promise,\n ]);\n delete this.streamControllers[streamId];\n }\n\n destroy() {\n this.comObj.removeEventListener(\"message\", this._onComObjOnMessage);\n }\n}\n\nexport { MessageHandler };\n","/* Copyright 2012 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { objectFromMap } from \"../shared/util.js\";\n\nclass Metadata {\n #metadataMap;\n\n #data;\n\n constructor({ parsedData, rawData }) {\n this.#metadataMap = parsedData;\n this.#data = rawData;\n }\n\n getRaw() {\n return this.#data;\n }\n\n get(name) {\n return this.#metadataMap.get(name) ?? null;\n }\n\n getAll() {\n return objectFromMap(this.#metadataMap);\n }\n\n has(name) {\n return this.#metadataMap.has(name);\n }\n}\n\nexport { Metadata };\n","/* Copyright 2020 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n info,\n objectFromMap,\n RenderingIntentFlag,\n unreachable,\n warn,\n} from \"../shared/util.js\";\nimport { MurmurHash3_64 } from \"../shared/murmurhash3.js\";\n\nconst INTERNAL = Symbol(\"INTERNAL\");\n\nclass OptionalContentGroup {\n #isDisplay = false;\n\n #isPrint = false;\n\n #userSet = false;\n\n #visible = true;\n\n constructor(renderingIntent, { name, intent, usage }) {\n this.#isDisplay = !!(renderingIntent & RenderingIntentFlag.DISPLAY);\n this.#isPrint = !!(renderingIntent & RenderingIntentFlag.PRINT);\n\n this.name = name;\n this.intent = intent;\n this.usage = usage;\n }\n\n /**\n * @type {boolean}\n */\n get visible() {\n if (this.#userSet) {\n return this.#visible;\n }\n if (!this.#visible) {\n return false;\n }\n const { print, view } = this.usage;\n\n if (this.#isDisplay) {\n return view?.viewState !== \"OFF\";\n } else if (this.#isPrint) {\n return print?.printState !== \"OFF\";\n }\n return true;\n }\n\n /**\n * @ignore\n */\n _setVisible(internal, visible, userSet = false) {\n if (internal !== INTERNAL) {\n unreachable(\"Internal method `_setVisible` called.\");\n }\n this.#userSet = userSet;\n this.#visible = visible;\n }\n}\n\nclass OptionalContentConfig {\n #cachedGetHash = null;\n\n #groups = new Map();\n\n #initialHash = null;\n\n #order = null;\n\n constructor(data, renderingIntent = RenderingIntentFlag.DISPLAY) {\n this.renderingIntent = renderingIntent;\n\n this.name = null;\n this.creator = null;\n\n if (data === null) {\n return;\n }\n this.name = data.name;\n this.creator = data.creator;\n this.#order = data.order;\n for (const group of data.groups) {\n this.#groups.set(\n group.id,\n new OptionalContentGroup(renderingIntent, group)\n );\n }\n\n if (data.baseState === \"OFF\") {\n for (const group of this.#groups.values()) {\n group._setVisible(INTERNAL, false);\n }\n }\n\n for (const on of data.on) {\n this.#groups.get(on)._setVisible(INTERNAL, true);\n }\n\n for (const off of data.off) {\n this.#groups.get(off)._setVisible(INTERNAL, false);\n }\n\n // The following code must always run *last* in the constructor.\n this.#initialHash = this.getHash();\n }\n\n #evaluateVisibilityExpression(array) {\n const length = array.length;\n if (length < 2) {\n return true;\n }\n const operator = array[0];\n for (let i = 1; i < length; i++) {\n const element = array[i];\n let state;\n if (Array.isArray(element)) {\n state = this.#evaluateVisibilityExpression(element);\n } else if (this.#groups.has(element)) {\n state = this.#groups.get(element).visible;\n } else {\n warn(`Optional content group not found: ${element}`);\n return true;\n }\n switch (operator) {\n case \"And\":\n if (!state) {\n return false;\n }\n break;\n case \"Or\":\n if (state) {\n return true;\n }\n break;\n case \"Not\":\n return !state;\n default:\n return true;\n }\n }\n return operator === \"And\";\n }\n\n isVisible(group) {\n if (this.#groups.size === 0) {\n return true;\n }\n if (!group) {\n info(\"Optional content group not defined.\");\n return true;\n }\n if (group.type === \"OCG\") {\n if (!this.#groups.has(group.id)) {\n warn(`Optional content group not found: ${group.id}`);\n return true;\n }\n return this.#groups.get(group.id).visible;\n } else if (group.type === \"OCMD\") {\n // Per the spec, the expression should be preferred if available.\n if (group.expression) {\n return this.#evaluateVisibilityExpression(group.expression);\n }\n if (!group.policy || group.policy === \"AnyOn\") {\n // Default\n for (const id of group.ids) {\n if (!this.#groups.has(id)) {\n warn(`Optional content group not found: ${id}`);\n return true;\n }\n if (this.#groups.get(id).visible) {\n return true;\n }\n }\n return false;\n } else if (group.policy === \"AllOn\") {\n for (const id of group.ids) {\n if (!this.#groups.has(id)) {\n warn(`Optional content group not found: ${id}`);\n return true;\n }\n if (!this.#groups.get(id).visible) {\n return false;\n }\n }\n return true;\n } else if (group.policy === \"AnyOff\") {\n for (const id of group.ids) {\n if (!this.#groups.has(id)) {\n warn(`Optional content group not found: ${id}`);\n return true;\n }\n if (!this.#groups.get(id).visible) {\n return true;\n }\n }\n return false;\n } else if (group.policy === \"AllOff\") {\n for (const id of group.ids) {\n if (!this.#groups.has(id)) {\n warn(`Optional content group not found: ${id}`);\n return true;\n }\n if (this.#groups.get(id).visible) {\n return false;\n }\n }\n return true;\n }\n warn(`Unknown optional content policy ${group.policy}.`);\n return true;\n }\n warn(`Unknown group type ${group.type}.`);\n return true;\n }\n\n setVisibility(id, visible = true) {\n const group = this.#groups.get(id);\n if (!group) {\n warn(`Optional content group not found: ${id}`);\n return;\n }\n group._setVisible(INTERNAL, !!visible, /* userSet = */ true);\n\n this.#cachedGetHash = null;\n }\n\n setOCGState({ state, preserveRB }) {\n let operator;\n\n for (const elem of state) {\n switch (elem) {\n case \"ON\":\n case \"OFF\":\n case \"Toggle\":\n operator = elem;\n continue;\n }\n\n const group = this.#groups.get(elem);\n if (!group) {\n continue;\n }\n switch (operator) {\n case \"ON\":\n group._setVisible(INTERNAL, true);\n break;\n case \"OFF\":\n group._setVisible(INTERNAL, false);\n break;\n case \"Toggle\":\n group._setVisible(INTERNAL, !group.visible);\n break;\n }\n }\n\n this.#cachedGetHash = null;\n }\n\n get hasInitialVisibility() {\n return this.#initialHash === null || this.getHash() === this.#initialHash;\n }\n\n getOrder() {\n if (!this.#groups.size) {\n return null;\n }\n if (this.#order) {\n return this.#order.slice();\n }\n return [...this.#groups.keys()];\n }\n\n getGroups() {\n return this.#groups.size > 0 ? objectFromMap(this.#groups) : null;\n }\n\n getGroup(id) {\n return this.#groups.get(id) || null;\n }\n\n getHash() {\n if (this.#cachedGetHash !== null) {\n return this.#cachedGetHash;\n }\n const hash = new MurmurHash3_64();\n\n for (const [id, group] of this.#groups) {\n hash.update(`${id}:${group.visible}`);\n }\n return (this.#cachedGetHash = hash.hexdigest());\n }\n}\n\nexport { OptionalContentConfig };\n","/* Copyright 2012 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** @typedef {import(\"../interfaces\").IPDFStream} IPDFStream */\n/** @typedef {import(\"../interfaces\").IPDFStreamReader} IPDFStreamReader */\n// eslint-disable-next-line max-len\n/** @typedef {import(\"../interfaces\").IPDFStreamRangeReader} IPDFStreamRangeReader */\n\nimport { assert } from \"../shared/util.js\";\nimport { isPdfFile } from \"./display_utils.js\";\n\n/** @implements {IPDFStream} */\nclass PDFDataTransportStream {\n constructor(\n pdfDataRangeTransport,\n { disableRange = false, disableStream = false }\n ) {\n assert(\n pdfDataRangeTransport,\n 'PDFDataTransportStream - missing required \"pdfDataRangeTransport\" argument.'\n );\n const { length, initialData, progressiveDone, contentDispositionFilename } =\n pdfDataRangeTransport;\n\n this._queuedChunks = [];\n this._progressiveDone = progressiveDone;\n this._contentDispositionFilename = contentDispositionFilename;\n\n if (initialData?.length > 0) {\n // Prevent any possible issues by only transferring a Uint8Array that\n // completely \"utilizes\" its underlying ArrayBuffer.\n const buffer =\n initialData instanceof Uint8Array &&\n initialData.byteLength === initialData.buffer.byteLength\n ? initialData.buffer\n : new Uint8Array(initialData).buffer;\n this._queuedChunks.push(buffer);\n }\n\n this._pdfDataRangeTransport = pdfDataRangeTransport;\n this._isStreamingSupported = !disableStream;\n this._isRangeSupported = !disableRange;\n this._contentLength = length;\n\n this._fullRequestReader = null;\n this._rangeReaders = [];\n\n pdfDataRangeTransport.addRangeListener((begin, chunk) => {\n this._onReceiveData({ begin, chunk });\n });\n\n pdfDataRangeTransport.addProgressListener((loaded, total) => {\n this._onProgress({ loaded, total });\n });\n\n pdfDataRangeTransport.addProgressiveReadListener(chunk => {\n this._onReceiveData({ chunk });\n });\n\n pdfDataRangeTransport.addProgressiveDoneListener(() => {\n this._onProgressiveDone();\n });\n\n pdfDataRangeTransport.transportReady();\n }\n\n _onReceiveData({ begin, chunk }) {\n // Prevent any possible issues by only transferring a Uint8Array that\n // completely \"utilizes\" its underlying ArrayBuffer.\n const buffer =\n chunk instanceof Uint8Array &&\n chunk.byteLength === chunk.buffer.byteLength\n ? chunk.buffer\n : new Uint8Array(chunk).buffer;\n\n if (begin === undefined) {\n if (this._fullRequestReader) {\n this._fullRequestReader._enqueue(buffer);\n } else {\n this._queuedChunks.push(buffer);\n }\n } else {\n const found = this._rangeReaders.some(function (rangeReader) {\n if (rangeReader._begin !== begin) {\n return false;\n }\n rangeReader._enqueue(buffer);\n return true;\n });\n assert(\n found,\n \"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.\"\n );\n }\n }\n\n get _progressiveDataLength() {\n return this._fullRequestReader?._loaded ?? 0;\n }\n\n _onProgress(evt) {\n if (evt.total === undefined) {\n // Reporting to first range reader, if it exists.\n this._rangeReaders[0]?.onProgress?.({ loaded: evt.loaded });\n } else {\n this._fullRequestReader?.onProgress?.({\n loaded: evt.loaded,\n total: evt.total,\n });\n }\n }\n\n _onProgressiveDone() {\n this._fullRequestReader?.progressiveDone();\n this._progressiveDone = true;\n }\n\n _removeRangeReader(reader) {\n const i = this._rangeReaders.indexOf(reader);\n if (i >= 0) {\n this._rangeReaders.splice(i, 1);\n }\n }\n\n getFullReader() {\n assert(\n !this._fullRequestReader,\n \"PDFDataTransportStream.getFullReader can only be called once.\"\n );\n const queuedChunks = this._queuedChunks;\n this._queuedChunks = null;\n return new PDFDataTransportStreamReader(\n this,\n queuedChunks,\n this._progressiveDone,\n this._contentDispositionFilename\n );\n }\n\n getRangeReader(begin, end) {\n if (end <= this._progressiveDataLength) {\n return null;\n }\n const reader = new PDFDataTransportStreamRangeReader(this, begin, end);\n this._pdfDataRangeTransport.requestDataRange(begin, end);\n this._rangeReaders.push(reader);\n return reader;\n }\n\n cancelAllRequests(reason) {\n this._fullRequestReader?.cancel(reason);\n\n for (const reader of this._rangeReaders.slice(0)) {\n reader.cancel(reason);\n }\n this._pdfDataRangeTransport.abort();\n }\n}\n\n/** @implements {IPDFStreamReader} */\nclass PDFDataTransportStreamReader {\n constructor(\n stream,\n queuedChunks,\n progressiveDone = false,\n contentDispositionFilename = null\n ) {\n this._stream = stream;\n this._done = progressiveDone || false;\n this._filename = isPdfFile(contentDispositionFilename)\n ? contentDispositionFilename\n : null;\n this._queuedChunks = queuedChunks || [];\n this._loaded = 0;\n for (const chunk of this._queuedChunks) {\n this._loaded += chunk.byteLength;\n }\n this._requests = [];\n this._headersReady = Promise.resolve();\n stream._fullRequestReader = this;\n\n this.onProgress = null;\n }\n\n _enqueue(chunk) {\n if (this._done) {\n return; // Ignore new data.\n }\n if (this._requests.length > 0) {\n const requestCapability = this._requests.shift();\n requestCapability.resolve({ value: chunk, done: false });\n } else {\n this._queuedChunks.push(chunk);\n }\n this._loaded += chunk.byteLength;\n }\n\n get headersReady() {\n return this._headersReady;\n }\n\n get filename() {\n return this._filename;\n }\n\n get isRangeSupported() {\n return this._stream._isRangeSupported;\n }\n\n get isStreamingSupported() {\n return this._stream._isStreamingSupported;\n }\n\n get contentLength() {\n return this._stream._contentLength;\n }\n\n async read() {\n if (this._queuedChunks.length > 0) {\n const chunk = this._queuedChunks.shift();\n return { value: chunk, done: false };\n }\n if (this._done) {\n return { value: undefined, done: true };\n }\n const requestCapability = Promise.withResolvers();\n this._requests.push(requestCapability);\n return requestCapability.promise;\n }\n\n cancel(reason) {\n this._done = true;\n for (const requestCapability of this._requests) {\n requestCapability.resolve({ value: undefined, done: true });\n }\n this._requests.length = 0;\n }\n\n progressiveDone() {\n if (this._done) {\n return;\n }\n this._done = true;\n }\n}\n\n/** @implements {IPDFStreamRangeReader} */\nclass PDFDataTransportStreamRangeReader {\n constructor(stream, begin, end) {\n this._stream = stream;\n this._begin = begin;\n this._end = end;\n this._queuedChunk = null;\n this._requests = [];\n this._done = false;\n\n this.onProgress = null;\n }\n\n _enqueue(chunk) {\n if (this._done) {\n return; // ignore new data\n }\n if (this._requests.length === 0) {\n this._queuedChunk = chunk;\n } else {\n const requestsCapability = this._requests.shift();\n requestsCapability.resolve({ value: chunk, done: false });\n for (const requestCapability of this._requests) {\n requestCapability.resolve({ value: undefined, done: true });\n }\n this._requests.length = 0;\n }\n this._done = true;\n this._stream._removeRangeReader(this);\n }\n\n get isStreamingSupported() {\n return false;\n }\n\n async read() {\n if (this._queuedChunk) {\n const chunk = this._queuedChunk;\n this._queuedChunk = null;\n return { value: chunk, done: false };\n }\n if (this._done) {\n return { value: undefined, done: true };\n }\n const requestCapability = Promise.withResolvers();\n this._requests.push(requestCapability);\n return requestCapability.promise;\n }\n\n cancel(reason) {\n this._done = true;\n for (const requestCapability of this._requests) {\n requestCapability.resolve({ value: undefined, done: true });\n }\n this._requests.length = 0;\n this._stream._removeRangeReader(this);\n }\n}\n\nexport { PDFDataTransportStream };\n","/* Copyright 2017 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { stringToBytes } from \"../shared/util.js\";\n\n// This getFilenameFromContentDispositionHeader function is adapted from\n// https://github.com/Rob--W/open-in-browser/blob/7e2e35a38b8b4e981b11da7b2f01df0149049e92/extension/content-disposition.js\n// with the following changes:\n// - Modified to conform to PDF.js's coding style.\n// - Move return to the end of the function to prevent Babel from dropping the\n// function declarations.\n\n/**\n * Extract file name from the Content-Disposition HTTP response header.\n *\n * @param {string} contentDisposition\n * @returns {string} Filename, if found in the Content-Disposition header.\n */\nfunction getFilenameFromContentDispositionHeader(contentDisposition) {\n let needsEncodingFixup = true;\n\n // filename*=ext-value (\"ext-value\" from RFC 5987, referenced by RFC 6266).\n let tmp = toParamRegExp(\"filename\\\\*\", \"i\").exec(contentDisposition);\n if (tmp) {\n tmp = tmp[1];\n let filename = rfc2616unquote(tmp);\n filename = unescape(filename);\n filename = rfc5987decode(filename);\n filename = rfc2047decode(filename);\n return fixupEncoding(filename);\n }\n\n // Continuations (RFC 2231 section 3, referenced by RFC 5987 section 3.1).\n // filename*n*=part\n // filename*n=part\n tmp = rfc2231getparam(contentDisposition);\n if (tmp) {\n // RFC 2047, section\n const filename = rfc2047decode(tmp);\n return fixupEncoding(filename);\n }\n\n // filename=value (RFC 5987, section 4.1).\n tmp = toParamRegExp(\"filename\", \"i\").exec(contentDisposition);\n if (tmp) {\n tmp = tmp[1];\n let filename = rfc2616unquote(tmp);\n filename = rfc2047decode(filename);\n return fixupEncoding(filename);\n }\n\n // After this line there are only function declarations. We cannot put\n // \"return\" here for readability because babel would then drop the function\n // declarations...\n function toParamRegExp(attributePattern, flags) {\n return new RegExp(\n \"(?:^|;)\\\\s*\" +\n attributePattern +\n \"\\\\s*=\\\\s*\" +\n // Captures: value = token | quoted-string\n // (RFC 2616, section 3.6 and referenced by RFC 6266 4.1)\n \"(\" +\n '[^\";\\\\s][^;\\\\s]*' +\n \"|\" +\n '\"(?:[^\"\\\\\\\\]|\\\\\\\\\"?)+\"?' +\n \")\",\n flags\n );\n }\n function textdecode(encoding, value) {\n if (encoding) {\n if (!/^[\\x00-\\xFF]+$/.test(value)) {\n return value;\n }\n try {\n const decoder = new TextDecoder(encoding, { fatal: true });\n const buffer = stringToBytes(value);\n value = decoder.decode(buffer);\n needsEncodingFixup = false;\n } catch {\n // TextDecoder constructor threw - unrecognized encoding.\n }\n }\n return value;\n }\n function fixupEncoding(value) {\n if (needsEncodingFixup && /[\\x80-\\xff]/.test(value)) {\n // Maybe multi-byte UTF-8.\n value = textdecode(\"utf-8\", value);\n if (needsEncodingFixup) {\n // Try iso-8859-1 encoding.\n value = textdecode(\"iso-8859-1\", value);\n }\n }\n return value;\n }\n function rfc2231getparam(contentDispositionStr) {\n const matches = [];\n let match;\n // Iterate over all filename*n= and filename*n*= with n being an integer\n // of at least zero. Any non-zero number must not start with '0'.\n const iter = toParamRegExp(\"filename\\\\*((?!0\\\\d)\\\\d+)(\\\\*?)\", \"ig\");\n while ((match = iter.exec(contentDispositionStr)) !== null) {\n let [, n, quot, part] = match; // eslint-disable-line prefer-const\n n = parseInt(n, 10);\n if (n in matches) {\n // Ignore anything after the invalid second filename*0.\n if (n === 0) {\n break;\n }\n continue;\n }\n matches[n] = [quot, part];\n }\n const parts = [];\n for (let n = 0; n < matches.length; ++n) {\n if (!(n in matches)) {\n // Numbers must be consecutive. Truncate when there is a hole.\n break;\n }\n let [quot, part] = matches[n]; // eslint-disable-line prefer-const\n part = rfc2616unquote(part);\n if (quot) {\n part = unescape(part);\n if (n === 0) {\n part = rfc5987decode(part);\n }\n }\n parts.push(part);\n }\n return parts.join(\"\");\n }\n function rfc2616unquote(value) {\n if (value.startsWith('\"')) {\n const parts = value.slice(1).split('\\\\\"');\n // Find the first unescaped \" and terminate there.\n for (let i = 0; i < parts.length; ++i) {\n const quotindex = parts[i].indexOf('\"');\n if (quotindex !== -1) {\n parts[i] = parts[i].slice(0, quotindex);\n parts.length = i + 1; // Truncates and stop the iteration.\n }\n parts[i] = parts[i].replaceAll(/\\\\(.)/g, \"$1\");\n }\n value = parts.join('\"');\n }\n return value;\n }\n function rfc5987decode(extvalue) {\n // Decodes \"ext-value\" from RFC 5987.\n const encodingend = extvalue.indexOf(\"'\");\n if (encodingend === -1) {\n // Some servers send \"filename*=\" without encoding 'language' prefix,\n // e.g. in https://github.com/Rob--W/open-in-browser/issues/26\n // Let's accept the value like Firefox (57) (Chrome 62 rejects it).\n return extvalue;\n }\n const encoding = extvalue.slice(0, encodingend);\n const langvalue = extvalue.slice(encodingend + 1);\n // Ignore language (RFC 5987 section 3.2.1, and RFC 6266 section 4.1 ).\n const value = langvalue.replace(/^[^']*'/, \"\");\n return textdecode(encoding, value);\n }\n function rfc2047decode(value) {\n // RFC 2047-decode the result. Firefox tried to drop support for it, but\n // backed out because some servers use it - https://bugzil.la/875615\n // Firefox's condition for decoding is here: https://searchfox.org/mozilla-central/rev/4a590a5a15e35d88a3b23dd6ac3c471cf85b04a8/netwerk/mime/nsMIMEHeaderParamImpl.cpp#742-748\n\n // We are more strict and only recognize RFC 2047-encoding if the value\n // starts with \"=?\", since then it is likely that the full value is\n // RFC 2047-encoded.\n\n // Firefox also decodes words even where RFC 2047 section 5 states:\n // \"An 'encoded-word' MUST NOT appear within a 'quoted-string'.\"\n if (!value.startsWith(\"=?\") || /[\\x00-\\x19\\x80-\\xff]/.test(value)) {\n return value;\n }\n // RFC 2047, section 2.4\n // encoded-word = \"=?\" charset \"?\" encoding \"?\" encoded-text \"?=\"\n // charset = token (but let's restrict to characters that denote a\n // possibly valid encoding).\n // encoding = q or b\n // encoded-text = any printable ASCII character other than ? or space.\n // ... but Firefox permits ? and space.\n return value.replaceAll(\n /=\\?([\\w-]*)\\?([QqBb])\\?((?:[^?]|\\?(?!=))*)\\?=/g,\n function (matches, charset, encoding, text) {\n if (encoding === \"q\" || encoding === \"Q\") {\n // RFC 2047 section 4.2.\n text = text.replaceAll(\"_\", \" \");\n text = text.replaceAll(/=([0-9a-fA-F]{2})/g, function (match, hex) {\n return String.fromCharCode(parseInt(hex, 16));\n });\n return textdecode(charset, text);\n } // else encoding is b or B - base64 (RFC 2047 section 4.1)\n try {\n text = atob(text);\n } catch {}\n return textdecode(charset, text);\n }\n );\n }\n\n return \"\";\n}\n\nexport { getFilenameFromContentDispositionHeader };\n","/* Copyright 2012 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n assert,\n MissingPDFException,\n UnexpectedResponseException,\n} from \"../shared/util.js\";\nimport { getFilenameFromContentDispositionHeader } from \"./content_disposition.js\";\nimport { isPdfFile } from \"./display_utils.js\";\n\nfunction validateRangeRequestCapabilities({\n getResponseHeader,\n isHttp,\n rangeChunkSize,\n disableRange,\n}) {\n if (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) {\n assert(\n Number.isInteger(rangeChunkSize) && rangeChunkSize > 0,\n \"rangeChunkSize must be an integer larger than zero.\"\n );\n }\n const returnValues = {\n allowRangeRequests: false,\n suggestedLength: undefined,\n };\n\n const length = parseInt(getResponseHeader(\"Content-Length\"), 10);\n if (!Number.isInteger(length)) {\n return returnValues;\n }\n\n returnValues.suggestedLength = length;\n\n if (length <= 2 * rangeChunkSize) {\n // The file size is smaller than the size of two chunks, so it does not\n // make any sense to abort the request and retry with a range request.\n return returnValues;\n }\n\n if (disableRange || !isHttp) {\n return returnValues;\n }\n if (getResponseHeader(\"Accept-Ranges\") !== \"bytes\") {\n return returnValues;\n }\n\n const contentEncoding = getResponseHeader(\"Content-Encoding\") || \"identity\";\n if (contentEncoding !== \"identity\") {\n return returnValues;\n }\n\n returnValues.allowRangeRequests = true;\n return returnValues;\n}\n\nfunction extractFilenameFromHeader(getResponseHeader) {\n const contentDisposition = getResponseHeader(\"Content-Disposition\");\n if (contentDisposition) {\n let filename = getFilenameFromContentDispositionHeader(contentDisposition);\n if (filename.includes(\"%\")) {\n try {\n filename = decodeURIComponent(filename);\n } catch {}\n }\n if (isPdfFile(filename)) {\n return filename;\n }\n }\n return null;\n}\n\nfunction createResponseStatusError(status, url) {\n if (status === 404 || (status === 0 && url.startsWith(\"file:\"))) {\n return new MissingPDFException('Missing PDF \"' + url + '\".');\n }\n return new UnexpectedResponseException(\n `Unexpected server response (${status}) while retrieving PDF \"${url}\".`,\n status\n );\n}\n\nfunction validateResponseStatus(status) {\n return status === 200 || status === 206;\n}\n\nexport {\n createResponseStatusError,\n extractFilenameFromHeader,\n validateRangeRequestCapabilities,\n validateResponseStatus,\n};\n","/* Copyright 2012 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AbortException, assert, warn } from \"../shared/util.js\";\nimport {\n createResponseStatusError,\n extractFilenameFromHeader,\n validateRangeRequestCapabilities,\n validateResponseStatus,\n} from \"./network_utils.js\";\n\nif (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n throw new Error(\n 'Module \"./fetch_stream.js\" shall not be used with MOZCENTRAL builds.'\n );\n}\n\nfunction createFetchOptions(headers, withCredentials, abortController) {\n return {\n method: \"GET\",\n headers,\n signal: abortController.signal,\n mode: \"cors\",\n credentials: withCredentials ? \"include\" : \"same-origin\",\n redirect: \"follow\",\n };\n}\n\nfunction createHeaders(httpHeaders) {\n const headers = new Headers();\n for (const property in httpHeaders) {\n const value = httpHeaders[property];\n if (value === undefined) {\n continue;\n }\n headers.append(property, value);\n }\n return headers;\n}\n\nfunction getArrayBuffer(val) {\n if (val instanceof Uint8Array) {\n return val.buffer;\n }\n if (val instanceof ArrayBuffer) {\n return val;\n }\n warn(`getArrayBuffer - unexpected data format: ${val}`);\n return new Uint8Array(val).buffer;\n}\n\n/** @implements {IPDFStream} */\nclass PDFFetchStream {\n constructor(source) {\n this.source = source;\n this.isHttp = /^https?:/i.test(source.url);\n this.httpHeaders = (this.isHttp && source.httpHeaders) || {};\n\n this._fullRequestReader = null;\n this._rangeRequestReaders = [];\n }\n\n get _progressiveDataLength() {\n return this._fullRequestReader?._loaded ?? 0;\n }\n\n getFullReader() {\n assert(\n !this._fullRequestReader,\n \"PDFFetchStream.getFullReader can only be called once.\"\n );\n this._fullRequestReader = new PDFFetchStreamReader(this);\n return this._fullRequestReader;\n }\n\n getRangeReader(begin, end) {\n if (end <= this._progressiveDataLength) {\n return null;\n }\n const reader = new PDFFetchStreamRangeReader(this, begin, end);\n this._rangeRequestReaders.push(reader);\n return reader;\n }\n\n cancelAllRequests(reason) {\n this._fullRequestReader?.cancel(reason);\n\n for (const reader of this._rangeRequestReaders.slice(0)) {\n reader.cancel(reason);\n }\n }\n}\n\n/** @implements {IPDFStreamReader} */\nclass PDFFetchStreamReader {\n constructor(stream) {\n this._stream = stream;\n this._reader = null;\n this._loaded = 0;\n this._filename = null;\n const source = stream.source;\n this._withCredentials = source.withCredentials || false;\n this._contentLength = source.length;\n this._headersCapability = Promise.withResolvers();\n this._disableRange = source.disableRange || false;\n this._rangeChunkSize = source.rangeChunkSize;\n if (!this._rangeChunkSize && !this._disableRange) {\n this._disableRange = true;\n }\n\n this._abortController = new AbortController();\n this._isStreamingSupported = !source.disableStream;\n this._isRangeSupported = !source.disableRange;\n\n this._headers = createHeaders(this._stream.httpHeaders);\n\n const url = source.url;\n fetch(\n url,\n createFetchOptions(\n this._headers,\n this._withCredentials,\n this._abortController\n )\n )\n .then(response => {\n if (!validateResponseStatus(response.status)) {\n throw createResponseStatusError(response.status, url);\n }\n this._reader = response.body.getReader();\n this._headersCapability.resolve();\n\n const getResponseHeader = name => response.headers.get(name);\n\n const { allowRangeRequests, suggestedLength } =\n validateRangeRequestCapabilities({\n getResponseHeader,\n isHttp: this._stream.isHttp,\n rangeChunkSize: this._rangeChunkSize,\n disableRange: this._disableRange,\n });\n\n this._isRangeSupported = allowRangeRequests;\n // Setting right content length.\n this._contentLength = suggestedLength || this._contentLength;\n\n this._filename = extractFilenameFromHeader(getResponseHeader);\n\n // We need to stop reading when range is supported and streaming is\n // disabled.\n if (!this._isStreamingSupported && this._isRangeSupported) {\n this.cancel(new AbortException(\"Streaming is disabled.\"));\n }\n })\n .catch(this._headersCapability.reject);\n\n this.onProgress = null;\n }\n\n get headersReady() {\n return this._headersCapability.promise;\n }\n\n get filename() {\n return this._filename;\n }\n\n get contentLength() {\n return this._contentLength;\n }\n\n get isRangeSupported() {\n return this._isRangeSupported;\n }\n\n get isStreamingSupported() {\n return this._isStreamingSupported;\n }\n\n async read() {\n await this._headersCapability.promise;\n const { value, done } = await this._reader.read();\n if (done) {\n return { value, done };\n }\n this._loaded += value.byteLength;\n this.onProgress?.({\n loaded: this._loaded,\n total: this._contentLength,\n });\n\n return { value: getArrayBuffer(value), done: false };\n }\n\n cancel(reason) {\n this._reader?.cancel(reason);\n this._abortController.abort();\n }\n}\n\n/** @implements {IPDFStreamRangeReader} */\nclass PDFFetchStreamRangeReader {\n constructor(stream, begin, end) {\n this._stream = stream;\n this._reader = null;\n this._loaded = 0;\n const source = stream.source;\n this._withCredentials = source.withCredentials || false;\n this._readCapability = Promise.withResolvers();\n this._isStreamingSupported = !source.disableStream;\n\n this._abortController = new AbortController();\n this._headers = createHeaders(this._stream.httpHeaders);\n this._headers.append(\"Range\", `bytes=${begin}-${end - 1}`);\n\n const url = source.url;\n fetch(\n url,\n createFetchOptions(\n this._headers,\n this._withCredentials,\n this._abortController\n )\n )\n .then(response => {\n if (!validateResponseStatus(response.status)) {\n throw createResponseStatusError(response.status, url);\n }\n this._readCapability.resolve();\n this._reader = response.body.getReader();\n })\n .catch(this._readCapability.reject);\n\n this.onProgress = null;\n }\n\n get isStreamingSupported() {\n return this._isStreamingSupported;\n }\n\n async read() {\n await this._readCapability.promise;\n const { value, done } = await this._reader.read();\n if (done) {\n return { value, done };\n }\n this._loaded += value.byteLength;\n this.onProgress?.({ loaded: this._loaded });\n\n return { value: getArrayBuffer(value), done: false };\n }\n\n cancel(reason) {\n this._reader?.cancel(reason);\n this._abortController.abort();\n }\n}\n\nexport { PDFFetchStream };\n","/* Copyright 2012 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, stringToBytes } from \"../shared/util.js\";\nimport {\n createResponseStatusError,\n extractFilenameFromHeader,\n validateRangeRequestCapabilities,\n} from \"./network_utils.js\";\n\nif (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n throw new Error(\n 'Module \"./network.js\" shall not be used with MOZCENTRAL builds.'\n );\n}\n\nconst OK_RESPONSE = 200;\nconst PARTIAL_CONTENT_RESPONSE = 206;\n\nfunction getArrayBuffer(xhr) {\n const data = xhr.response;\n if (typeof data !== \"string\") {\n return data;\n }\n return stringToBytes(data).buffer;\n}\n\nclass NetworkManager {\n constructor(url, args = {}) {\n this.url = url;\n this.isHttp = /^https?:/i.test(url);\n this.httpHeaders = (this.isHttp && args.httpHeaders) || Object.create(null);\n this.withCredentials = args.withCredentials || false;\n\n this.currXhrId = 0;\n this.pendingRequests = Object.create(null);\n }\n\n requestRange(begin, end, listeners) {\n const args = {\n begin,\n end,\n };\n for (const prop in listeners) {\n args[prop] = listeners[prop];\n }\n return this.request(args);\n }\n\n requestFull(listeners) {\n return this.request(listeners);\n }\n\n request(args) {\n const xhr = new XMLHttpRequest();\n const xhrId = this.currXhrId++;\n const pendingRequest = (this.pendingRequests[xhrId] = { xhr });\n\n xhr.open(\"GET\", this.url);\n xhr.withCredentials = this.withCredentials;\n for (const property in this.httpHeaders) {\n const value = this.httpHeaders[property];\n if (value === undefined) {\n continue;\n }\n xhr.setRequestHeader(property, value);\n }\n if (this.isHttp && \"begin\" in args && \"end\" in args) {\n xhr.setRequestHeader(\"Range\", `bytes=${args.begin}-${args.end - 1}`);\n pendingRequest.expectedStatus = PARTIAL_CONTENT_RESPONSE;\n } else {\n pendingRequest.expectedStatus = OK_RESPONSE;\n }\n xhr.responseType = \"arraybuffer\";\n\n if (args.onError) {\n xhr.onerror = function (evt) {\n args.onError(xhr.status);\n };\n }\n xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);\n xhr.onprogress = this.onProgress.bind(this, xhrId);\n\n pendingRequest.onHeadersReceived = args.onHeadersReceived;\n pendingRequest.onDone = args.onDone;\n pendingRequest.onError = args.onError;\n pendingRequest.onProgress = args.onProgress;\n\n xhr.send(null);\n\n return xhrId;\n }\n\n onProgress(xhrId, evt) {\n const pendingRequest = this.pendingRequests[xhrId];\n if (!pendingRequest) {\n return; // Maybe abortRequest was called...\n }\n pendingRequest.onProgress?.(evt);\n }\n\n onStateChange(xhrId, evt) {\n const pendingRequest = this.pendingRequests[xhrId];\n if (!pendingRequest) {\n return; // Maybe abortRequest was called...\n }\n\n const xhr = pendingRequest.xhr;\n if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {\n pendingRequest.onHeadersReceived();\n delete pendingRequest.onHeadersReceived;\n }\n\n if (xhr.readyState !== 4) {\n return;\n }\n\n if (!(xhrId in this.pendingRequests)) {\n // The XHR request might have been aborted in onHeadersReceived()\n // callback, in which case we should abort request.\n return;\n }\n\n delete this.pendingRequests[xhrId];\n\n // Success status == 0 can be on ftp, file and other protocols.\n if (xhr.status === 0 && this.isHttp) {\n pendingRequest.onError?.(xhr.status);\n return;\n }\n const xhrStatus = xhr.status || OK_RESPONSE;\n\n // From http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35.2:\n // \"A server MAY ignore the Range header\". This means it's possible to\n // get a 200 rather than a 206 response from a range request.\n const ok_response_on_range_request =\n xhrStatus === OK_RESPONSE &&\n pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;\n\n if (\n !ok_response_on_range_request &&\n xhrStatus !== pendingRequest.expectedStatus\n ) {\n pendingRequest.onError?.(xhr.status);\n return;\n }\n\n const chunk = getArrayBuffer(xhr);\n if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {\n const rangeHeader = xhr.getResponseHeader(\"Content-Range\");\n const matches = /bytes (\\d+)-(\\d+)\\/(\\d+)/.exec(rangeHeader);\n pendingRequest.onDone({\n begin: parseInt(matches[1], 10),\n chunk,\n });\n } else if (chunk) {\n pendingRequest.onDone({\n begin: 0,\n chunk,\n });\n } else {\n pendingRequest.onError?.(xhr.status);\n }\n }\n\n getRequestXhr(xhrId) {\n return this.pendingRequests[xhrId].xhr;\n }\n\n isPendingRequest(xhrId) {\n return xhrId in this.pendingRequests;\n }\n\n abortRequest(xhrId) {\n const xhr = this.pendingRequests[xhrId].xhr;\n delete this.pendingRequests[xhrId];\n xhr.abort();\n }\n}\n\n/** @implements {IPDFStream} */\nclass PDFNetworkStream {\n constructor(source) {\n this._source = source;\n this._manager = new NetworkManager(source.url, {\n httpHeaders: source.httpHeaders,\n withCredentials: source.withCredentials,\n });\n this._rangeChunkSize = source.rangeChunkSize;\n this._fullRequestReader = null;\n this._rangeRequestReaders = [];\n }\n\n _onRangeRequestReaderClosed(reader) {\n const i = this._rangeRequestReaders.indexOf(reader);\n if (i >= 0) {\n this._rangeRequestReaders.splice(i, 1);\n }\n }\n\n getFullReader() {\n assert(\n !this._fullRequestReader,\n \"PDFNetworkStream.getFullReader can only be called once.\"\n );\n this._fullRequestReader = new PDFNetworkStreamFullRequestReader(\n this._manager,\n this._source\n );\n return this._fullRequestReader;\n }\n\n getRangeReader(begin, end) {\n const reader = new PDFNetworkStreamRangeRequestReader(\n this._manager,\n begin,\n end\n );\n reader.onClosed = this._onRangeRequestReaderClosed.bind(this);\n this._rangeRequestReaders.push(reader);\n return reader;\n }\n\n cancelAllRequests(reason) {\n this._fullRequestReader?.cancel(reason);\n\n for (const reader of this._rangeRequestReaders.slice(0)) {\n reader.cancel(reason);\n }\n }\n}\n\n/** @implements {IPDFStreamReader} */\nclass PDFNetworkStreamFullRequestReader {\n constructor(manager, source) {\n this._manager = manager;\n\n const args = {\n onHeadersReceived: this._onHeadersReceived.bind(this),\n onDone: this._onDone.bind(this),\n onError: this._onError.bind(this),\n onProgress: this._onProgress.bind(this),\n };\n this._url = source.url;\n this._fullRequestId = manager.requestFull(args);\n this._headersReceivedCapability = Promise.withResolvers();\n this._disableRange = source.disableRange || false;\n this._contentLength = source.length; // Optional\n this._rangeChunkSize = source.rangeChunkSize;\n if (!this._rangeChunkSize && !this._disableRange) {\n this._disableRange = true;\n }\n\n this._isStreamingSupported = false;\n this._isRangeSupported = false;\n\n this._cachedChunks = [];\n this._requests = [];\n this._done = false;\n this._storedError = undefined;\n this._filename = null;\n\n this.onProgress = null;\n }\n\n _onHeadersReceived() {\n const fullRequestXhrId = this._fullRequestId;\n const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId);\n\n const getResponseHeader = name => fullRequestXhr.getResponseHeader(name);\n\n const { allowRangeRequests, suggestedLength } =\n validateRangeRequestCapabilities({\n getResponseHeader,\n isHttp: this._manager.isHttp,\n rangeChunkSize: this._rangeChunkSize,\n disableRange: this._disableRange,\n });\n\n if (allowRangeRequests) {\n this._isRangeSupported = true;\n }\n // Setting right content length.\n this._contentLength = suggestedLength || this._contentLength;\n\n this._filename = extractFilenameFromHeader(getResponseHeader);\n\n if (this._isRangeSupported) {\n // NOTE: by cancelling the full request, and then issuing range\n // requests, there will be an issue for sites where you can only\n // request the pdf once. However, if this is the case, then the\n // server should not be returning that it can support range requests.\n this._manager.abortRequest(fullRequestXhrId);\n }\n\n this._headersReceivedCapability.resolve();\n }\n\n _onDone(data) {\n if (data) {\n if (this._requests.length > 0) {\n const requestCapability = this._requests.shift();\n requestCapability.resolve({ value: data.chunk, done: false });\n } else {\n this._cachedChunks.push(data.chunk);\n }\n }\n this._done = true;\n if (this._cachedChunks.length > 0) {\n return;\n }\n for (const requestCapability of this._requests) {\n requestCapability.resolve({ value: undefined, done: true });\n }\n this._requests.length = 0;\n }\n\n _onError(status) {\n this._storedError = createResponseStatusError(status, this._url);\n this._headersReceivedCapability.reject(this._storedError);\n for (const requestCapability of this._requests) {\n requestCapability.reject(this._storedError);\n }\n this._requests.length = 0;\n this._cachedChunks.length = 0;\n }\n\n _onProgress(evt) {\n this.onProgress?.({\n loaded: evt.loaded,\n total: evt.lengthComputable ? evt.total : this._contentLength,\n });\n }\n\n get filename() {\n return this._filename;\n }\n\n get isRangeSupported() {\n return this._isRangeSupported;\n }\n\n get isStreamingSupported() {\n return this._isStreamingSupported;\n }\n\n get contentLength() {\n return this._contentLength;\n }\n\n get headersReady() {\n return this._headersReceivedCapability.promise;\n }\n\n async read() {\n if (this._storedError) {\n throw this._storedError;\n }\n if (this._cachedChunks.length > 0) {\n const chunk = this._cachedChunks.shift();\n return { value: chunk, done: false };\n }\n if (this._done) {\n return { value: undefined, done: true };\n }\n const requestCapability = Promise.withResolvers();\n this._requests.push(requestCapability);\n return requestCapability.promise;\n }\n\n cancel(reason) {\n this._done = true;\n this._headersReceivedCapability.reject(reason);\n for (const requestCapability of this._requests) {\n requestCapability.resolve({ value: undefined, done: true });\n }\n this._requests.length = 0;\n if (this._manager.isPendingRequest(this._fullRequestId)) {\n this._manager.abortRequest(this._fullRequestId);\n }\n this._fullRequestReader = null;\n }\n}\n\n/** @implements {IPDFStreamRangeReader} */\nclass PDFNetworkStreamRangeRequestReader {\n constructor(manager, begin, end) {\n this._manager = manager;\n\n const args = {\n onDone: this._onDone.bind(this),\n onError: this._onError.bind(this),\n onProgress: this._onProgress.bind(this),\n };\n this._url = manager.url;\n this._requestId = manager.requestRange(begin, end, args);\n this._requests = [];\n this._queuedChunk = null;\n this._done = false;\n this._storedError = undefined;\n\n this.onProgress = null;\n this.onClosed = null;\n }\n\n _close() {\n this.onClosed?.(this);\n }\n\n _onDone(data) {\n const chunk = data.chunk;\n if (this._requests.length > 0) {\n const requestCapability = this._requests.shift();\n requestCapability.resolve({ value: chunk, done: false });\n } else {\n this._queuedChunk = chunk;\n }\n this._done = true;\n for (const requestCapability of this._requests) {\n requestCapability.resolve({ value: undefined, done: true });\n }\n this._requests.length = 0;\n this._close();\n }\n\n _onError(status) {\n this._storedError = createResponseStatusError(status, this._url);\n for (const requestCapability of this._requests) {\n requestCapability.reject(this._storedError);\n }\n this._requests.length = 0;\n this._queuedChunk = null;\n }\n\n _onProgress(evt) {\n if (!this.isStreamingSupported) {\n this.onProgress?.({ loaded: evt.loaded });\n }\n }\n\n get isStreamingSupported() {\n return false;\n }\n\n async read() {\n if (this._storedError) {\n throw this._storedError;\n }\n if (this._queuedChunk !== null) {\n const chunk = this._queuedChunk;\n this._queuedChunk = null;\n return { value: chunk, done: false };\n }\n if (this._done) {\n return { value: undefined, done: true };\n }\n const requestCapability = Promise.withResolvers();\n this._requests.push(requestCapability);\n return requestCapability.promise;\n }\n\n cancel(reason) {\n this._done = true;\n for (const requestCapability of this._requests) {\n requestCapability.resolve({ value: undefined, done: true });\n }\n this._requests.length = 0;\n if (this._manager.isPendingRequest(this._requestId)) {\n this._manager.abortRequest(this._requestId);\n }\n this._close();\n }\n}\n\nexport { PDFNetworkStream };\n","/* Copyright 2012 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AbortException, assert, MissingPDFException } from \"../shared/util.js\";\nimport {\n extractFilenameFromHeader,\n validateRangeRequestCapabilities,\n} from \"./network_utils.js\";\nimport { NodePackages } from \"./node_utils.js\";\n\nif (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n throw new Error(\n 'Module \"./node_stream.js\" shall not be used with MOZCENTRAL builds.'\n );\n}\n\nconst urlRegex = /^[a-z][a-z0-9\\-+.]+:/i;\n\nfunction parseUrlOrPath(sourceUrl) {\n if (urlRegex.test(sourceUrl)) {\n return new URL(sourceUrl);\n }\n const url = NodePackages.get(\"url\");\n return new URL(url.pathToFileURL(sourceUrl));\n}\n\nfunction createRequest(url, headers, callback) {\n if (url.protocol === \"http:\") {\n const http = NodePackages.get(\"http\");\n return http.request(url, { headers }, callback);\n }\n const https = NodePackages.get(\"https\");\n return https.request(url, { headers }, callback);\n}\n\nclass PDFNodeStream {\n constructor(source) {\n this.source = source;\n this.url = parseUrlOrPath(source.url);\n this.isHttp =\n this.url.protocol === \"http:\" || this.url.protocol === \"https:\";\n // Check if url refers to filesystem.\n this.isFsUrl = this.url.protocol === \"file:\";\n this.httpHeaders = (this.isHttp && source.httpHeaders) || {};\n\n this._fullRequestReader = null;\n this._rangeRequestReaders = [];\n }\n\n get _progressiveDataLength() {\n return this._fullRequestReader?._loaded ?? 0;\n }\n\n getFullReader() {\n assert(\n !this._fullRequestReader,\n \"PDFNodeStream.getFullReader can only be called once.\"\n );\n this._fullRequestReader = this.isFsUrl\n ? new PDFNodeStreamFsFullReader(this)\n : new PDFNodeStreamFullReader(this);\n return this._fullRequestReader;\n }\n\n getRangeReader(start, end) {\n if (end <= this._progressiveDataLength) {\n return null;\n }\n const rangeReader = this.isFsUrl\n ? new PDFNodeStreamFsRangeReader(this, start, end)\n : new PDFNodeStreamRangeReader(this, start, end);\n this._rangeRequestReaders.push(rangeReader);\n return rangeReader;\n }\n\n cancelAllRequests(reason) {\n this._fullRequestReader?.cancel(reason);\n\n for (const reader of this._rangeRequestReaders.slice(0)) {\n reader.cancel(reason);\n }\n }\n}\n\nclass BaseFullReader {\n constructor(stream) {\n this._url = stream.url;\n this._done = false;\n this._storedError = null;\n this.onProgress = null;\n const source = stream.source;\n this._contentLength = source.length; // optional\n this._loaded = 0;\n this._filename = null;\n\n this._disableRange = source.disableRange || false;\n this._rangeChunkSize = source.rangeChunkSize;\n if (!this._rangeChunkSize && !this._disableRange) {\n this._disableRange = true;\n }\n\n this._isStreamingSupported = !source.disableStream;\n this._isRangeSupported = !source.disableRange;\n\n this._readableStream = null;\n this._readCapability = Promise.withResolvers();\n this._headersCapability = Promise.withResolvers();\n }\n\n get headersReady() {\n return this._headersCapability.promise;\n }\n\n get filename() {\n return this._filename;\n }\n\n get contentLength() {\n return this._contentLength;\n }\n\n get isRangeSupported() {\n return this._isRangeSupported;\n }\n\n get isStreamingSupported() {\n return this._isStreamingSupported;\n }\n\n async read() {\n await this._readCapability.promise;\n if (this._done) {\n return { value: undefined, done: true };\n }\n if (this._storedError) {\n throw this._storedError;\n }\n\n const chunk = this._readableStream.read();\n if (chunk === null) {\n this._readCapability = Promise.withResolvers();\n return this.read();\n }\n this._loaded += chunk.length;\n this.onProgress?.({\n loaded: this._loaded,\n total: this._contentLength,\n });\n\n // Ensure that `read()` method returns ArrayBuffer.\n const buffer = new Uint8Array(chunk).buffer;\n return { value: buffer, done: false };\n }\n\n cancel(reason) {\n // Call `this._error()` method when cancel is called\n // before _readableStream is set.\n if (!this._readableStream) {\n this._error(reason);\n return;\n }\n this._readableStream.destroy(reason);\n }\n\n _error(reason) {\n this._storedError = reason;\n this._readCapability.resolve();\n }\n\n _setReadableStream(readableStream) {\n this._readableStream = readableStream;\n readableStream.on(\"readable\", () => {\n this._readCapability.resolve();\n });\n\n readableStream.on(\"end\", () => {\n // Destroy readable to minimize resource usage.\n readableStream.destroy();\n this._done = true;\n this._readCapability.resolve();\n });\n\n readableStream.on(\"error\", reason => {\n this._error(reason);\n });\n\n // We need to stop reading when range is supported and streaming is\n // disabled.\n if (!this._isStreamingSupported && this._isRangeSupported) {\n this._error(new AbortException(\"streaming is disabled\"));\n }\n\n // Destroy ReadableStream if already in errored state.\n if (this._storedError) {\n this._readableStream.destroy(this._storedError);\n }\n }\n}\n\nclass BaseRangeReader {\n constructor(stream) {\n this._url = stream.url;\n this._done = false;\n this._storedError = null;\n this.onProgress = null;\n this._loaded = 0;\n this._readableStream = null;\n this._readCapability = Promise.withResolvers();\n const source = stream.source;\n this._isStreamingSupported = !source.disableStream;\n }\n\n get isStreamingSupported() {\n return this._isStreamingSupported;\n }\n\n async read() {\n await this._readCapability.promise;\n if (this._done) {\n return { value: undefined, done: true };\n }\n if (this._storedError) {\n throw this._storedError;\n }\n\n const chunk = this._readableStream.read();\n if (chunk === null) {\n this._readCapability = Promise.withResolvers();\n return this.read();\n }\n this._loaded += chunk.length;\n this.onProgress?.({ loaded: this._loaded });\n\n // Ensure that `read()` method returns ArrayBuffer.\n const buffer = new Uint8Array(chunk).buffer;\n return { value: buffer, done: false };\n }\n\n cancel(reason) {\n // Call `this._error()` method when cancel is called\n // before _readableStream is set.\n if (!this._readableStream) {\n this._error(reason);\n return;\n }\n this._readableStream.destroy(reason);\n }\n\n _error(reason) {\n this._storedError = reason;\n this._readCapability.resolve();\n }\n\n _setReadableStream(readableStream) {\n this._readableStream = readableStream;\n readableStream.on(\"readable\", () => {\n this._readCapability.resolve();\n });\n\n readableStream.on(\"end\", () => {\n // Destroy readableStream to minimize resource usage.\n readableStream.destroy();\n this._done = true;\n this._readCapability.resolve();\n });\n\n readableStream.on(\"error\", reason => {\n this._error(reason);\n });\n\n // Destroy readableStream if already in errored state.\n if (this._storedError) {\n this._readableStream.destroy(this._storedError);\n }\n }\n}\n\nclass PDFNodeStreamFullReader extends BaseFullReader {\n constructor(stream) {\n super(stream);\n\n const handleResponse = response => {\n if (response.statusCode === 404) {\n const error = new MissingPDFException(`Missing PDF \"${this._url}\".`);\n this._storedError = error;\n this._headersCapability.reject(error);\n return;\n }\n this._headersCapability.resolve();\n this._setReadableStream(response);\n\n // Make sure that headers name are in lower case, as mentioned\n // here: https://nodejs.org/api/http.html#http_message_headers.\n const getResponseHeader = name =>\n this._readableStream.headers[name.toLowerCase()];\n\n const { allowRangeRequests, suggestedLength } =\n validateRangeRequestCapabilities({\n getResponseHeader,\n isHttp: stream.isHttp,\n rangeChunkSize: this._rangeChunkSize,\n disableRange: this._disableRange,\n });\n\n this._isRangeSupported = allowRangeRequests;\n // Setting right content length.\n this._contentLength = suggestedLength || this._contentLength;\n\n this._filename = extractFilenameFromHeader(getResponseHeader);\n };\n\n this._request = createRequest(\n this._url,\n stream.httpHeaders,\n handleResponse\n );\n\n this._request.on(\"error\", reason => {\n this._storedError = reason;\n this._headersCapability.reject(reason);\n });\n // Note: `request.end(data)` is used to write `data` to request body\n // and notify end of request. But one should always call `request.end()`\n // even if there is no data to write -- (to notify the end of request).\n this._request.end();\n }\n}\n\nclass PDFNodeStreamRangeReader extends BaseRangeReader {\n constructor(stream, start, end) {\n super(stream);\n\n this._httpHeaders = {};\n for (const property in stream.httpHeaders) {\n const value = stream.httpHeaders[property];\n if (value === undefined) {\n continue;\n }\n this._httpHeaders[property] = value;\n }\n this._httpHeaders.Range = `bytes=${start}-${end - 1}`;\n\n const handleResponse = response => {\n if (response.statusCode === 404) {\n const error = new MissingPDFException(`Missing PDF \"${this._url}\".`);\n this._storedError = error;\n return;\n }\n this._setReadableStream(response);\n };\n\n this._request = createRequest(this._url, this._httpHeaders, handleResponse);\n\n this._request.on(\"error\", reason => {\n this._storedError = reason;\n });\n this._request.end();\n }\n}\n\nclass PDFNodeStreamFsFullReader extends BaseFullReader {\n constructor(stream) {\n super(stream);\n\n const fs = NodePackages.get(\"fs\");\n fs.promises.lstat(this._url).then(\n stat => {\n // Setting right content length.\n this._contentLength = stat.size;\n\n this._setReadableStream(fs.createReadStream(this._url));\n this._headersCapability.resolve();\n },\n error => {\n if (error.code === \"ENOENT\") {\n error = new MissingPDFException(`Missing PDF \"${this._url}\".`);\n }\n this._storedError = error;\n this._headersCapability.reject(error);\n }\n );\n }\n}\n\nclass PDFNodeStreamFsRangeReader extends BaseRangeReader {\n constructor(stream, start, end) {\n super(stream);\n\n const fs = NodePackages.get(\"fs\");\n this._setReadableStream(\n fs.createReadStream(this._url, { start, end: end - 1 })\n );\n }\n}\n\nexport { PDFNodeStream };\n","/* Copyright 2015 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** @typedef {import(\"./display_utils\").PageViewport} PageViewport */\n/** @typedef {import(\"./api\").TextContent} TextContent */\n\nimport { AbortException, Util, warn } from \"../shared/util.js\";\nimport { setLayerDimensions } from \"./display_utils.js\";\n\n/**\n * @typedef {Object} TextLayerParameters\n * @property {ReadableStream | TextContent} textContentSource - Text content to\n * render, i.e. the value returned by the page's `streamTextContent` or\n * `getTextContent` method.\n * @property {HTMLElement} container - The DOM node that will contain the text\n * runs.\n * @property {PageViewport} viewport - The target viewport to properly layout\n * the text runs.\n */\n\n/**\n * @typedef {Object} TextLayerUpdateParameters\n * @property {PageViewport} viewport - The target viewport to properly layout\n * the text runs.\n * @property {function} [onBefore] - Callback invoked before the textLayer is\n * updated in the DOM.\n */\n\nconst MAX_TEXT_DIVS_TO_RENDER = 100000;\nconst DEFAULT_FONT_SIZE = 30;\nconst DEFAULT_FONT_ASCENT = 0.8;\n\nclass TextLayer {\n #capability = Promise.withResolvers();\n\n #container = null;\n\n #disableProcessItems = false;\n\n #fontInspectorEnabled = !!globalThis.FontInspector?.enabled;\n\n #lang = null;\n\n #layoutTextParams = null;\n\n #pageHeight = 0;\n\n #pageWidth = 0;\n\n #reader = null;\n\n #rootContainer = null;\n\n #rotation = 0;\n\n #scale = 0;\n\n #styleCache = Object.create(null);\n\n #textContentItemsStr = [];\n\n #textContentSource = null;\n\n #textDivs = [];\n\n #textDivProperties = new WeakMap();\n\n #transform = null;\n\n static #ascentCache = new Map();\n\n static #canvasContexts = new Map();\n\n static #minFontSize = null;\n\n static #pendingTextLayers = new Set();\n\n /**\n * @param {TextLayerParameters} options\n */\n constructor({ textContentSource, container, viewport }) {\n if (textContentSource instanceof ReadableStream) {\n this.#textContentSource = textContentSource;\n } else if (\n (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"GENERIC\")) &&\n typeof textContentSource === \"object\"\n ) {\n this.#textContentSource = new ReadableStream({\n start(controller) {\n controller.enqueue(textContentSource);\n controller.close();\n },\n });\n } else {\n throw new Error('No \"textContentSource\" parameter specified.');\n }\n this.#container = this.#rootContainer = container;\n\n this.#scale = viewport.scale * (globalThis.devicePixelRatio || 1);\n this.#rotation = viewport.rotation;\n this.#layoutTextParams = {\n prevFontSize: null,\n prevFontFamily: null,\n div: null,\n properties: null,\n ctx: null,\n };\n const { pageWidth, pageHeight, pageX, pageY } = viewport.rawDims;\n this.#transform = [1, 0, 0, -1, -pageX, pageY + pageHeight];\n this.#pageWidth = pageWidth;\n this.#pageHeight = pageHeight;\n\n TextLayer.#ensureMinFontSizeComputed();\n\n setLayerDimensions(container, viewport);\n\n // Always clean-up the temporary canvas once rendering is no longer pending.\n this.#capability.promise\n .catch(() => {\n // Avoid \"Uncaught promise\" messages in the console.\n })\n .then(() => {\n TextLayer.#pendingTextLayers.delete(this);\n this.#layoutTextParams = null;\n this.#styleCache = null;\n });\n\n if (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) {\n // For testing purposes.\n Object.defineProperty(this, \"pageWidth\", {\n get() {\n return this.#pageWidth;\n },\n });\n Object.defineProperty(this, \"pageHeight\", {\n get() {\n return this.#pageHeight;\n },\n });\n }\n }\n\n /**\n * Render the textLayer.\n * @returns {Promise}\n */\n render() {\n const pump = () => {\n this.#reader.read().then(({ value, done }) => {\n if (done) {\n this.#capability.resolve();\n return;\n }\n this.#lang ??= value.lang;\n Object.assign(this.#styleCache, value.styles);\n this.#processItems(value.items);\n pump();\n }, this.#capability.reject);\n };\n this.#reader = this.#textContentSource.getReader();\n TextLayer.#pendingTextLayers.add(this);\n pump();\n\n return this.#capability.promise;\n }\n\n /**\n * Update a previously rendered textLayer, if necessary.\n * @param {TextLayerUpdateParameters} options\n * @returns {undefined}\n */\n update({ viewport, onBefore = null }) {\n const scale = viewport.scale * (globalThis.devicePixelRatio || 1);\n const rotation = viewport.rotation;\n\n if (rotation !== this.#rotation) {\n onBefore?.();\n this.#rotation = rotation;\n setLayerDimensions(this.#rootContainer, { rotation });\n }\n\n if (scale !== this.#scale) {\n onBefore?.();\n this.#scale = scale;\n const params = {\n prevFontSize: null,\n prevFontFamily: null,\n div: null,\n properties: null,\n ctx: TextLayer.#getCtx(this.#lang),\n };\n for (const div of this.#textDivs) {\n params.properties = this.#textDivProperties.get(div);\n params.div = div;\n this.#layout(params);\n }\n }\n }\n\n /**\n * Cancel rendering of the textLayer.\n * @returns {undefined}\n */\n cancel() {\n const abortEx = new AbortException(\"TextLayer task cancelled.\");\n\n this.#reader?.cancel(abortEx).catch(() => {\n // Avoid \"Uncaught promise\" messages in the console.\n });\n this.#reader = null;\n\n this.#capability.reject(abortEx);\n }\n\n /**\n * @type {Array} HTML elements that correspond to the text items\n * of the textContent input.\n * This is output and will initially be set to an empty array.\n */\n get textDivs() {\n return this.#textDivs;\n }\n\n /**\n * @type {Array} Strings that correspond to the `str` property of\n * the text items of the textContent input.\n * This is output and will initially be set to an empty array\n */\n get textContentItemsStr() {\n return this.#textContentItemsStr;\n }\n\n #processItems(items) {\n if (this.#disableProcessItems) {\n return;\n }\n this.#layoutTextParams.ctx ??= TextLayer.#getCtx(this.#lang);\n\n const textDivs = this.#textDivs,\n textContentItemsStr = this.#textContentItemsStr;\n\n for (const item of items) {\n // No point in rendering many divs as it would make the browser\n // unusable even after the divs are rendered.\n if (textDivs.length > MAX_TEXT_DIVS_TO_RENDER) {\n warn(\"Ignoring additional textDivs for performance reasons.\");\n\n this.#disableProcessItems = true; // Avoid multiple warnings for one page.\n return;\n }\n\n if (item.str === undefined) {\n if (\n item.type === \"beginMarkedContentProps\" ||\n item.type === \"beginMarkedContent\"\n ) {\n const parent = this.#container;\n this.#container = document.createElement(\"span\");\n this.#container.classList.add(\"markedContent\");\n if (item.id !== null) {\n this.#container.setAttribute(\"id\", `${item.id}`);\n }\n parent.append(this.#container);\n } else if (item.type === \"endMarkedContent\") {\n this.#container = this.#container.parentNode;\n }\n continue;\n }\n textContentItemsStr.push(item.str);\n this.#appendText(item);\n }\n }\n\n #appendText(geom) {\n // Initialize all used properties to keep the caches monomorphic.\n const textDiv = document.createElement(\"span\");\n const textDivProperties = {\n angle: 0,\n canvasWidth: 0,\n hasText: geom.str !== \"\",\n hasEOL: geom.hasEOL,\n fontSize: 0,\n };\n this.#textDivs.push(textDiv);\n\n const tx = Util.transform(this.#transform, geom.transform);\n let angle = Math.atan2(tx[1], tx[0]);\n const style = this.#styleCache[geom.fontName];\n if (style.vertical) {\n angle += Math.PI / 2;\n }\n\n const fontFamily =\n (this.#fontInspectorEnabled && style.fontSubstitution) ||\n style.fontFamily;\n const fontHeight = Math.hypot(tx[2], tx[3]);\n const fontAscent =\n fontHeight * TextLayer.#getAscent(fontFamily, this.#lang);\n\n let left, top;\n if (angle === 0) {\n left = tx[4];\n top = tx[5] - fontAscent;\n } else {\n left = tx[4] + fontAscent * Math.sin(angle);\n top = tx[5] - fontAscent * Math.cos(angle);\n }\n\n const scaleFactorStr = \"calc(var(--scale-factor)*\";\n const divStyle = textDiv.style;\n // Setting the style properties individually, rather than all at once,\n // should be OK since the `textDiv` isn't appended to the document yet.\n if (this.#container === this.#rootContainer) {\n divStyle.left = `${((100 * left) / this.#pageWidth).toFixed(2)}%`;\n divStyle.top = `${((100 * top) / this.#pageHeight).toFixed(2)}%`;\n } else {\n // We're in a marked content span, hence we can't use percents.\n divStyle.left = `${scaleFactorStr}${left.toFixed(2)}px)`;\n divStyle.top = `${scaleFactorStr}${top.toFixed(2)}px)`;\n }\n // We multiply the font size by #minFontSize, and then #layout will\n // scale the element by 1/#minFontSize. This allows us to effectively\n // ignore the minimum font size enforced by the browser, so that the text\n // layer s can always match the size of the text in the canvas.\n divStyle.fontSize = `${scaleFactorStr}${(TextLayer.#minFontSize * fontHeight).toFixed(2)}px)`;\n divStyle.fontFamily = fontFamily;\n\n textDivProperties.fontSize = fontHeight;\n\n // Keeps screen readers from pausing on every new text span.\n textDiv.setAttribute(\"role\", \"presentation\");\n\n textDiv.textContent = geom.str;\n // geom.dir may be 'ttb' for vertical texts.\n textDiv.dir = geom.dir;\n\n // `fontName` is only used by the FontInspector, and we only use `dataset`\n // here to make the font name available in the debugger.\n if (this.#fontInspectorEnabled) {\n textDiv.dataset.fontName =\n style.fontSubstitutionLoadedName || geom.fontName;\n }\n if (angle !== 0) {\n textDivProperties.angle = angle * (180 / Math.PI);\n }\n // We don't bother scaling single-char text divs, because it has very\n // little effect on text highlighting. This makes scrolling on docs with\n // lots of such divs a lot faster.\n let shouldScaleText = false;\n if (geom.str.length > 1) {\n shouldScaleText = true;\n } else if (geom.str !== \" \" && geom.transform[0] !== geom.transform[3]) {\n const absScaleX = Math.abs(geom.transform[0]),\n absScaleY = Math.abs(geom.transform[3]);\n // When the horizontal/vertical scaling differs significantly, also scale\n // even single-char text to improve highlighting (fixes issue11713.pdf).\n if (\n absScaleX !== absScaleY &&\n Math.max(absScaleX, absScaleY) / Math.min(absScaleX, absScaleY) > 1.5\n ) {\n shouldScaleText = true;\n }\n }\n if (shouldScaleText) {\n textDivProperties.canvasWidth = style.vertical ? geom.height : geom.width;\n }\n this.#textDivProperties.set(textDiv, textDivProperties);\n\n // Finally, layout and append the text to the DOM.\n this.#layoutTextParams.div = textDiv;\n this.#layoutTextParams.properties = textDivProperties;\n this.#layout(this.#layoutTextParams);\n\n if (textDivProperties.hasText) {\n this.#container.append(textDiv);\n }\n if (textDivProperties.hasEOL) {\n const br = document.createElement(\"br\");\n br.setAttribute(\"role\", \"presentation\");\n this.#container.append(br);\n }\n }\n\n #layout(params) {\n const { div, properties, ctx, prevFontSize, prevFontFamily } = params;\n const { style } = div;\n\n let transform = \"\";\n if (TextLayer.#minFontSize > 1) {\n transform = `scale(${1 / TextLayer.#minFontSize})`;\n }\n\n if (properties.canvasWidth !== 0 && properties.hasText) {\n const { fontFamily } = style;\n const { canvasWidth, fontSize } = properties;\n\n if (prevFontSize !== fontSize || prevFontFamily !== fontFamily) {\n ctx.font = `${fontSize * this.#scale}px ${fontFamily}`;\n params.prevFontSize = fontSize;\n params.prevFontFamily = fontFamily;\n }\n\n // Only measure the width for multi-char text divs, see `appendText`.\n const { width } = ctx.measureText(div.textContent);\n\n if (width > 0) {\n transform = `scaleX(${(canvasWidth * this.#scale) / width}) ${transform}`;\n }\n }\n if (properties.angle !== 0) {\n transform = `rotate(${properties.angle}deg) ${transform}`;\n }\n if (transform.length > 0) {\n style.transform = transform;\n }\n }\n\n /**\n * Clean-up global textLayer data.\n * @returns {undefined}\n */\n static cleanup() {\n if (this.#pendingTextLayers.size > 0) {\n return;\n }\n this.#ascentCache.clear();\n\n for (const { canvas } of this.#canvasContexts.values()) {\n canvas.remove();\n }\n this.#canvasContexts.clear();\n }\n\n static #getCtx(lang = null) {\n let canvasContext = this.#canvasContexts.get((lang ||= \"\"));\n if (!canvasContext) {\n // We don't use an OffscreenCanvas here because we use serif/sans serif\n // fonts with it and they depends on the locale.\n // In Firefox, the element get a lang attribute that depends on\n // what Fluent returns for the locale and the OffscreenCanvas uses\n // the OS locale.\n // Those two locales can be different and consequently the used fonts will\n // be different (see bug 1869001).\n // Ideally, we should use in the text layer the fonts we've in the pdf (or\n // their replacements when they aren't embedded) and then we can use an\n // OffscreenCanvas.\n const canvas = document.createElement(\"canvas\");\n canvas.className = \"hiddenCanvasElement\";\n canvas.lang = lang;\n document.body.append(canvas);\n canvasContext = canvas.getContext(\"2d\", {\n alpha: false,\n willReadFrequently: true,\n });\n this.#canvasContexts.set(lang, canvasContext);\n }\n return canvasContext;\n }\n\n /**\n * Compute the minimum font size enforced by the browser.\n */\n static #ensureMinFontSizeComputed() {\n if (this.#minFontSize !== null) {\n return;\n }\n const div = document.createElement(\"div\");\n div.style.opacity = 0;\n div.style.lineHeight = 1;\n div.style.fontSize = \"1px\";\n div.style.position = \"absolute\";\n div.textContent = \"X\";\n document.body.append(div);\n // In `display:block` elements contain a single line of text,\n // the height matches the line height (which, when set to 1,\n // matches the actual font size).\n this.#minFontSize = div.getBoundingClientRect().height;\n div.remove();\n }\n\n static #getAscent(fontFamily, lang) {\n const cachedAscent = this.#ascentCache.get(fontFamily);\n if (cachedAscent) {\n return cachedAscent;\n }\n const ctx = this.#getCtx(lang);\n\n const savedFont = ctx.font;\n ctx.canvas.width = ctx.canvas.height = DEFAULT_FONT_SIZE;\n ctx.font = `${DEFAULT_FONT_SIZE}px ${fontFamily}`;\n const metrics = ctx.measureText(\"\");\n\n // Both properties aren't available by default in Firefox.\n let ascent = metrics.fontBoundingBoxAscent;\n let descent = Math.abs(metrics.fontBoundingBoxDescent);\n if (ascent) {\n const ratio = ascent / (ascent + descent);\n this.#ascentCache.set(fontFamily, ratio);\n\n ctx.canvas.width = ctx.canvas.height = 0;\n ctx.font = savedFont;\n return ratio;\n }\n\n // Try basic heuristic to guess ascent/descent.\n // Draw a g with baseline at 0,0 and then get the line\n // number where a pixel has non-null red component (starting\n // from bottom).\n ctx.strokeStyle = \"red\";\n ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);\n ctx.strokeText(\"g\", 0, 0);\n let pixels = ctx.getImageData(\n 0,\n 0,\n DEFAULT_FONT_SIZE,\n DEFAULT_FONT_SIZE\n ).data;\n descent = 0;\n for (let i = pixels.length - 1 - 3; i >= 0; i -= 4) {\n if (pixels[i] > 0) {\n descent = Math.ceil(i / 4 / DEFAULT_FONT_SIZE);\n break;\n }\n }\n\n // Draw an A with baseline at 0,DEFAULT_FONT_SIZE and then get the line\n // number where a pixel has non-null red component (starting\n // from top).\n ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);\n ctx.strokeText(\"A\", 0, DEFAULT_FONT_SIZE);\n pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;\n ascent = 0;\n for (let i = 0, ii = pixels.length; i < ii; i += 4) {\n if (pixels[i] > 0) {\n ascent = DEFAULT_FONT_SIZE - Math.floor(i / 4 / DEFAULT_FONT_SIZE);\n break;\n }\n }\n\n ctx.canvas.width = ctx.canvas.height = 0;\n ctx.font = savedFont;\n\n const ratio = ascent ? ascent / (ascent + descent) : DEFAULT_FONT_ASCENT;\n this.#ascentCache.set(fontFamily, ratio);\n return ratio;\n }\n}\n\nexport { TextLayer };\n","/* Copyright 2021 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** @typedef {import(\"./api\").TextContent} TextContent */\n\nclass XfaText {\n /**\n * Walk an XFA tree and create an array of text nodes that is compatible\n * with a regular PDFs TextContent. Currently, only TextItem.str is supported,\n * all other fields and styles haven't been implemented.\n *\n * @param {Object} xfa - An XFA fake DOM object.\n *\n * @returns {TextContent}\n */\n static textContent(xfa) {\n const items = [];\n const output = {\n items,\n styles: Object.create(null),\n };\n function walk(node) {\n if (!node) {\n return;\n }\n let str = null;\n const name = node.name;\n if (name === \"#text\") {\n str = node.value;\n } else if (!XfaText.shouldBuildText(name)) {\n return;\n } else if (node?.attributes?.textContent) {\n str = node.attributes.textContent;\n } else if (node.value) {\n str = node.value;\n }\n if (str !== null) {\n items.push({\n str,\n });\n }\n if (!node.children) {\n return;\n }\n for (const child of node.children) {\n walk(child);\n }\n }\n walk(xfa);\n return output;\n }\n\n /**\n * @param {string} name - DOM node name. (lower case)\n *\n * @returns {boolean} true if the DOM node should have a corresponding text\n * node.\n */\n static shouldBuildText(name) {\n return !(\n name === \"textarea\" ||\n name === \"input\" ||\n name === \"option\" ||\n name === \"select\"\n );\n }\n}\n\nexport { XfaText };\n","/* Copyright 2012 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @module pdfjsLib\n */\n\nimport {\n AbortException,\n AnnotationMode,\n assert,\n getVerbosityLevel,\n info,\n InvalidPDFException,\n isNodeJS,\n MAX_IMAGE_SIZE_TO_CACHE,\n MissingPDFException,\n PasswordException,\n RenderingIntentFlag,\n setVerbosityLevel,\n shadow,\n stringToBytes,\n UnexpectedResponseException,\n UnknownErrorException,\n unreachable,\n warn,\n} from \"../shared/util.js\";\nimport {\n AnnotationStorage,\n PrintAnnotationStorage,\n SerializableEmpty,\n} from \"./annotation_storage.js\";\nimport {\n DOMCanvasFactory,\n DOMCMapReaderFactory,\n DOMFilterFactory,\n DOMStandardFontDataFactory,\n isDataScheme,\n isValidFetchUrl,\n PageViewport,\n RenderingCancelledException,\n StatTimer,\n} from \"./display_utils.js\";\nimport { FontFaceObject, FontLoader } from \"./font_loader.js\";\nimport {\n NodeCanvasFactory,\n NodeCMapReaderFactory,\n NodeFilterFactory,\n NodePackages,\n NodeStandardFontDataFactory,\n} from \"display-node_utils\";\nimport { CanvasGraphics } from \"./canvas.js\";\nimport { GlobalWorkerOptions } from \"./worker_options.js\";\nimport { MessageHandler } from \"../shared/message_handler.js\";\nimport { Metadata } from \"./metadata.js\";\nimport { OptionalContentConfig } from \"./optional_content_config.js\";\nimport { PDFDataTransportStream } from \"./transport_stream.js\";\nimport { PDFFetchStream } from \"display-fetch_stream\";\nimport { PDFNetworkStream } from \"display-network\";\nimport { PDFNodeStream } from \"display-node_stream\";\nimport { TextLayer } from \"./text_layer.js\";\nimport { XfaText } from \"./xfa_text.js\";\n\nconst DEFAULT_RANGE_CHUNK_SIZE = 65536; // 2^16 = 65536\nconst RENDERING_CANCELLED_TIMEOUT = 100; // ms\nconst DELAYED_CLEANUP_TIMEOUT = 5000; // ms\n\nconst DefaultCanvasFactory =\n typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"GENERIC\") && isNodeJS\n ? NodeCanvasFactory\n : DOMCanvasFactory;\nconst DefaultCMapReaderFactory =\n typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"GENERIC\") && isNodeJS\n ? NodeCMapReaderFactory\n : DOMCMapReaderFactory;\nconst DefaultFilterFactory =\n typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"GENERIC\") && isNodeJS\n ? NodeFilterFactory\n : DOMFilterFactory;\nconst DefaultStandardFontDataFactory =\n typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"GENERIC\") && isNodeJS\n ? NodeStandardFontDataFactory\n : DOMStandardFontDataFactory;\n\n/**\n * @typedef { Int8Array | Uint8Array | Uint8ClampedArray |\n * Int16Array | Uint16Array |\n * Int32Array | Uint32Array | Float32Array |\n * Float64Array\n * } TypedArray\n */\n\n/**\n * @typedef {Object} RefProxy\n * @property {number} num\n * @property {number} gen\n */\n\n/**\n * Document initialization / loading parameters object.\n *\n * @typedef {Object} DocumentInitParameters\n * @property {string | URL} [url] - The URL of the PDF.\n * @property {TypedArray | ArrayBuffer | Array | string} [data] -\n * Binary PDF data.\n * Use TypedArrays (Uint8Array) to improve the memory usage. If PDF data is\n * BASE64-encoded, use `atob()` to convert it to a binary string first.\n *\n * NOTE: If TypedArrays are used they will generally be transferred to the\n * worker-thread. This will help reduce main-thread memory usage, however\n * it will take ownership of the TypedArrays.\n * @property {Object} [httpHeaders] - Basic authentication headers.\n * @property {boolean} [withCredentials] - Indicates whether or not\n * cross-site Access-Control requests should be made using credentials such\n * as cookies or authorization headers. The default is `false`.\n * @property {string} [password] - For decrypting password-protected PDFs.\n * @property {number} [length] - The PDF file length. It's used for progress\n * reports and range requests operations.\n * @property {PDFDataRangeTransport} [range] - Allows for using a custom range\n * transport implementation.\n * @property {number} [rangeChunkSize] - Specify maximum number of bytes fetched\n * per range request. The default value is {@link DEFAULT_RANGE_CHUNK_SIZE}.\n * @property {PDFWorker} [worker] - The worker that will be used for loading and\n * parsing the PDF data.\n * @property {number} [verbosity] - Controls the logging level; the constants\n * from {@link VerbosityLevel} should be used.\n * @property {string} [docBaseUrl] - The base URL of the document, used when\n * attempting to recover valid absolute URLs for annotations, and outline\n * items, that (incorrectly) only specify relative URLs.\n * @property {string} [cMapUrl] - The URL where the predefined Adobe CMaps are\n * located. Include the trailing slash.\n * @property {boolean} [cMapPacked] - Specifies if the Adobe CMaps are binary\n * packed or not. The default value is `true`.\n * @property {Object} [CMapReaderFactory] - The factory that will be used when\n * reading built-in CMap files. Providing a custom factory is useful for\n * environments without Fetch API or `XMLHttpRequest` support, such as\n * Node.js. The default value is {DOMCMapReaderFactory}.\n * @property {boolean} [useSystemFonts] - When `true`, fonts that aren't\n * embedded in the PDF document will fallback to a system font.\n * The default value is `true` in web environments and `false` in Node.js;\n * unless `disableFontFace === true` in which case this defaults to `false`\n * regardless of the environment (to prevent completely broken fonts).\n * @property {string} [standardFontDataUrl] - The URL where the standard font\n * files are located. Include the trailing slash.\n * @property {Object} [StandardFontDataFactory] - The factory that will be used\n * when reading the standard font files. Providing a custom factory is useful\n * for environments without Fetch API or `XMLHttpRequest` support, such as\n * Node.js. The default value is {DOMStandardFontDataFactory}.\n * @property {boolean} [useWorkerFetch] - Enable using the Fetch API in the\n * worker-thread when reading CMap and standard font files. When `true`,\n * the `CMapReaderFactory` and `StandardFontDataFactory` options are ignored.\n * The default value is `true` in web environments and `false` in Node.js.\n * @property {boolean} [stopAtErrors] - Reject certain promises, e.g.\n * `getOperatorList`, `getTextContent`, and `RenderTask`, when the associated\n * PDF data cannot be successfully parsed, instead of attempting to recover\n * whatever possible of the data. The default value is `false`.\n * @property {number} [maxImageSize] - The maximum allowed image size in total\n * pixels, i.e. width * height. Images above this value will not be rendered.\n * Use -1 for no limit, which is also the default value.\n * @property {boolean} [isEvalSupported] - Determines if we can evaluate strings\n * as JavaScript. Primarily used to improve performance of PDF functions.\n * The default value is `true`.\n * @property {boolean} [isOffscreenCanvasSupported] - Determines if we can use\n * `OffscreenCanvas` in the worker. Primarily used to improve performance of\n * image conversion/rendering.\n * The default value is `true` in web environments and `false` in Node.js.\n * @property {number} [canvasMaxAreaInBytes] - The integer value is used to\n * know when an image must be resized (uses `OffscreenCanvas` in the worker).\n * If it's -1 then a possibly slow algorithm is used to guess the max value.\n * @property {boolean} [disableFontFace] - By default fonts are converted to\n * OpenType fonts and loaded via the Font Loading API or `@font-face` rules.\n * If disabled, fonts will be rendered using a built-in font renderer that\n * constructs the glyphs with primitive path commands.\n * The default value is `false` in web environments and `true` in Node.js.\n * @property {boolean} [fontExtraProperties] - Include additional properties,\n * which are unused during rendering of PDF documents, when exporting the\n * parsed font data from the worker-thread. This may be useful for debugging\n * purposes (and backwards compatibility), but note that it will lead to\n * increased memory usage. The default value is `false`.\n * @property {boolean} [enableXfa] - Render Xfa forms if any.\n * The default value is `false`.\n * @property {HTMLDocument} [ownerDocument] - Specify an explicit document\n * context to create elements with and to load resources, such as fonts,\n * into. Defaults to the current document.\n * @property {boolean} [disableRange] - Disable range request loading of PDF\n * files. When enabled, and if the server supports partial content requests,\n * then the PDF will be fetched in chunks. The default value is `false`.\n * @property {boolean} [disableStream] - Disable streaming of PDF file data.\n * By default PDF.js attempts to load PDF files in chunks. The default value\n * is `false`.\n * @property {boolean} [disableAutoFetch] - Disable pre-fetching of PDF file\n * data. When range requests are enabled PDF.js will automatically keep\n * fetching more data even if it isn't needed to display the current page.\n * The default value is `false`.\n *\n * NOTE: It is also necessary to disable streaming, see above, in order for\n * disabling of pre-fetching to work correctly.\n * @property {boolean} [pdfBug] - Enables special hooks for debugging PDF.js\n * (see `web/debugger.js`). The default value is `false`.\n * @property {Object} [canvasFactory] - The factory instance that will be used\n * when creating canvases. The default value is {new DOMCanvasFactory()}.\n * @property {Object} [filterFactory] - A factory instance that will be used\n * to create SVG filters when rendering some images on the main canvas.\n * @property {boolean} [enableHWA] - Enables hardware acceleration for\n * rendering. The default value is `false`.\n */\n\n/**\n * This is the main entry point for loading a PDF and interacting with it.\n *\n * NOTE: If a URL is used to fetch the PDF data a standard Fetch API call (or\n * XHR as fallback) is used, which means it must follow same origin rules,\n * e.g. no cross-domain requests without CORS.\n *\n * @param {string | URL | TypedArray | ArrayBuffer | DocumentInitParameters}\n * src - Can be a URL where a PDF file is located, a typed array (Uint8Array)\n * already populated with data, or a parameter object.\n * @returns {PDFDocumentLoadingTask}\n */\nfunction getDocument(src = {}) {\n if (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"GENERIC\")) {\n if (typeof src === \"string\" || src instanceof URL) {\n src = { url: src };\n } else if (src instanceof ArrayBuffer || ArrayBuffer.isView(src)) {\n src = { data: src };\n }\n }\n const task = new PDFDocumentLoadingTask();\n const { docId } = task;\n\n const url = src.url ? getUrlProp(src.url) : null;\n const data = src.data ? getDataProp(src.data) : null;\n const httpHeaders = src.httpHeaders || null;\n const withCredentials = src.withCredentials === true;\n const password = src.password ?? null;\n const rangeTransport =\n src.range instanceof PDFDataRangeTransport ? src.range : null;\n const rangeChunkSize =\n Number.isInteger(src.rangeChunkSize) && src.rangeChunkSize > 0\n ? src.rangeChunkSize\n : DEFAULT_RANGE_CHUNK_SIZE;\n let worker = src.worker instanceof PDFWorker ? src.worker : null;\n const verbosity = src.verbosity;\n // Ignore \"data:\"-URLs, since they can't be used to recover valid absolute\n // URLs anyway. We want to avoid sending them to the worker-thread, since\n // they contain the *entire* PDF document and can thus be arbitrarily long.\n const docBaseUrl =\n typeof src.docBaseUrl === \"string\" && !isDataScheme(src.docBaseUrl)\n ? src.docBaseUrl\n : null;\n const cMapUrl = typeof src.cMapUrl === \"string\" ? src.cMapUrl : null;\n const cMapPacked = src.cMapPacked !== false;\n const CMapReaderFactory = src.CMapReaderFactory || DefaultCMapReaderFactory;\n const standardFontDataUrl =\n typeof src.standardFontDataUrl === \"string\"\n ? src.standardFontDataUrl\n : null;\n const StandardFontDataFactory =\n src.StandardFontDataFactory || DefaultStandardFontDataFactory;\n const ignoreErrors = src.stopAtErrors !== true;\n const maxImageSize =\n Number.isInteger(src.maxImageSize) && src.maxImageSize > -1\n ? src.maxImageSize\n : -1;\n const isEvalSupported = src.isEvalSupported !== false;\n const isOffscreenCanvasSupported =\n typeof src.isOffscreenCanvasSupported === \"boolean\"\n ? src.isOffscreenCanvasSupported\n : !isNodeJS;\n const canvasMaxAreaInBytes = Number.isInteger(src.canvasMaxAreaInBytes)\n ? src.canvasMaxAreaInBytes\n : -1;\n const disableFontFace =\n typeof src.disableFontFace === \"boolean\" ? src.disableFontFace : isNodeJS;\n const fontExtraProperties = src.fontExtraProperties === true;\n const enableXfa = src.enableXfa === true;\n const ownerDocument = src.ownerDocument || globalThis.document;\n const disableRange = src.disableRange === true;\n const disableStream = src.disableStream === true;\n const disableAutoFetch = src.disableAutoFetch === true;\n const pdfBug = src.pdfBug === true;\n const enableHWA = src.enableHWA === true;\n\n // Parameters whose default values depend on other parameters.\n const length = rangeTransport ? rangeTransport.length : (src.length ?? NaN);\n const useSystemFonts =\n typeof src.useSystemFonts === \"boolean\"\n ? src.useSystemFonts\n : !isNodeJS && !disableFontFace;\n const useWorkerFetch =\n typeof src.useWorkerFetch === \"boolean\"\n ? src.useWorkerFetch\n : (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) ||\n (CMapReaderFactory === DOMCMapReaderFactory &&\n StandardFontDataFactory === DOMStandardFontDataFactory &&\n cMapUrl &&\n standardFontDataUrl &&\n isValidFetchUrl(cMapUrl, document.baseURI) &&\n isValidFetchUrl(standardFontDataUrl, document.baseURI));\n const canvasFactory =\n src.canvasFactory || new DefaultCanvasFactory({ ownerDocument, enableHWA });\n const filterFactory =\n src.filterFactory || new DefaultFilterFactory({ docId, ownerDocument });\n\n // Parameters only intended for development/testing purposes.\n const styleElement =\n typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")\n ? src.styleElement\n : null;\n\n // Set the main-thread verbosity level.\n setVerbosityLevel(verbosity);\n\n // Ensure that the various factories can be initialized, when necessary,\n // since the user may provide *custom* ones.\n const transportFactory = {\n canvasFactory,\n filterFactory,\n };\n if (!useWorkerFetch) {\n transportFactory.cMapReaderFactory = new CMapReaderFactory({\n baseUrl: cMapUrl,\n isCompressed: cMapPacked,\n });\n transportFactory.standardFontDataFactory = new StandardFontDataFactory({\n baseUrl: standardFontDataUrl,\n });\n }\n\n if (!worker) {\n const workerParams = {\n verbosity,\n port: GlobalWorkerOptions.workerPort,\n };\n // Worker was not provided -- creating and owning our own. If message port\n // is specified in global worker options, using it.\n worker = workerParams.port\n ? PDFWorker.fromPort(workerParams)\n : new PDFWorker(workerParams);\n task._worker = worker;\n }\n\n const docParams = {\n docId,\n apiVersion:\n typeof PDFJSDev !== \"undefined\" && !PDFJSDev.test(\"TESTING\")\n ? PDFJSDev.eval(\"BUNDLE_VERSION\")\n : null,\n data,\n password,\n disableAutoFetch,\n rangeChunkSize,\n length,\n docBaseUrl,\n enableXfa,\n evaluatorOptions: {\n maxImageSize,\n disableFontFace,\n ignoreErrors,\n isEvalSupported,\n isOffscreenCanvasSupported,\n canvasMaxAreaInBytes,\n fontExtraProperties,\n useSystemFonts,\n cMapUrl: useWorkerFetch ? cMapUrl : null,\n standardFontDataUrl: useWorkerFetch ? standardFontDataUrl : null,\n },\n };\n const transportParams = {\n disableFontFace,\n fontExtraProperties,\n ownerDocument,\n pdfBug,\n styleElement,\n loadingParams: {\n disableAutoFetch,\n enableXfa,\n },\n };\n\n worker.promise\n .then(function () {\n if (task.destroyed) {\n throw new Error(\"Loading aborted\");\n }\n if (worker.destroyed) {\n throw new Error(\"Worker was destroyed\");\n }\n\n const workerIdPromise = worker.messageHandler.sendWithPromise(\n \"GetDocRequest\",\n docParams,\n data ? [data.buffer] : null\n );\n\n let networkStream;\n if (rangeTransport) {\n networkStream = new PDFDataTransportStream(rangeTransport, {\n disableRange,\n disableStream,\n });\n } else if (!data) {\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n throw new Error(\"Not implemented: createPDFNetworkStream\");\n }\n if (!url) {\n throw new Error(\"getDocument - no `url` parameter provided.\");\n }\n const createPDFNetworkStream = params => {\n if (\n typeof PDFJSDev !== \"undefined\" &&\n PDFJSDev.test(\"GENERIC\") &&\n isNodeJS\n ) {\n const isFetchSupported = function () {\n return (\n typeof fetch !== \"undefined\" &&\n typeof Response !== \"undefined\" &&\n \"body\" in Response.prototype\n );\n };\n return isFetchSupported() && isValidFetchUrl(params.url)\n ? new PDFFetchStream(params)\n : new PDFNodeStream(params);\n }\n return isValidFetchUrl(params.url)\n ? new PDFFetchStream(params)\n : new PDFNetworkStream(params);\n };\n\n networkStream = createPDFNetworkStream({\n url,\n length,\n httpHeaders,\n withCredentials,\n rangeChunkSize,\n disableRange,\n disableStream,\n });\n }\n\n return workerIdPromise.then(workerId => {\n if (task.destroyed) {\n throw new Error(\"Loading aborted\");\n }\n if (worker.destroyed) {\n throw new Error(\"Worker was destroyed\");\n }\n\n const messageHandler = new MessageHandler(docId, workerId, worker.port);\n const transport = new WorkerTransport(\n messageHandler,\n task,\n networkStream,\n transportParams,\n transportFactory\n );\n task._transport = transport;\n messageHandler.send(\"Ready\", null);\n });\n })\n .catch(task._capability.reject);\n\n return task;\n}\n\nfunction getUrlProp(val) {\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n return null; // The 'url' is unused with `PDFDataRangeTransport`.\n }\n if (val instanceof URL) {\n return val.href;\n }\n try {\n // The full path is required in the 'url' field.\n return new URL(val, window.location).href;\n } catch {\n if (\n typeof PDFJSDev !== \"undefined\" &&\n PDFJSDev.test(\"GENERIC\") &&\n isNodeJS &&\n typeof val === \"string\"\n ) {\n return val; // Use the url as-is in Node.js environments.\n }\n }\n throw new Error(\n \"Invalid PDF url data: \" +\n \"either string or URL-object is expected in the url property.\"\n );\n}\n\nfunction getDataProp(val) {\n // Converting string or array-like data to Uint8Array.\n if (\n typeof PDFJSDev !== \"undefined\" &&\n PDFJSDev.test(\"GENERIC\") &&\n isNodeJS &&\n typeof Buffer !== \"undefined\" && // eslint-disable-line no-undef\n val instanceof Buffer // eslint-disable-line no-undef\n ) {\n throw new Error(\n \"Please provide binary data as `Uint8Array`, rather than `Buffer`.\"\n );\n }\n if (val instanceof Uint8Array && val.byteLength === val.buffer.byteLength) {\n // Use the data as-is when it's already a Uint8Array that completely\n // \"utilizes\" its underlying ArrayBuffer, to prevent any possible\n // issues when transferring it to the worker-thread.\n return val;\n }\n if (typeof val === \"string\") {\n return stringToBytes(val);\n }\n if (\n val instanceof ArrayBuffer ||\n ArrayBuffer.isView(val) ||\n (typeof val === \"object\" && !isNaN(val?.length))\n ) {\n return new Uint8Array(val);\n }\n throw new Error(\n \"Invalid PDF binary data: either TypedArray, \" +\n \"string, or array-like object is expected in the data property.\"\n );\n}\n\nfunction isRefProxy(ref) {\n return (\n typeof ref === \"object\" &&\n Number.isInteger(ref?.num) &&\n ref.num >= 0 &&\n Number.isInteger(ref?.gen) &&\n ref.gen >= 0\n );\n}\n\n/**\n * @typedef {Object} OnProgressParameters\n * @property {number} loaded - Currently loaded number of bytes.\n * @property {number} total - Total number of bytes in the PDF file.\n */\n\n/**\n * The loading task controls the operations required to load a PDF document\n * (such as network requests) and provides a way to listen for completion,\n * after which individual pages can be rendered.\n */\nclass PDFDocumentLoadingTask {\n static #docId = 0;\n\n constructor() {\n this._capability = Promise.withResolvers();\n this._transport = null;\n this._worker = null;\n\n /**\n * Unique identifier for the document loading task.\n * @type {string}\n */\n this.docId = `d${PDFDocumentLoadingTask.#docId++}`;\n\n /**\n * Whether the loading task is destroyed or not.\n * @type {boolean}\n */\n this.destroyed = false;\n\n /**\n * Callback to request a password if a wrong or no password was provided.\n * The callback receives two parameters: a function that should be called\n * with the new password, and a reason (see {@link PasswordResponses}).\n * @type {function}\n */\n this.onPassword = null;\n\n /**\n * Callback to be able to monitor the loading progress of the PDF file\n * (necessary to implement e.g. a loading bar).\n * The callback receives an {@link OnProgressParameters} argument.\n * @type {function}\n */\n this.onProgress = null;\n }\n\n /**\n * Promise for document loading task completion.\n * @type {Promise}\n */\n get promise() {\n return this._capability.promise;\n }\n\n /**\n * Abort all network requests and destroy the worker.\n * @returns {Promise} A promise that is resolved when destruction is\n * completed.\n */\n async destroy() {\n this.destroyed = true;\n try {\n if (this._worker?.port) {\n this._worker._pendingDestroy = true;\n }\n await this._transport?.destroy();\n } catch (ex) {\n if (this._worker?.port) {\n delete this._worker._pendingDestroy;\n }\n throw ex;\n }\n\n this._transport = null;\n if (this._worker) {\n this._worker.destroy();\n this._worker = null;\n }\n }\n}\n\n/**\n * Abstract class to support range requests file loading.\n *\n * NOTE: The TypedArrays passed to the constructor and relevant methods below\n * will generally be transferred to the worker-thread. This will help reduce\n * main-thread memory usage, however it will take ownership of the TypedArrays.\n */\nclass PDFDataRangeTransport {\n /**\n * @param {number} length\n * @param {Uint8Array|null} initialData\n * @param {boolean} [progressiveDone]\n * @param {string} [contentDispositionFilename]\n */\n constructor(\n length,\n initialData,\n progressiveDone = false,\n contentDispositionFilename = null\n ) {\n this.length = length;\n this.initialData = initialData;\n this.progressiveDone = progressiveDone;\n this.contentDispositionFilename = contentDispositionFilename;\n\n this._rangeListeners = [];\n this._progressListeners = [];\n this._progressiveReadListeners = [];\n this._progressiveDoneListeners = [];\n this._readyCapability = Promise.withResolvers();\n }\n\n /**\n * @param {function} listener\n */\n addRangeListener(listener) {\n this._rangeListeners.push(listener);\n }\n\n /**\n * @param {function} listener\n */\n addProgressListener(listener) {\n this._progressListeners.push(listener);\n }\n\n /**\n * @param {function} listener\n */\n addProgressiveReadListener(listener) {\n this._progressiveReadListeners.push(listener);\n }\n\n /**\n * @param {function} listener\n */\n addProgressiveDoneListener(listener) {\n this._progressiveDoneListeners.push(listener);\n }\n\n /**\n * @param {number} begin\n * @param {Uint8Array|null} chunk\n */\n onDataRange(begin, chunk) {\n for (const listener of this._rangeListeners) {\n listener(begin, chunk);\n }\n }\n\n /**\n * @param {number} loaded\n * @param {number|undefined} total\n */\n onDataProgress(loaded, total) {\n this._readyCapability.promise.then(() => {\n for (const listener of this._progressListeners) {\n listener(loaded, total);\n }\n });\n }\n\n /**\n * @param {Uint8Array|null} chunk\n */\n onDataProgressiveRead(chunk) {\n this._readyCapability.promise.then(() => {\n for (const listener of this._progressiveReadListeners) {\n listener(chunk);\n }\n });\n }\n\n onDataProgressiveDone() {\n this._readyCapability.promise.then(() => {\n for (const listener of this._progressiveDoneListeners) {\n listener();\n }\n });\n }\n\n transportReady() {\n this._readyCapability.resolve();\n }\n\n /**\n * @param {number} begin\n * @param {number} end\n */\n requestDataRange(begin, end) {\n unreachable(\"Abstract method PDFDataRangeTransport.requestDataRange\");\n }\n\n abort() {}\n}\n\n/**\n * Proxy to a `PDFDocument` in the worker thread.\n */\nclass PDFDocumentProxy {\n constructor(pdfInfo, transport) {\n this._pdfInfo = pdfInfo;\n this._transport = transport;\n\n if (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) {\n // For testing purposes.\n Object.defineProperty(this, \"getNetworkStreamName\", {\n value: () => this._transport.getNetworkStreamName(),\n });\n Object.defineProperty(this, \"getXFADatasets\", {\n value: () => this._transport.getXFADatasets(),\n });\n Object.defineProperty(this, \"getXRefPrevValue\", {\n value: () => this._transport.getXRefPrevValue(),\n });\n Object.defineProperty(this, \"getStartXRefPos\", {\n value: () => this._transport.getStartXRefPos(),\n });\n Object.defineProperty(this, \"getAnnotArray\", {\n value: pageIndex => this._transport.getAnnotArray(pageIndex),\n });\n }\n }\n\n /**\n * @type {AnnotationStorage} Storage for annotation data in forms.\n */\n get annotationStorage() {\n return this._transport.annotationStorage;\n }\n\n /**\n * @type {Object} The filter factory instance.\n */\n get filterFactory() {\n return this._transport.filterFactory;\n }\n\n /**\n * @type {number} Total number of pages in the PDF file.\n */\n get numPages() {\n return this._pdfInfo.numPages;\n }\n\n /**\n * @type {Array} A (not guaranteed to be) unique ID to\n * identify the PDF document.\n * NOTE: The first element will always be defined for all PDF documents,\n * whereas the second element is only defined for *modified* PDF documents.\n */\n get fingerprints() {\n return this._pdfInfo.fingerprints;\n }\n\n /**\n * @type {boolean} True if only XFA form.\n */\n get isPureXfa() {\n return shadow(this, \"isPureXfa\", !!this._transport._htmlForXfa);\n }\n\n /**\n * NOTE: This is (mostly) intended to support printing of XFA forms.\n *\n * @type {Object | null} An object representing a HTML tree structure\n * to render the XFA, or `null` when no XFA form exists.\n */\n get allXfaHtml() {\n return this._transport._htmlForXfa;\n }\n\n /**\n * @param {number} pageNumber - The page number to get. The first page is 1.\n * @returns {Promise} A promise that is resolved with\n * a {@link PDFPageProxy} object.\n */\n getPage(pageNumber) {\n return this._transport.getPage(pageNumber);\n }\n\n /**\n * @param {RefProxy} ref - The page reference.\n * @returns {Promise} A promise that is resolved with the page index,\n * starting from zero, that is associated with the reference.\n */\n getPageIndex(ref) {\n return this._transport.getPageIndex(ref);\n }\n\n /**\n * @returns {Promise>>} A promise that is resolved\n * with a mapping from named destinations to references.\n *\n * This can be slow for large documents. Use `getDestination` instead.\n */\n getDestinations() {\n return this._transport.getDestinations();\n }\n\n /**\n * @param {string} id - The named destination to get.\n * @returns {Promise | null>} A promise that is resolved with all\n * information of the given named destination, or `null` when the named\n * destination is not present in the PDF file.\n */\n getDestination(id) {\n return this._transport.getDestination(id);\n }\n\n /**\n * @returns {Promise | null>} A promise that is resolved with\n * an {Array} containing the page labels that correspond to the page\n * indexes, or `null` when no page labels are present in the PDF file.\n */\n getPageLabels() {\n return this._transport.getPageLabels();\n }\n\n /**\n * @returns {Promise} A promise that is resolved with a {string}\n * containing the page layout name.\n */\n getPageLayout() {\n return this._transport.getPageLayout();\n }\n\n /**\n * @returns {Promise} A promise that is resolved with a {string}\n * containing the page mode name.\n */\n getPageMode() {\n return this._transport.getPageMode();\n }\n\n /**\n * @returns {Promise} A promise that is resolved with an\n * {Object} containing the viewer preferences, or `null` when no viewer\n * preferences are present in the PDF file.\n */\n getViewerPreferences() {\n return this._transport.getViewerPreferences();\n }\n\n /**\n * @returns {Promise} A promise that is resolved with an {Array}\n * containing the destination, or `null` when no open action is present\n * in the PDF.\n */\n getOpenAction() {\n return this._transport.getOpenAction();\n }\n\n /**\n * @returns {Promise} A promise that is resolved with a lookup table\n * for mapping named attachments to their content.\n */\n getAttachments() {\n return this._transport.getAttachments();\n }\n\n /**\n * @returns {Promise} A promise that is resolved with\n * an {Object} with the JavaScript actions:\n * - from the name tree.\n * - from A or AA entries in the catalog dictionary.\n * , or `null` if no JavaScript exists.\n */\n getJSActions() {\n return this._transport.getDocJSActions();\n }\n\n /**\n * @typedef {Object} OutlineNode\n * @property {string} title\n * @property {boolean} bold\n * @property {boolean} italic\n * @property {Uint8ClampedArray} color - The color in RGB format to use for\n * display purposes.\n * @property {string | Array | null} dest\n * @property {string | null} url\n * @property {string | undefined} unsafeUrl\n * @property {boolean | undefined} newWindow\n * @property {number | undefined} count\n * @property {Array} items\n */\n\n /**\n * @returns {Promise>} A promise that is resolved with an\n * {Array} that is a tree outline (if it has one) of the PDF file.\n */\n getOutline() {\n return this._transport.getOutline();\n }\n\n /**\n * @typedef {Object} GetOptionalContentConfigParameters\n * @property {string} [intent] - Determines the optional content groups that\n * are visible by default; valid values are:\n * - 'display' (viewable groups).\n * - 'print' (printable groups).\n * - 'any' (all groups).\n * The default value is 'display'.\n */\n\n /**\n * @param {GetOptionalContentConfigParameters} [params] - Optional content\n * config parameters.\n * @returns {Promise} A promise that is resolved with\n * an {@link OptionalContentConfig} that contains all the optional content\n * groups (assuming that the document has any).\n */\n getOptionalContentConfig({ intent = \"display\" } = {}) {\n const { renderingIntent } = this._transport.getRenderingIntent(intent);\n\n return this._transport.getOptionalContentConfig(renderingIntent);\n }\n\n /**\n * @returns {Promise | null>} A promise that is resolved with\n * an {Array} that contains the permission flags for the PDF document, or\n * `null` when no permissions are present in the PDF file.\n */\n getPermissions() {\n return this._transport.getPermissions();\n }\n\n /**\n * @returns {Promise<{ info: Object, metadata: Metadata }>} A promise that is\n * resolved with an {Object} that has `info` and `metadata` properties.\n * `info` is an {Object} filled with anything available in the information\n * dictionary and similarly `metadata` is a {Metadata} object with\n * information from the metadata section of the PDF.\n */\n getMetadata() {\n return this._transport.getMetadata();\n }\n\n /**\n * @typedef {Object} MarkInfo\n * Properties correspond to Table 321 of the PDF 32000-1:2008 spec.\n * @property {boolean} Marked\n * @property {boolean} UserProperties\n * @property {boolean} Suspects\n */\n\n /**\n * @returns {Promise} A promise that is resolved with\n * a {MarkInfo} object that contains the MarkInfo flags for the PDF\n * document, or `null` when no MarkInfo values are present in the PDF file.\n */\n getMarkInfo() {\n return this._transport.getMarkInfo();\n }\n\n /**\n * @returns {Promise} A promise that is resolved with a\n * {Uint8Array} containing the raw data of the PDF document.\n */\n getData() {\n return this._transport.getData();\n }\n\n /**\n * @returns {Promise} A promise that is resolved with a\n * {Uint8Array} containing the full data of the saved document.\n */\n saveDocument() {\n return this._transport.saveDocument();\n }\n\n /**\n * @returns {Promise<{ length: number }>} A promise that is resolved when the\n * document's data is loaded. It is resolved with an {Object} that contains\n * the `length` property that indicates size of the PDF data in bytes.\n */\n getDownloadInfo() {\n return this._transport.downloadInfoCapability.promise;\n }\n\n /**\n * Cleans up resources allocated by the document on both the main and worker\n * threads.\n *\n * NOTE: Do not, under any circumstances, call this method when rendering is\n * currently ongoing since that may lead to rendering errors.\n *\n * @param {boolean} [keepLoadedFonts] - Let fonts remain attached to the DOM.\n * NOTE: This will increase persistent memory usage, hence don't use this\n * option unless absolutely necessary. The default value is `false`.\n * @returns {Promise} A promise that is resolved when clean-up has finished.\n */\n cleanup(keepLoadedFonts = false) {\n return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa);\n }\n\n /**\n * Destroys the current document instance and terminates the worker.\n */\n destroy() {\n return this.loadingTask.destroy();\n }\n\n /**\n * @param {RefProxy} ref - The page reference.\n * @returns {number | null} The page number, if it's cached.\n */\n cachedPageNumber(ref) {\n return this._transport.cachedPageNumber(ref);\n }\n\n /**\n * @type {DocumentInitParameters} A subset of the current\n * {DocumentInitParameters}, which are needed in the viewer.\n */\n get loadingParams() {\n return this._transport.loadingParams;\n }\n\n /**\n * @type {PDFDocumentLoadingTask} The loadingTask for the current document.\n */\n get loadingTask() {\n return this._transport.loadingTask;\n }\n\n /**\n * @returns {Promise> | null>} A promise that is\n * resolved with an {Object} containing /AcroForm field data for the JS\n * sandbox, or `null` when no field data is present in the PDF file.\n */\n getFieldObjects() {\n return this._transport.getFieldObjects();\n }\n\n /**\n * @returns {Promise} A promise that is resolved with `true`\n * if some /AcroForm fields have JavaScript actions.\n */\n hasJSActions() {\n return this._transport.hasJSActions();\n }\n\n /**\n * @returns {Promise | null>} A promise that is resolved with an\n * {Array} containing IDs of annotations that have a calculation\n * action, or `null` when no such annotations are present in the PDF file.\n */\n getCalculationOrderIds() {\n return this._transport.getCalculationOrderIds();\n }\n}\n\n/**\n * Page getViewport parameters.\n *\n * @typedef {Object} GetViewportParameters\n * @property {number} scale - The desired scale of the viewport.\n * @property {number} [rotation] - The desired rotation, in degrees, of\n * the viewport. If omitted it defaults to the page rotation.\n * @property {number} [offsetX] - The horizontal, i.e. x-axis, offset.\n * The default value is `0`.\n * @property {number} [offsetY] - The vertical, i.e. y-axis, offset.\n * The default value is `0`.\n * @property {boolean} [dontFlip] - If true, the y-axis will not be\n * flipped. The default value is `false`.\n */\n\n/**\n * Page getTextContent parameters.\n *\n * @typedef {Object} getTextContentParameters\n * @property {boolean} [includeMarkedContent] - When true include marked\n * content items in the items array of TextContent. The default is `false`.\n * @property {boolean} [disableNormalization] - When true the text is *not*\n * normalized in the worker-thread. The default is `false`.\n */\n\n/**\n * Page text content.\n *\n * @typedef {Object} TextContent\n * @property {Array} items - Array of\n * {@link TextItem} and {@link TextMarkedContent} objects. TextMarkedContent\n * items are included when includeMarkedContent is true.\n * @property {Object} styles - {@link TextStyle} objects,\n * indexed by font name.\n * @property {string | null} lang - The document /Lang attribute.\n */\n\n/**\n * Page text content part.\n *\n * @typedef {Object} TextItem\n * @property {string} str - Text content.\n * @property {string} dir - Text direction: 'ttb', 'ltr' or 'rtl'.\n * @property {Array} transform - Transformation matrix.\n * @property {number} width - Width in device space.\n * @property {number} height - Height in device space.\n * @property {string} fontName - Font name used by PDF.js for converted font.\n * @property {boolean} hasEOL - Indicating if the text content is followed by a\n * line-break.\n */\n\n/**\n * Page text marked content part.\n *\n * @typedef {Object} TextMarkedContent\n * @property {string} type - Either 'beginMarkedContent',\n * 'beginMarkedContentProps', or 'endMarkedContent'.\n * @property {string} id - The marked content identifier. Only used for type\n * 'beginMarkedContentProps'.\n */\n\n/**\n * Text style.\n *\n * @typedef {Object} TextStyle\n * @property {number} ascent - Font ascent.\n * @property {number} descent - Font descent.\n * @property {boolean} vertical - Whether or not the text is in vertical mode.\n * @property {string} fontFamily - The possible font family.\n */\n\n/**\n * Page annotation parameters.\n *\n * @typedef {Object} GetAnnotationsParameters\n * @property {string} [intent] - Determines the annotations that are fetched,\n * can be 'display' (viewable annotations), 'print' (printable annotations),\n * or 'any' (all annotations). The default value is 'display'.\n */\n\n/**\n * Page render parameters.\n *\n * @typedef {Object} RenderParameters\n * @property {CanvasRenderingContext2D} canvasContext - A 2D context of a DOM\n * Canvas object.\n * @property {PageViewport} viewport - Rendering viewport obtained by calling\n * the `PDFPageProxy.getViewport` method.\n * @property {string} [intent] - Rendering intent, can be 'display', 'print',\n * or 'any'. The default value is 'display'.\n * @property {number} [annotationMode] Controls which annotations are rendered\n * onto the canvas, for annotations with appearance-data; the values from\n * {@link AnnotationMode} should be used. The following values are supported:\n * - `AnnotationMode.DISABLE`, which disables all annotations.\n * - `AnnotationMode.ENABLE`, which includes all possible annotations (thus\n * it also depends on the `intent`-option, see above).\n * - `AnnotationMode.ENABLE_FORMS`, which excludes annotations that contain\n * interactive form elements (those will be rendered in the display layer).\n * - `AnnotationMode.ENABLE_STORAGE`, which includes all possible annotations\n * (as above) but where interactive form elements are updated with data\n * from the {@link AnnotationStorage}-instance; useful e.g. for printing.\n * The default value is `AnnotationMode.ENABLE`.\n * @property {Array} [transform] - Additional transform, applied just\n * before viewport transform.\n * @property {CanvasGradient | CanvasPattern | string} [background] - Background\n * to use for the canvas.\n * Any valid `canvas.fillStyle` can be used: a `DOMString` parsed as CSS\n * value, a `CanvasGradient` object (a linear or radial gradient) or\n * a `CanvasPattern` object (a repetitive image). The default value is\n * 'rgb(255,255,255)'.\n *\n * NOTE: This option may be partially, or completely, ignored when the\n * `pageColors`-option is used.\n * @property {Object} [pageColors] - Overwrites background and foreground colors\n * with user defined ones in order to improve readability in high contrast\n * mode.\n * @property {Promise} [optionalContentConfigPromise] -\n * A promise that should resolve with an {@link OptionalContentConfig}\n * created from `PDFDocumentProxy.getOptionalContentConfig`. If `null`,\n * the configuration will be fetched automatically with the default visibility\n * states set.\n * @property {Map} [annotationCanvasMap] - Map some\n * annotation ids with canvases used to render them.\n * @property {PrintAnnotationStorage} [printAnnotationStorage]\n * @property {boolean} [isEditing] - Render the page in editing mode.\n */\n\n/**\n * Page getOperatorList parameters.\n *\n * @typedef {Object} GetOperatorListParameters\n * @property {string} [intent] - Rendering intent, can be 'display', 'print',\n * or 'any'. The default value is 'display'.\n * @property {number} [annotationMode] Controls which annotations are included\n * in the operatorList, for annotations with appearance-data; the values from\n * {@link AnnotationMode} should be used. The following values are supported:\n * - `AnnotationMode.DISABLE`, which disables all annotations.\n * - `AnnotationMode.ENABLE`, which includes all possible annotations (thus\n * it also depends on the `intent`-option, see above).\n * - `AnnotationMode.ENABLE_FORMS`, which excludes annotations that contain\n * interactive form elements (those will be rendered in the display layer).\n * - `AnnotationMode.ENABLE_STORAGE`, which includes all possible annotations\n * (as above) but where interactive form elements are updated with data\n * from the {@link AnnotationStorage}-instance; useful e.g. for printing.\n * The default value is `AnnotationMode.ENABLE`.\n * @property {PrintAnnotationStorage} [printAnnotationStorage]\n * @property {boolean} [isEditing] - Render the page in editing mode.\n */\n\n/**\n * Structure tree node. The root node will have a role \"Root\".\n *\n * @typedef {Object} StructTreeNode\n * @property {Array} children - Array of\n * {@link StructTreeNode} and {@link StructTreeContent} objects.\n * @property {string} role - element's role, already mapped if a role map exists\n * in the PDF.\n */\n\n/**\n * Structure tree content.\n *\n * @typedef {Object} StructTreeContent\n * @property {string} type - either \"content\" for page and stream structure\n * elements or \"object\" for object references.\n * @property {string} id - unique id that will map to the text layer.\n */\n\n/**\n * PDF page operator list.\n *\n * @typedef {Object} PDFOperatorList\n * @property {Array} fnArray - Array containing the operator functions.\n * @property {Array} argsArray - Array containing the arguments of the\n * functions.\n */\n\n/**\n * Proxy to a `PDFPage` in the worker thread.\n */\nclass PDFPageProxy {\n #delayedCleanupTimeout = null;\n\n #pendingCleanup = false;\n\n constructor(pageIndex, pageInfo, transport, pdfBug = false) {\n this._pageIndex = pageIndex;\n this._pageInfo = pageInfo;\n this._transport = transport;\n this._stats = pdfBug ? new StatTimer() : null;\n this._pdfBug = pdfBug;\n /** @type {PDFObjects} */\n this.commonObjs = transport.commonObjs;\n this.objs = new PDFObjects();\n\n this._maybeCleanupAfterRender = false;\n this._intentStates = new Map();\n this.destroyed = false;\n }\n\n /**\n * @type {number} Page number of the page. First page is 1.\n */\n get pageNumber() {\n return this._pageIndex + 1;\n }\n\n /**\n * @type {number} The number of degrees the page is rotated clockwise.\n */\n get rotate() {\n return this._pageInfo.rotate;\n }\n\n /**\n * @type {RefProxy | null} The reference that points to this page.\n */\n get ref() {\n return this._pageInfo.ref;\n }\n\n /**\n * @type {number} The default size of units in 1/72nds of an inch.\n */\n get userUnit() {\n return this._pageInfo.userUnit;\n }\n\n /**\n * @type {Array} An array of the visible portion of the PDF page in\n * user space units [x1, y1, x2, y2].\n */\n get view() {\n return this._pageInfo.view;\n }\n\n /**\n * @param {GetViewportParameters} params - Viewport parameters.\n * @returns {PageViewport} Contains 'width' and 'height' properties\n * along with transforms required for rendering.\n */\n getViewport({\n scale,\n rotation = this.rotate,\n offsetX = 0,\n offsetY = 0,\n dontFlip = false,\n } = {}) {\n return new PageViewport({\n viewBox: this.view,\n scale,\n rotation,\n offsetX,\n offsetY,\n dontFlip,\n });\n }\n\n /**\n * @param {GetAnnotationsParameters} [params] - Annotation parameters.\n * @returns {Promise>} A promise that is resolved with an\n * {Array} of the annotation objects.\n */\n getAnnotations({ intent = \"display\" } = {}) {\n const { renderingIntent } = this._transport.getRenderingIntent(intent);\n\n return this._transport.getAnnotations(this._pageIndex, renderingIntent);\n }\n\n /**\n * @returns {Promise} A promise that is resolved with an\n * {Object} with JS actions.\n */\n getJSActions() {\n return this._transport.getPageJSActions(this._pageIndex);\n }\n\n /**\n * @type {Object} The filter factory instance.\n */\n get filterFactory() {\n return this._transport.filterFactory;\n }\n\n /**\n * @type {boolean} True if only XFA form.\n */\n get isPureXfa() {\n return shadow(this, \"isPureXfa\", !!this._transport._htmlForXfa);\n }\n\n /**\n * @returns {Promise} A promise that is resolved with\n * an {Object} with a fake DOM object (a tree structure where elements\n * are {Object} with a name, attributes (class, style, ...), value and\n * children, very similar to a HTML DOM tree), or `null` if no XFA exists.\n */\n async getXfa() {\n return this._transport._htmlForXfa?.children[this._pageIndex] || null;\n }\n\n /**\n * Begins the process of rendering a page to the desired context.\n *\n * @param {RenderParameters} params - Page render parameters.\n * @returns {RenderTask} An object that contains a promise that is\n * resolved when the page finishes rendering.\n */\n render({\n canvasContext,\n viewport,\n intent = \"display\",\n annotationMode = AnnotationMode.ENABLE,\n transform = null,\n background = null,\n optionalContentConfigPromise = null,\n annotationCanvasMap = null,\n pageColors = null,\n printAnnotationStorage = null,\n isEditing = false,\n }) {\n this._stats?.time(\"Overall\");\n\n const intentArgs = this._transport.getRenderingIntent(\n intent,\n annotationMode,\n printAnnotationStorage,\n isEditing\n );\n const { renderingIntent, cacheKey } = intentArgs;\n // If there was a pending destroy, cancel it so no cleanup happens during\n // this call to render...\n this.#pendingCleanup = false;\n // ... and ensure that a delayed cleanup is always aborted.\n this.#abortDelayedCleanup();\n\n optionalContentConfigPromise ||=\n this._transport.getOptionalContentConfig(renderingIntent);\n\n let intentState = this._intentStates.get(cacheKey);\n if (!intentState) {\n intentState = Object.create(null);\n this._intentStates.set(cacheKey, intentState);\n }\n\n // Ensure that a pending `streamReader` cancel timeout is always aborted.\n if (intentState.streamReaderCancelTimeout) {\n clearTimeout(intentState.streamReaderCancelTimeout);\n intentState.streamReaderCancelTimeout = null;\n }\n\n const intentPrint = !!(renderingIntent & RenderingIntentFlag.PRINT);\n\n // If there's no displayReadyCapability yet, then the operatorList\n // was never requested before. Make the request and create the promise.\n if (!intentState.displayReadyCapability) {\n intentState.displayReadyCapability = Promise.withResolvers();\n intentState.operatorList = {\n fnArray: [],\n argsArray: [],\n lastChunk: false,\n separateAnnots: null,\n };\n\n this._stats?.time(\"Page Request\");\n this._pumpOperatorList(intentArgs);\n }\n\n const complete = error => {\n intentState.renderTasks.delete(internalRenderTask);\n\n // Attempt to reduce memory usage during *printing*, by always running\n // cleanup immediately once rendering has finished.\n if (this._maybeCleanupAfterRender || intentPrint) {\n this.#pendingCleanup = true;\n }\n this.#tryCleanup(/* delayed = */ !intentPrint);\n\n if (error) {\n internalRenderTask.capability.reject(error);\n\n this._abortOperatorList({\n intentState,\n reason: error instanceof Error ? error : new Error(error),\n });\n } else {\n internalRenderTask.capability.resolve();\n }\n\n if (this._stats) {\n this._stats.timeEnd(\"Rendering\");\n this._stats.timeEnd(\"Overall\");\n\n if (globalThis.Stats?.enabled) {\n globalThis.Stats.add(this.pageNumber, this._stats);\n }\n }\n };\n\n const internalRenderTask = new InternalRenderTask({\n callback: complete,\n // Only include the required properties, and *not* the entire object.\n params: {\n canvasContext,\n viewport,\n transform,\n background,\n },\n objs: this.objs,\n commonObjs: this.commonObjs,\n annotationCanvasMap,\n operatorList: intentState.operatorList,\n pageIndex: this._pageIndex,\n canvasFactory: this._transport.canvasFactory,\n filterFactory: this._transport.filterFactory,\n useRequestAnimationFrame: !intentPrint,\n pdfBug: this._pdfBug,\n pageColors,\n });\n\n (intentState.renderTasks ||= new Set()).add(internalRenderTask);\n const renderTask = internalRenderTask.task;\n\n Promise.all([\n intentState.displayReadyCapability.promise,\n optionalContentConfigPromise,\n ])\n .then(([transparency, optionalContentConfig]) => {\n if (this.destroyed) {\n complete();\n return;\n }\n this._stats?.time(\"Rendering\");\n\n if (!(optionalContentConfig.renderingIntent & renderingIntent)) {\n throw new Error(\n \"Must use the same `intent`-argument when calling the `PDFPageProxy.render` \" +\n \"and `PDFDocumentProxy.getOptionalContentConfig` methods.\"\n );\n }\n internalRenderTask.initializeGraphics({\n transparency,\n optionalContentConfig,\n });\n internalRenderTask.operatorListChanged();\n })\n .catch(complete);\n\n return renderTask;\n }\n\n /**\n * @param {GetOperatorListParameters} params - Page getOperatorList\n * parameters.\n * @returns {Promise} A promise resolved with an\n * {@link PDFOperatorList} object that represents the page's operator list.\n */\n getOperatorList({\n intent = \"display\",\n annotationMode = AnnotationMode.ENABLE,\n printAnnotationStorage = null,\n isEditing = false,\n } = {}) {\n if (typeof PDFJSDev !== \"undefined\" && !PDFJSDev.test(\"GENERIC\")) {\n throw new Error(\"Not implemented: getOperatorList\");\n }\n function operatorListChanged() {\n if (intentState.operatorList.lastChunk) {\n intentState.opListReadCapability.resolve(intentState.operatorList);\n\n intentState.renderTasks.delete(opListTask);\n }\n }\n\n const intentArgs = this._transport.getRenderingIntent(\n intent,\n annotationMode,\n printAnnotationStorage,\n isEditing,\n /* isOpList = */ true\n );\n let intentState = this._intentStates.get(intentArgs.cacheKey);\n if (!intentState) {\n intentState = Object.create(null);\n this._intentStates.set(intentArgs.cacheKey, intentState);\n }\n let opListTask;\n\n if (!intentState.opListReadCapability) {\n opListTask = Object.create(null);\n opListTask.operatorListChanged = operatorListChanged;\n intentState.opListReadCapability = Promise.withResolvers();\n (intentState.renderTasks ||= new Set()).add(opListTask);\n intentState.operatorList = {\n fnArray: [],\n argsArray: [],\n lastChunk: false,\n separateAnnots: null,\n };\n\n this._stats?.time(\"Page Request\");\n this._pumpOperatorList(intentArgs);\n }\n return intentState.opListReadCapability.promise;\n }\n\n /**\n * NOTE: All occurrences of whitespace will be replaced by\n * standard spaces (0x20).\n *\n * @param {getTextContentParameters} params - getTextContent parameters.\n * @returns {ReadableStream} Stream for reading text content chunks.\n */\n streamTextContent({\n includeMarkedContent = false,\n disableNormalization = false,\n } = {}) {\n const TEXT_CONTENT_CHUNK_SIZE = 100;\n\n return this._transport.messageHandler.sendWithStream(\n \"GetTextContent\",\n {\n pageIndex: this._pageIndex,\n includeMarkedContent: includeMarkedContent === true,\n disableNormalization: disableNormalization === true,\n },\n {\n highWaterMark: TEXT_CONTENT_CHUNK_SIZE,\n size(textContent) {\n return textContent.items.length;\n },\n }\n );\n }\n\n /**\n * NOTE: All occurrences of whitespace will be replaced by\n * standard spaces (0x20).\n *\n * @param {getTextContentParameters} params - getTextContent parameters.\n * @returns {Promise} A promise that is resolved with a\n * {@link TextContent} object that represents the page's text content.\n */\n getTextContent(params = {}) {\n if (this._transport._htmlForXfa) {\n // TODO: We need to revisit this once the XFA foreground patch lands and\n // only do this for non-foreground XFA.\n return this.getXfa().then(xfa => XfaText.textContent(xfa));\n }\n const readableStream = this.streamTextContent(params);\n\n return new Promise(function (resolve, reject) {\n function pump() {\n reader.read().then(function ({ value, done }) {\n if (done) {\n resolve(textContent);\n return;\n }\n textContent.lang ??= value.lang;\n Object.assign(textContent.styles, value.styles);\n textContent.items.push(...value.items);\n pump();\n }, reject);\n }\n\n const reader = readableStream.getReader();\n const textContent = {\n items: [],\n styles: Object.create(null),\n lang: null,\n };\n pump();\n });\n }\n\n /**\n * @returns {Promise} A promise that is resolved with a\n * {@link StructTreeNode} object that represents the page's structure tree,\n * or `null` when no structure tree is present for the current page.\n */\n getStructTree() {\n return this._transport.getStructTree(this._pageIndex);\n }\n\n /**\n * Destroys the page object.\n * @private\n */\n _destroy() {\n this.destroyed = true;\n\n const waitOn = [];\n for (const intentState of this._intentStates.values()) {\n this._abortOperatorList({\n intentState,\n reason: new Error(\"Page was destroyed.\"),\n force: true,\n });\n\n if (intentState.opListReadCapability) {\n // Avoid errors below, since the renderTasks are just stubs.\n continue;\n }\n for (const internalRenderTask of intentState.renderTasks) {\n waitOn.push(internalRenderTask.completed);\n internalRenderTask.cancel();\n }\n }\n this.objs.clear();\n this.#pendingCleanup = false;\n this.#abortDelayedCleanup();\n\n return Promise.all(waitOn);\n }\n\n /**\n * Cleans up resources allocated by the page.\n *\n * @param {boolean} [resetStats] - Reset page stats, if enabled.\n * The default value is `false`.\n * @returns {boolean} Indicates if clean-up was successfully run.\n */\n cleanup(resetStats = false) {\n this.#pendingCleanup = true;\n const success = this.#tryCleanup(/* delayed = */ false);\n\n if (resetStats && success) {\n this._stats &&= new StatTimer();\n }\n return success;\n }\n\n /**\n * Attempts to clean up if rendering is in a state where that's possible.\n * @param {boolean} [delayed] - Delay the cleanup, to e.g. improve zooming\n * performance in documents with large images.\n * The default value is `false`.\n * @returns {boolean} Indicates if clean-up was successfully run.\n */\n #tryCleanup(delayed = false) {\n this.#abortDelayedCleanup();\n\n if (!this.#pendingCleanup || this.destroyed) {\n return false;\n }\n if (delayed) {\n this.#delayedCleanupTimeout = setTimeout(() => {\n this.#delayedCleanupTimeout = null;\n this.#tryCleanup(/* delayed = */ false);\n }, DELAYED_CLEANUP_TIMEOUT);\n\n return false;\n }\n for (const { renderTasks, operatorList } of this._intentStates.values()) {\n if (renderTasks.size > 0 || !operatorList.lastChunk) {\n return false;\n }\n }\n this._intentStates.clear();\n this.objs.clear();\n this.#pendingCleanup = false;\n return true;\n }\n\n #abortDelayedCleanup() {\n if (this.#delayedCleanupTimeout) {\n clearTimeout(this.#delayedCleanupTimeout);\n this.#delayedCleanupTimeout = null;\n }\n }\n\n /**\n * @private\n */\n _startRenderPage(transparency, cacheKey) {\n const intentState = this._intentStates.get(cacheKey);\n if (!intentState) {\n return; // Rendering was cancelled.\n }\n this._stats?.timeEnd(\"Page Request\");\n\n // TODO Refactor RenderPageRequest to separate rendering\n // and operator list logic\n intentState.displayReadyCapability?.resolve(transparency);\n }\n\n /**\n * @private\n */\n _renderPageChunk(operatorListChunk, intentState) {\n // Add the new chunk to the current operator list.\n for (let i = 0, ii = operatorListChunk.length; i < ii; i++) {\n intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);\n intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);\n }\n intentState.operatorList.lastChunk = operatorListChunk.lastChunk;\n intentState.operatorList.separateAnnots = operatorListChunk.separateAnnots;\n\n // Notify all the rendering tasks there are more operators to be consumed.\n for (const internalRenderTask of intentState.renderTasks) {\n internalRenderTask.operatorListChanged();\n }\n\n if (operatorListChunk.lastChunk) {\n this.#tryCleanup(/* delayed = */ true);\n }\n }\n\n /**\n * @private\n */\n _pumpOperatorList({\n renderingIntent,\n cacheKey,\n annotationStorageSerializable,\n modifiedIds,\n }) {\n if (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) {\n assert(\n Number.isInteger(renderingIntent) && renderingIntent > 0,\n '_pumpOperatorList: Expected valid \"renderingIntent\" argument.'\n );\n }\n const { map, transfer } = annotationStorageSerializable;\n\n const readableStream = this._transport.messageHandler.sendWithStream(\n \"GetOperatorList\",\n {\n pageIndex: this._pageIndex,\n intent: renderingIntent,\n cacheKey,\n annotationStorage: map,\n modifiedIds,\n },\n transfer\n );\n const reader = readableStream.getReader();\n\n const intentState = this._intentStates.get(cacheKey);\n intentState.streamReader = reader;\n\n const pump = () => {\n reader.read().then(\n ({ value, done }) => {\n if (done) {\n intentState.streamReader = null;\n return;\n }\n if (this._transport.destroyed) {\n return; // Ignore any pending requests if the worker was terminated.\n }\n this._renderPageChunk(value, intentState);\n pump();\n },\n reason => {\n intentState.streamReader = null;\n\n if (this._transport.destroyed) {\n return; // Ignore any pending requests if the worker was terminated.\n }\n if (intentState.operatorList) {\n // Mark operator list as complete.\n intentState.operatorList.lastChunk = true;\n\n for (const internalRenderTask of intentState.renderTasks) {\n internalRenderTask.operatorListChanged();\n }\n this.#tryCleanup(/* delayed = */ true);\n }\n\n if (intentState.displayReadyCapability) {\n intentState.displayReadyCapability.reject(reason);\n } else if (intentState.opListReadCapability) {\n intentState.opListReadCapability.reject(reason);\n } else {\n throw reason;\n }\n }\n );\n };\n pump();\n }\n\n /**\n * @private\n */\n _abortOperatorList({ intentState, reason, force = false }) {\n if (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) {\n assert(\n reason instanceof Error,\n '_abortOperatorList: Expected valid \"reason\" argument.'\n );\n }\n\n if (!intentState.streamReader) {\n return;\n }\n // Ensure that a pending `streamReader` cancel timeout is always aborted.\n if (intentState.streamReaderCancelTimeout) {\n clearTimeout(intentState.streamReaderCancelTimeout);\n intentState.streamReaderCancelTimeout = null;\n }\n\n if (!force) {\n // Ensure that an Error occurring in *only* one `InternalRenderTask`, e.g.\n // multiple render() calls on the same canvas, won't break all rendering.\n if (intentState.renderTasks.size > 0) {\n return;\n }\n // Don't immediately abort parsing on the worker-thread when rendering is\n // cancelled, since that will unnecessarily delay re-rendering when (for\n // partially parsed pages) e.g. zooming/rotation occurs in the viewer.\n if (reason instanceof RenderingCancelledException) {\n let delay = RENDERING_CANCELLED_TIMEOUT;\n if (reason.extraDelay > 0 && reason.extraDelay < /* ms = */ 1000) {\n // Above, we prevent the total delay from becoming arbitrarily large.\n delay += reason.extraDelay;\n }\n\n intentState.streamReaderCancelTimeout = setTimeout(() => {\n intentState.streamReaderCancelTimeout = null;\n this._abortOperatorList({ intentState, reason, force: true });\n }, delay);\n return;\n }\n }\n intentState.streamReader\n .cancel(new AbortException(reason.message))\n .catch(() => {\n // Avoid \"Uncaught promise\" messages in the console.\n });\n intentState.streamReader = null;\n\n if (this._transport.destroyed) {\n return; // Ignore any pending requests if the worker was terminated.\n }\n // Remove the current `intentState`, since a cancelled `getOperatorList`\n // call on the worker-thread cannot be re-started...\n for (const [curCacheKey, curIntentState] of this._intentStates) {\n if (curIntentState === intentState) {\n this._intentStates.delete(curCacheKey);\n break;\n }\n }\n // ... and force clean-up to ensure that any old state is always removed.\n this.cleanup();\n }\n\n /**\n * @type {StatTimer | null} Returns page stats, if enabled; returns `null`\n * otherwise.\n */\n get stats() {\n return this._stats;\n }\n}\n\nclass LoopbackPort {\n #listeners = new Set();\n\n #deferred = Promise.resolve();\n\n postMessage(obj, transfer) {\n const event = {\n data: structuredClone(obj, transfer ? { transfer } : null),\n };\n\n this.#deferred.then(() => {\n for (const listener of this.#listeners) {\n listener.call(this, event);\n }\n });\n }\n\n addEventListener(name, listener) {\n this.#listeners.add(listener);\n }\n\n removeEventListener(name, listener) {\n this.#listeners.delete(listener);\n }\n\n terminate() {\n this.#listeners.clear();\n }\n}\n\n/**\n * @typedef {Object} PDFWorkerParameters\n * @property {string} [name] - The name of the worker.\n * @property {Worker} [port] - The `workerPort` object.\n * @property {number} [verbosity] - Controls the logging level;\n * the constants from {@link VerbosityLevel} should be used.\n */\n\n/**\n * PDF.js web worker abstraction that controls the instantiation of PDF\n * documents. Message handlers are used to pass information from the main\n * thread to the worker thread and vice versa. If the creation of a web\n * worker is not possible, a \"fake\" worker will be used instead.\n *\n * @param {PDFWorkerParameters} params - The worker initialization parameters.\n */\nclass PDFWorker {\n static #fakeWorkerId = 0;\n\n static #isWorkerDisabled = false;\n\n static #workerPorts;\n\n static {\n if (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"GENERIC\")) {\n if (isNodeJS) {\n // Workers aren't supported in Node.js, force-disabling them there.\n this.#isWorkerDisabled = true;\n\n GlobalWorkerOptions.workerSrc ||= PDFJSDev.test(\"LIB\")\n ? \"../pdf.worker.js\"\n : \"./pdf.worker.mjs\";\n }\n\n // Check if URLs have the same origin. For non-HTTP based URLs, returns\n // false.\n this._isSameOrigin = (baseUrl, otherUrl) => {\n let base;\n try {\n base = new URL(baseUrl);\n if (!base.origin || base.origin === \"null\") {\n return false; // non-HTTP url\n }\n } catch {\n return false;\n }\n const other = new URL(otherUrl, base);\n return base.origin === other.origin;\n };\n\n this._createCDNWrapper = url => {\n // We will rely on blob URL's property to specify origin.\n // We want this function to fail in case if createObjectURL or Blob do\n // not exist or fail for some reason -- our Worker creation will fail\n // anyway.\n const wrapper = `await import(\"${url}\");`;\n return URL.createObjectURL(\n new Blob([wrapper], { type: \"text/javascript\" })\n );\n };\n }\n }\n\n constructor({\n name = null,\n port = null,\n verbosity = getVerbosityLevel(),\n } = {}) {\n this.name = name;\n this.destroyed = false;\n this.verbosity = verbosity;\n\n this._readyCapability = Promise.withResolvers();\n this._port = null;\n this._webWorker = null;\n this._messageHandler = null;\n\n if (\n (typeof PDFJSDev === \"undefined\" || !PDFJSDev.test(\"MOZCENTRAL\")) &&\n port\n ) {\n if (PDFWorker.#workerPorts?.has(port)) {\n throw new Error(\"Cannot use more than one PDFWorker per port.\");\n }\n (PDFWorker.#workerPorts ||= new WeakMap()).set(port, this);\n this._initializeFromPort(port);\n return;\n }\n this._initialize();\n }\n\n /**\n * Promise for worker initialization completion.\n * @type {Promise}\n */\n get promise() {\n if (\n typeof PDFJSDev !== \"undefined\" &&\n PDFJSDev.test(\"GENERIC\") &&\n isNodeJS\n ) {\n // Ensure that all Node.js packages/polyfills have loaded.\n return Promise.all([NodePackages.promise, this._readyCapability.promise]);\n }\n return this._readyCapability.promise;\n }\n\n #resolve() {\n this._readyCapability.resolve();\n // Send global setting, e.g. verbosity level.\n this._messageHandler.send(\"configure\", {\n verbosity: this.verbosity,\n });\n }\n\n /**\n * The current `workerPort`, when it exists.\n * @type {Worker}\n */\n get port() {\n return this._port;\n }\n\n /**\n * The current MessageHandler-instance.\n * @type {MessageHandler}\n */\n get messageHandler() {\n return this._messageHandler;\n }\n\n _initializeFromPort(port) {\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n throw new Error(\"Not implemented: _initializeFromPort\");\n }\n this._port = port;\n this._messageHandler = new MessageHandler(\"main\", \"worker\", port);\n this._messageHandler.on(\"ready\", function () {\n // Ignoring \"ready\" event -- MessageHandler should already be initialized\n // and ready to accept messages.\n });\n this.#resolve();\n }\n\n _initialize() {\n // If worker support isn't disabled explicit and the browser has worker\n // support, create a new web worker and test if it/the browser fulfills\n // all requirements to run parts of pdf.js in a web worker.\n // Right now, the requirement is, that an Uint8Array is still an\n // Uint8Array as it arrives on the worker.\n if (\n PDFWorker.#isWorkerDisabled ||\n PDFWorker.#mainThreadWorkerMessageHandler\n ) {\n this._setupFakeWorker();\n return;\n }\n let { workerSrc } = PDFWorker;\n\n try {\n // Wraps workerSrc path into blob URL, if the former does not belong\n // to the same origin.\n if (\n typeof PDFJSDev !== \"undefined\" &&\n PDFJSDev.test(\"GENERIC\") &&\n !PDFWorker._isSameOrigin(window.location.href, workerSrc)\n ) {\n workerSrc = PDFWorker._createCDNWrapper(\n new URL(workerSrc, window.location).href\n );\n }\n\n const worker = new Worker(workerSrc, { type: \"module\" });\n const messageHandler = new MessageHandler(\"main\", \"worker\", worker);\n const terminateEarly = () => {\n ac.abort();\n messageHandler.destroy();\n worker.terminate();\n if (this.destroyed) {\n this._readyCapability.reject(new Error(\"Worker was destroyed\"));\n } else {\n // Fall back to fake worker if the termination is caused by an\n // error (e.g. NetworkError / SecurityError).\n this._setupFakeWorker();\n }\n };\n\n const ac = new AbortController();\n worker.addEventListener(\n \"error\",\n () => {\n if (!this._webWorker) {\n // Worker failed to initialize due to an error. Clean up and fall\n // back to the fake worker.\n terminateEarly();\n }\n },\n { signal: ac.signal }\n );\n\n messageHandler.on(\"test\", data => {\n ac.abort();\n if (this.destroyed || !data) {\n terminateEarly();\n return;\n }\n this._messageHandler = messageHandler;\n this._port = worker;\n this._webWorker = worker;\n\n this.#resolve();\n });\n\n messageHandler.on(\"ready\", data => {\n ac.abort();\n if (this.destroyed) {\n terminateEarly();\n return;\n }\n try {\n sendTest();\n } catch {\n // We need fallback to a faked worker.\n this._setupFakeWorker();\n }\n });\n\n const sendTest = () => {\n const testObj = new Uint8Array();\n // Ensure that we can use `postMessage` transfers.\n messageHandler.send(\"test\", testObj, [testObj.buffer]);\n };\n\n // It might take time for the worker to initialize. We will try to send\n // the \"test\" message immediately, and once the \"ready\" message arrives.\n // The worker shall process only the first received \"test\" message.\n sendTest();\n return;\n } catch {\n info(\"The worker has been disabled.\");\n }\n // Either workers are not supported or have thrown an exception.\n // Thus, we fallback to a faked worker.\n this._setupFakeWorker();\n }\n\n _setupFakeWorker() {\n if (!PDFWorker.#isWorkerDisabled) {\n warn(\"Setting up fake worker.\");\n PDFWorker.#isWorkerDisabled = true;\n }\n\n PDFWorker._setupFakeWorkerGlobal\n .then(WorkerMessageHandler => {\n if (this.destroyed) {\n this._readyCapability.reject(new Error(\"Worker was destroyed\"));\n return;\n }\n const port = new LoopbackPort();\n this._port = port;\n\n // All fake workers use the same port, making id unique.\n const id = `fake${PDFWorker.#fakeWorkerId++}`;\n\n // If the main thread is our worker, setup the handling for the\n // messages -- the main thread sends to it self.\n const workerHandler = new MessageHandler(id + \"_worker\", id, port);\n WorkerMessageHandler.setup(workerHandler, port);\n\n this._messageHandler = new MessageHandler(id, id + \"_worker\", port);\n this.#resolve();\n })\n .catch(reason => {\n this._readyCapability.reject(\n new Error(`Setting up fake worker failed: \"${reason.message}\".`)\n );\n });\n }\n\n /**\n * Destroys the worker instance.\n */\n destroy() {\n this.destroyed = true;\n if (this._webWorker) {\n // We need to terminate only web worker created resource.\n this._webWorker.terminate();\n this._webWorker = null;\n }\n PDFWorker.#workerPorts?.delete(this._port);\n this._port = null;\n if (this._messageHandler) {\n this._messageHandler.destroy();\n this._messageHandler = null;\n }\n }\n\n /**\n * @param {PDFWorkerParameters} params - The worker initialization parameters.\n */\n static fromPort(params) {\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n throw new Error(\"Not implemented: fromPort\");\n }\n if (!params?.port) {\n throw new Error(\"PDFWorker.fromPort - invalid method signature.\");\n }\n const cachedPort = this.#workerPorts?.get(params.port);\n if (cachedPort) {\n if (cachedPort._pendingDestroy) {\n throw new Error(\n \"PDFWorker.fromPort - the worker is being destroyed.\\n\" +\n \"Please remember to await `PDFDocumentLoadingTask.destroy()`-calls.\"\n );\n }\n return cachedPort;\n }\n return new PDFWorker(params);\n }\n\n /**\n * The current `workerSrc`, when it exists.\n * @type {string}\n */\n static get workerSrc() {\n if (GlobalWorkerOptions.workerSrc) {\n return GlobalWorkerOptions.workerSrc;\n }\n throw new Error('No \"GlobalWorkerOptions.workerSrc\" specified.');\n }\n\n static get #mainThreadWorkerMessageHandler() {\n try {\n return globalThis.pdfjsWorker?.WorkerMessageHandler || null;\n } catch {\n return null;\n }\n }\n\n // Loads worker code into the main-thread.\n static get _setupFakeWorkerGlobal() {\n const loader = async () => {\n if (this.#mainThreadWorkerMessageHandler) {\n // The worker was already loaded using e.g. a `